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

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

    135def generate_date_delta_with_unit_sql(
    136    self: TSQL.Generator, expression: exp.DateAdd | exp.DateDiff
    137) -> str:
    138    func = "DATEADD" if isinstance(expression, exp.DateAdd) else "DATEDIFF"
    139    return self.func(func, expression.text("unit"), expression.expression, expression.this)

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

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

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

##### Inherited Members

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

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

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'>, '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'>, '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'>, 'CLOB': <TokenType.TEXT: 'TEXT'>, 'LONGVARCHAR': <TokenType.TEXT: 'TEXT'>, 'BINARY': <TokenType.BINARY: 'BINARY'>, 'BLOB': <TokenType.VARBINARY: 'VARBINARY'>, 'BYTEA': <TokenType.VARBINARY: 'VARBINARY'>, 'VARBINARY': <TokenType.VARBINARY: 'VARBINARY'>, 'TIME': <TokenType.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
  IDENTIFIER_ESCAPES
  STRING_ESCAPES
  VAR_SINGLE_TOKENS
  IDENTIFIERS_CAN_START_WITH_DIGIT
  WHITE_SPACE
  COMMANDS
  COMMAND_PREFIX_TOKENS
  NUMERIC_LITERALS
  ENCODE
  COMMENTS
  reset
  tokenize
  peek
  size
  sql
  tokens

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

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

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

###### Arguments:

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

FUNCTIONS = {'ABS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Abs'>>, 'ANY_VALUE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.AnyValue'>>, 'APPROX_DISTINCT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxDistinct'>>, 'APPROX_COUNT_DISTINCT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxDistinct'>>, 'APPROX_QUANTILE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxQuantile'>>, 'ARRAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Array'>>, 'ARRAY_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayAgg'>>, 'ARRAY_ALL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayAll'>>, 'ARRAY_ANY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayAny'>>, 'ARRAY_CONCAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayConcat'>>, 'ARRAY_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'>>, 'COALESCE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'IFNULL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'NVL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'CONCAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Concat'>>, 'CONCAT_WS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ConcatWs'>>, 'COUNT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Count'>>, 'COUNT_IF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CountIf'>>, 'CURRENT_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentDate'>>, 'CURRENT_DATETIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentDatetime'>>, 'CURRENT_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentTime'>>, 'CURRENT_TIMESTAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentTimestamp'>>, 'CURRENT_USER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentUser'>>, 'DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Date'>>, 'DATE_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateAdd'>>, 'DATEDIFF': <function _parse_date_delta.<locals>.inner_func>, 'DATE_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateDiff'>>, 'DATEFROMPARTS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateFromParts'>>, 'DATE_STR_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateStrToDate'>>, 'DATE_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateSub'>>, 'DATE_TO_DATE_STR': <function Parser.<lambda>>, 'DATE_TO_DI': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateToDi'>>, 'DATE_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateTrunc'>>, 'DATETIME_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeAdd'>>, 'DATETIME_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeDiff'>>, 'DATETIME_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeSub'>>, 'DATETIME_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeTrunc'>>, 'DAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Day'>>, 'DAY_OF_MONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfMonth'>>, 'DAYOFMONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfMonth'>>, 'DAY_OF_WEEK': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfWeek'>>, 'DAYOFWEEK': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfWeek'>>, 'DAY_OF_YEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfYear'>>, 'DAYOFYEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfYear'>>, 'DECODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Decode'>>, 'DI_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DiToDate'>>, 'ENCODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Encode'>>, 'EXP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Exp'>>, 'EXPLODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Explode'>>, 'EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Extract'>>, 'FIRST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.First'>>, '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'>>, 'JSON_ARRAY_CONTAINS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONArrayContains'>>, 'JSONB_EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONBExtract'>>, 'JSONB_EXTRACT_SCALAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONBExtractScalar'>>, 'JSON_EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONExtract'>>, 'JSON_EXTRACT_SCALAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONExtractScalar'>>, 'JSON_FORMAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONFormat'>>, 'J_S_O_N_OBJECT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONObject'>>, 'LAST': <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'>>, 'PERCENTILE_CONT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.PercentileCont'>>, 'PERCENTILE_DISC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.PercentileDisc'>>, 'POSEXPLODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Posexplode'>>, 'POWER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Pow'>>, 'POW': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Pow'>>, 'QUANTILE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Quantile'>>, 'RANGE_N': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RangeN'>>, 'READ_CSV': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ReadCSV'>>, 'REDUCE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Reduce'>>, 'REGEXP_EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpExtract'>>, 'REGEXP_I_LIKE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpILike'>>, 'REGEXP_LIKE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpLike'>>, 'REGEXP_REPLACE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpReplace'>>, 'REGEXP_SPLIT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpSplit'>>, 'REPEAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Repeat'>>, 'RIGHT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Right'>>, 'ROUND': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Round'>>, 'ROW_NUMBER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RowNumber'>>, 'SHA': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SHA'>>, 'SHA1': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SHA'>>, 'SHA2': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SHA2'>>, 'SAFE_CONCAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SafeConcat'>>, 'SAFE_DIVIDE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SafeDivide'>>, 'SET_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SetAgg'>>, 'SORT_ARRAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SortArray'>>, 'SPLIT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Split'>>, 'SQRT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Sqrt'>>, 'STANDARD_HASH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StandardHash'>>, 'STAR_MAP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StarMap'>>, '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_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'>>, '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 = {'HASH', 'LOOP', 'REMOTE', 'MERGE'}
VAR_LENGTH_DATATYPES = {<Type.VARCHAR: 'VARCHAR'>, <Type.NVARCHAR: 'NVARCHAR'>, <Type.CHAR: 'CHAR'>, <Type.NCHAR: 'NCHAR'>}
RETURNS_TABLE_TOKENS = {<TokenType.LOAD: 'LOAD'>, <TokenType.ORDINALITY: 'ORDINALITY'>, <TokenType.REFERENCES: 'REFERENCES'>, <TokenType.DELETE: 'DELETE'>, <TokenType.PROCEDURE: 'PROCEDURE'>, <TokenType.LEFT: 'LEFT'>, <TokenType.ROW: 'ROW'>, <TokenType.UNIQUE: 'UNIQUE'>, <TokenType.FIRST: 'FIRST'>, <TokenType.SOME: 'SOME'>, <TokenType.IS: 'IS'>, <TokenType.COLLATE: 'COLLATE'>, <TokenType.MERGE: 'MERGE'>, <TokenType.WINDOW: 'WINDOW'>, <TokenType.SEMI: 'SEMI'>, <TokenType.SHOW: 'SHOW'>, <TokenType.INDEX: 'INDEX'>, <TokenType.TOP: 'TOP'>, <TokenType.SCHEMA: 'SCHEMA'>, <TokenType.DIV: 'DIV'>, <TokenType.COMMENT: 'COMMENT'>, <TokenType.CONSTRAINT: 'CONSTRAINT'>, <TokenType.DESC: 'DESC'>, <TokenType.ASC: 'ASC'>, <TokenType.APPLY: 'APPLY'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.FILTER: 'FILTER'>, <TokenType.VIEW: 'VIEW'>, <TokenType.ANY: 'ANY'>, <TokenType.DICTIONARY: 'DICTIONARY'>, <TokenType.ALL: 'ALL'>, <TokenType.VAR: 'VAR'>, <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>, <TokenType.UNPIVOT: 'UNPIVOT'>, <TokenType.OFFSET: 'OFFSET'>, <TokenType.RIGHT: 'RIGHT'>, <TokenType.NEXT: 'NEXT'>, <TokenType.SET: 'SET'>, <TokenType.ROWS: 'ROWS'>, <TokenType.END: 'END'>, <TokenType.SETTINGS: 'SETTINGS'>, <TokenType.EXISTS: 'EXISTS'>, <TokenType.ANTI: 'ANTI'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.TEMPORARY: 'TEMPORARY'>, <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, <TokenType.TRUE: 'TRUE'>, <TokenType.UPDATE: 'UPDATE'>, <TokenType.DATABASE: 'DATABASE'>, <TokenType.FULL: 'FULL'>, <TokenType.VOLATILE: 'VOLATILE'>, <TokenType.PRAGMA: 'PRAGMA'>, <TokenType.DESCRIBE: 'DESCRIBE'>, <TokenType.COMMIT: 'COMMIT'>, <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, <TokenType.ESCAPE: 'ESCAPE'>, <TokenType.CASE: 'CASE'>, <TokenType.ISNULL: 'ISNULL'>, <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, <TokenType.COLUMN: 'COLUMN'>, <TokenType.BEGIN: 'BEGIN'>, <TokenType.FUNCTION: 'FUNCTION'>, <TokenType.PARTITION: 'PARTITION'>, <TokenType.OVERWRITE: 'OVERWRITE'>, <TokenType.CURRENT_USER: 'CURRENT_USER'>, <TokenType.CACHE: 'CACHE'>, <TokenType.NATURAL: 'NATURAL'>, <TokenType.FALSE: 'FALSE'>, <TokenType.FORMAT: 'FORMAT'>, <TokenType.DEFAULT: 'DEFAULT'>, <TokenType.RANGE: 'RANGE'>, <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, <TokenType.PERCENT: 'PERCENT'>, <TokenType.PIVOT: 'PIVOT'>, <TokenType.KEEP: 'KEEP'>}
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.LOAD: 'LOAD'>: <function Parser.<lambda>>, <TokenType.MERGE: 'MERGE'>: <function Parser.<lambda>>, <TokenType.PIVOT: 'PIVOT'>: <function Parser.<lambda>>, <TokenType.PRAGMA: 'PRAGMA'>: <function Parser.<lambda>>, <TokenType.ROLLBACK: 'ROLLBACK'>: <function Parser.<lambda>>, <TokenType.SET: 'SET'>: <function Parser.<lambda>>, <TokenType.UNCACHE: 'UNCACHE'>: <function Parser.<lambda>>, <TokenType.UPDATE: 'UPDATE'>: <function Parser.<lambda>>, <TokenType.USE: 'USE'>: <function Parser.<lambda>>, <TokenType.END: 'END'>: <function TSQL.Parser.<lambda>>}
LOG_BASE_FIRST = False
LOG_DEFAULTS_TO_LN = True
CONCAT_NULL_OUTPUTS_STRING = True
ALTER_TABLE_ADD_COLUMN_KEYWORD = False
TOKENIZER_CLASS: Type[sqlglot.tokens.Tokenizer] = <class 'sqlglot.dialects.tsql.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': {0: True}, 0: True}, 'w': {'e': {'e': {'k': {0: True, 'd': {'a': {'y': {0: True}}}}}}, 'w': {0: True}, 'k': {0: True}}, 'h': {'o': {'u': {'r': {0: True}}}, 'h': {0: True}, 0: True}, 'm': {'i': {'n': {'u': {'t': {'e': {0: True}}}}, 0: True, 'l': {'l': {'i': {'s': {'e': {'c': {'o': {'n': {'d': {0: True}}}}}}}}}}, 's': {0: True}, 'o': {'n': {'t': {'h': {0: True}}}}, 'm': {0: True}, 0: True}, 'n': {0: True}, 's': {'e': {'c': {'o': {'n': {'d': {0: True}}}}}, 's': {0: True}, 0: True}, 'Y': {0: True, 'Y': {'Y': {'Y': {0: True}}, 0: True}}, 'M': {'M': {'M': {'M': {0: True}, 0: True}, 0: True}, 0: True}, 'H': {'H': {0: True}, 0: True}, 'S': {0: True}}
TIME_MAPPING: Dict[str, str] = {'year': '%Y', 'qq': '%q', 'q': '%q', 'quarter': '%q', 'dayofyear': '%j', 'day': '%d', 'dy': '%d', 'y': '%Y', 'week': '%W', 'ww': '%W', 'wk': '%W', 'hour': '%h', 'hh': '%I', 'minute': '%M', 'mi': '%M', 'n': '%M', 'second': '%S', 'ss': '%S', 's': '%-S', 'millisecond': '%f', 'ms': '%f', 'weekday': '%W', 'dw': '%W', 'month': '%m', 'mm': '%M', 'm': '%-M', 'Y': '%Y', 'YYYY': '%Y', 'YY': '%y', 'MMMM': '%B', 'MMM': '%b', 'MM': '%m', 'M': '%-m', 'dd': '%d', 'd': '%-d', 'HH': '%H', 'H': '%-H', 'h': '%-I', 'S': '%f', 'yyyy': '%Y', 'yy': '%y'}
TIME_TRIE: Dict = {'y': {'e': {'a': {'r': {0: True}}}, 0: True, 'y': {'y': {'y': {0: True}}, 0: True}}, 'q': {'q': {0: True}, 0: True, 'u': {'a': {'r': {'t': {'e': {'r': {0: True}}}}}}}, 'd': {'a': {'y': {'o': {'f': {'y': {'e': {'a': {'r': {0: True}}}}}}, 0: True}}, 'y': {0: True}, 'w': {0: True}, 'd': {0: True}, 0: True}, 'w': {'e': {'e': {'k': {0: True, 'd': {'a': {'y': {0: True}}}}}}, 'w': {0: True}, 'k': {0: True}}, 'h': {'o': {'u': {'r': {0: True}}}, 'h': {0: True}, 0: True}, 'm': {'i': {'n': {'u': {'t': {'e': {0: True}}}}, 0: True, 'l': {'l': {'i': {'s': {'e': {'c': {'o': {'n': {'d': {0: True}}}}}}}}}}, 's': {0: True}, 'o': {'n': {'t': {'h': {0: True}}}}, 'm': {0: True}, 0: True}, 'n': {0: True}, 's': {'e': {'c': {'o': {'n': {'d': {0: True}}}}}, 's': {0: True}, 0: True}, 'Y': {0: True, 'Y': {'Y': {'Y': {0: True}}, 0: True}}, 'M': {'M': {'M': {'M': {0: True}, 0: True}, 0: True}, 0: True}, 'H': {'H': {0: True}, 0: True}, 'S': {0: True}}

##### Inherited Members

sqlglot.parser.Parser
  Parser
  NO_PAREN_FUNCTIONS
  STRUCT_TYPE_TOKENS
  NESTED_TYPE_TOKENS
  ENUM_TYPE_TOKENS
  TYPE_TOKENS
  SUBQUERY_PREDICATES
  RESERVED_KEYWORDS
  DB_CREATABLES
  CREATABLES
  ID_VAR_TOKENS
  INTERVAL_VARS
  TABLE_ALIAS_TOKENS
  COMMENT_TABLE_ALIAS_TOKENS
  UPDATE_ALIAS_TOKENS
  TRIM_TYPES
  FUNC_TOKENS
  CONJUNCTION
  EQUALITY
  COMPARISON
  BITWISE
  TERM
  FACTOR
  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_KINDS
  TABLE_INDEX_HINT_TOKENS
  WINDOW_ALIAS_TOKENS
  WINDOW_BEFORE_PAREN_TOKENS
  WINDOW_SIDES
  ADD_CONSTRAINT_TOKENS
  DISTINCT_TOKENS
  STRICT_CAST
  PREFIXED_PIVOT_COLUMNS
  IDENTIFY_PIVOT_STRINGS
  SUPPORTS_USER_DEFINED_TYPES
  INDEX_OFFSET
  UNNEST_COLUMN_ONLY
  ALIAS_POST_TABLESAMPLE
  STRICT_STRING_CONCAT
  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

    581    class Generator(generator.Generator):
    582        LOCKING_READS_SUPPORTED = True
    583        LIMIT_IS_TOP = True
    584        QUERY_HINTS = False
    585        RETURNING_END = False
    586        NVL2_SUPPORTED = False
    587        ALTER_TABLE_ADD_COLUMN_KEYWORD = False
    588
    589        TYPE_MAPPING = {
    590            **generator.Generator.TYPE_MAPPING,
    591            exp.DataType.Type.BOOLEAN: "BIT",
    592            exp.DataType.Type.DECIMAL: "NUMERIC",
    593            exp.DataType.Type.DATETIME: "DATETIME2",
    594            exp.DataType.Type.INT: "INTEGER",
    595            exp.DataType.Type.TIMESTAMP: "DATETIME2",
    596            exp.DataType.Type.TIMESTAMPTZ: "DATETIMEOFFSET",
    597            exp.DataType.Type.VARIANT: "SQL_VARIANT",
    598        }
    599
    600        TRANSFORMS = {
    601            **generator.Generator.TRANSFORMS,
    602            exp.AnyValue: any_value_to_max_sql,
    603            exp.AutoIncrementColumnConstraint: lambda *_: "IDENTITY",
    604            exp.DateAdd: generate_date_delta_with_unit_sql,
    605            exp.DateDiff: generate_date_delta_with_unit_sql,
    606            exp.CurrentDate: rename_func("GETDATE"),
    607            exp.CurrentTimestamp: rename_func("GETDATE"),
    608            exp.Extract: rename_func("DATEPART"),
    609            exp.GroupConcat: _string_agg_sql,
    610            exp.If: rename_func("IIF"),
    611            exp.Max: max_or_greatest,
    612            exp.MD5: lambda self, e: self.func("HASHBYTES", exp.Literal.string("MD5"), e.this),
    613            exp.Min: min_or_least,
    614            exp.NumberToStr: _format_sql,
    615            exp.Select: transforms.preprocess([transforms.eliminate_distinct_on]),
    616            exp.SHA: lambda self, e: self.func("HASHBYTES", exp.Literal.string("SHA1"), e.this),
    617            exp.SHA2: lambda self, e: self.func(
    618                "HASHBYTES",
    619                exp.Literal.string(f"SHA2_{e.args.get('length', 256)}"),
    620                e.this,
    621            ),
    622            exp.TemporaryProperty: lambda self, e: "",
    623            exp.TimeStrToTime: timestrtotime_sql,
    624            exp.TimeToStr: _format_sql,
    625        }
    626
    627        TRANSFORMS.pop(exp.ReturnsProperty)
    628
    629        PROPERTIES_LOCATION = {
    630            **generator.Generator.PROPERTIES_LOCATION,
    631            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
    632        }
    633
    634        LIMIT_FETCH = "FETCH"
    635
    636        def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
    637            sql = self.sql(expression, "this")
    638            properties = expression.args.get("properties")
    639
    640            if sql[:1] != "#" and any(
    641                isinstance(prop, exp.TemporaryProperty)
    642                for prop in (properties.expressions if properties else [])
    643            ):
    644                sql = f"#{sql}"
    645
    646            return sql
    647
    648        def create_sql(self, expression: exp.Create) -> str:
    649            expression = expression.copy()
    650            kind = self.sql(expression, "kind").upper()
    651            exists = expression.args.pop("exists", None)
    652            sql = super().create_sql(expression)
    653
    654            if exists:
    655                table = expression.find(exp.Table)
    656                identifier = self.sql(exp.Literal.string(exp.table_name(table) if table else ""))
    657                if kind == "SCHEMA":
    658                    sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.schemata WHERE schema_name = {identifier}) EXEC('{sql}')"""
    659                elif kind == "TABLE":
    660                    sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.tables WHERE table_name = {identifier}) EXEC('{sql}')"""
    661                elif kind == "INDEX":
    662                    index = self.sql(exp.Literal.string(expression.this.text("this")))
    663                    sql = f"""IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id({identifier}) AND name = {index}) EXEC('{sql}')"""
    664            elif expression.args.get("replace"):
    665                sql = sql.replace("CREATE OR REPLACE ", "CREATE OR ALTER ", 1)
    666
    667            return sql
    668
    669        def offset_sql(self, expression: exp.Offset) -> str:
    670            return f"{super().offset_sql(expression)} ROWS"
    671
    672        def version_sql(self, expression: exp.Version) -> str:
    673            name = "SYSTEM_TIME" if expression.name == "TIMESTAMP" else expression.name
    674            this = f"FOR {name}"
    675            expr = expression.expression
    676            kind = expression.text("kind")
    677            if kind in ("FROM", "BETWEEN"):
    678                args = expr.expressions
    679                sep = "TO" if kind == "FROM" else "AND"
    680                expr_sql = f"{self.sql(seq_get(args, 0))} {sep} {self.sql(seq_get(args, 1))}"
    681            else:
    682                expr_sql = self.sql(expr)
    683
    684            expr_sql = f" {expr_sql}" if expr_sql else ""
    685            return f"{this} {kind}{expr_sql}"
    686
    687        def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str:
    688            table = expression.args.get("table")
    689            table = f"{table} " if table else ""
    690            return f"RETURNS {table}{self.sql(expression, 'this')}"
    691
    692        def returning_sql(self, expression: exp.Returning) -> str:
    693            into = self.sql(expression, "into")
    694            into = self.seg(f"INTO {into}") if into else ""
    695            return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}"
    696
    697        def transaction_sql(self, expression: exp.Transaction) -> str:
    698            this = self.sql(expression, "this")
    699            this = f" {this}" if this else ""
    700            mark = self.sql(expression, "mark")
    701            mark = f" WITH MARK {mark}" if mark else ""
    702            return f"BEGIN TRANSACTION{this}{mark}"
    703
    704        def commit_sql(self, expression: exp.Commit) -> str:
    705            this = self.sql(expression, "this")
    706            this = f" {this}" if this else ""
    707            durability = expression.args.get("durability")
    708            durability = (
    709                f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})"
    710                if durability is not None
    711                else ""
    712            )
    713            return f"COMMIT TRANSACTION{this}{durability}"
    714
    715        def rollback_sql(self, expression: exp.Rollback) -> str:
    716            this = self.sql(expression, "this")
    717            this = f" {this}" if this else ""
    718            return f"ROLLBACK TRANSACTION{this}"
    719
    720        def identifier_sql(self, expression: exp.Identifier) -> str:
    721            identifier = super().identifier_sql(expression)
    722
    723            if expression.args.get("global"):
    724                identifier = f"##{identifier}"
    725            elif expression.args.get("temporary"):
    726                identifier = f"#{identifier}"
    727
    728            return identifier
    729
    730        def constraint_sql(self, expression: exp.Constraint) -> str:
    731            this = self.sql(expression, "this")
    732            expressions = self.expressions(expression, flat=True, sep=" ")
    733            return f"CONSTRAINT {this} {expressions}"
    734
    735        # https://learn.microsoft.com/en-us/answers/questions/448821/create-table-in-sql-server
    736        def generatedasidentitycolumnconstraint_sql(
    737            self, expression: exp.GeneratedAsIdentityColumnConstraint
    738        ) -> str:
    739            start = self.sql(expression, "start") or "1"
    740            increment = self.sql(expression, "increment") or "1"
    741            return f"IDENTITY({start}, {increment})"

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

###### Arguments:

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

LOCKING_READS_SUPPORTED = True
LIMIT_IS_TOP = True
QUERY_HINTS = False
RETURNING_END = False
NVL2_SUPPORTED = False
ALTER_TABLE_ADD_COLUMN_KEYWORD = False
TYPE_MAPPING = {<Type.NCHAR: 'NCHAR'>: 'CHAR', <Type.NVARCHAR: 'NVARCHAR'>: 'VARCHAR', <Type.MEDIUMTEXT: 'MEDIUMTEXT'>: 'TEXT', <Type.LONGTEXT: 'LONGTEXT'>: 'TEXT', <Type.MEDIUMBLOB: 'MEDIUMBLOB'>: 'BLOB', <Type.LONGBLOB: 'LONGBLOB'>: 'BLOB', <Type.INET: 'INET'>: 'INET', <Type.BOOLEAN: 'BOOLEAN'>: 'BIT', <Type.DECIMAL: 'DECIMAL'>: 'NUMERIC', <Type.DATETIME: 'DATETIME'>: 'DATETIME2', <Type.INT: 'INT'>: 'INTEGER', <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.IntervalDayToSecondSpan'>: 'DAY TO SECOND', <class 'sqlglot.expressions.IntervalYearToMonthSpan'>: 'YEAR TO MONTH', <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.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StabilityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TemporaryProperty'>: <function TSQL.Generator.<lambda>>, <class 'sqlglot.expressions.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VarMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.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.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>}
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.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.PartitionedByProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.PrimaryKey'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Property'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.ReturnsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatDelimitedProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatSerdeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SchemaCommentProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SerdeProperties'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Set'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SettingsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SetProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.SortKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StabilityProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TemporaryProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.ToTableProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TransientProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.MergeTreeTTL'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.VolatileProperty'>: <Location.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.WithDataProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <Location.POST_NAME: 'POST_NAME'>}
LIMIT_FETCH = 'FETCH'
def createable_sql( self, expression: sqlglot.expressions.Create, locations: DefaultDict) -> str: View Source

    636        def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
    637            sql = self.sql(expression, "this")
    638            properties = expression.args.get("properties")
    639
    640            if sql[:1] != "#" and any(
    641                isinstance(prop, exp.TemporaryProperty)
    642                for prop in (properties.expressions if properties else [])
    643            ):
    644                sql = f"#{sql}"
    645
    646            return sql

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

    648        def create_sql(self, expression: exp.Create) -> str:
    649            expression = expression.copy()
    650            kind = self.sql(expression, "kind").upper()
    651            exists = expression.args.pop("exists", None)
    652            sql = super().create_sql(expression)
    653
    654            if exists:
    655                table = expression.find(exp.Table)
    656                identifier = self.sql(exp.Literal.string(exp.table_name(table) if table else ""))
    657                if kind == "SCHEMA":
    658                    sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.schemata WHERE schema_name = {identifier}) EXEC('{sql}')"""
    659                elif kind == "TABLE":
    660                    sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.tables WHERE table_name = {identifier}) EXEC('{sql}')"""
    661                elif kind == "INDEX":
    662                    index = self.sql(exp.Literal.string(expression.this.text("this")))
    663                    sql = f"""IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id({identifier}) AND name = {index}) EXEC('{sql}')"""
    664            elif expression.args.get("replace"):
    665                sql = sql.replace("CREATE OR REPLACE ", "CREATE OR ALTER ", 1)
    666
    667            return sql

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

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

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

    672        def version_sql(self, expression: exp.Version) -> str:
    673            name = "SYSTEM_TIME" if expression.name == "TIMESTAMP" else expression.name
    674            this = f"FOR {name}"
    675            expr = expression.expression
    676            kind = expression.text("kind")
    677            if kind in ("FROM", "BETWEEN"):
    678                args = expr.expressions
    679                sep = "TO" if kind == "FROM" else "AND"
    680                expr_sql = f"{self.sql(seq_get(args, 0))} {sep} {self.sql(seq_get(args, 1))}"
    681            else:
    682                expr_sql = self.sql(expr)
    683
    684            expr_sql = f" {expr_sql}" if expr_sql else ""
    685            return f"{this} {kind}{expr_sql}"

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

    687        def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str:
    688            table = expression.args.get("table")
    689            table = f"{table} " if table else ""
    690            return f"RETURNS {table}{self.sql(expression, 'this')}"

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

    692        def returning_sql(self, expression: exp.Returning) -> str:
    693            into = self.sql(expression, "into")
    694            into = self.seg(f"INTO {into}") if into else ""
    695            return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}"

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

    697        def transaction_sql(self, expression: exp.Transaction) -> str:
    698            this = self.sql(expression, "this")
    699            this = f" {this}" if this else ""
    700            mark = self.sql(expression, "mark")
    701            mark = f" WITH MARK {mark}" if mark else ""
    702            return f"BEGIN TRANSACTION{this}{mark}"

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

    704        def commit_sql(self, expression: exp.Commit) -> str:
    705            this = self.sql(expression, "this")
    706            this = f" {this}" if this else ""
    707            durability = expression.args.get("durability")
    708            durability = (
    709                f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})"
    710                if durability is not None
    711                else ""
    712            )
    713            return f"COMMIT TRANSACTION{this}{durability}"

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

    715        def rollback_sql(self, expression: exp.Rollback) -> str:
    716            this = self.sql(expression, "this")
    717            this = f" {this}" if this else ""
    718            return f"ROLLBACK TRANSACTION{this}"

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

    720        def identifier_sql(self, expression: exp.Identifier) -> str:
    721            identifier = super().identifier_sql(expression)
    722
    723            if expression.args.get("global"):
    724                identifier = f"##{identifier}"
    725            elif expression.args.get("temporary"):
    726                identifier = f"#{identifier}"
    727
    728            return identifier

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

    730        def constraint_sql(self, expression: exp.Constraint) -> str:
    731            this = self.sql(expression, "this")
    732            expressions = self.expressions(expression, flat=True, sep=" ")
    733            return f"CONSTRAINT {this} {expressions}"

def generatedasidentitycolumnconstraint_sql( self, expression: sqlglot.expressions.GeneratedAsIdentityColumnConstraint) -> str: View Source

    736        def generatedasidentitycolumnconstraint_sql(
    737            self, expression: exp.GeneratedAsIdentityColumnConstraint
    738        ) -> str:
    739            start = self.sql(expression, "start") or "1"
    740            increment = self.sql(expression, "increment") or "1"
    741            return f"IDENTITY({start}, {increment})"

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

    256    @classmethod
    257    def can_identify(cls, text: str, identify: str | bool = "safe") -> bool:
    258        """Checks if text can be identified given an identify option.
    259
    260        Args:
    261            text: The text to check.
    262            identify:
    263                "always" or `True`: Always returns true.
    264                "safe": True if the identifier is case-insensitive.
    265
    266        Returns:
    267            Whether or not the given text can be identified.
    268        """
    269        if identify is True or identify == "always":
    270            return True
    271
    272        if identify == "safe":
    273            return not cls.case_sensitive(text)
    274
    275        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 'sqlglot.dialects.tsql.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
  EXPLICIT_UNION
  WRAP_DERIVED_VALUES
  CREATE_FUNCTION_RETURN_AS
  MATCHED_BY_SOURCE
  SINGLE_STRING_INTERVAL
  INTERVAL_ALLOWS_PLURAL_FORM
  TABLESAMPLE_WITH_METHOD
  TABLESAMPLE_SIZE_IS_PERCENT
  RENAME_TABLE_WITH_DB
  GROUPINGS_SEP
  INDEX_ON
  JOIN_HINTS
  TABLE_HINTS
  QUERY_HINT_SEP
  IS_BOOL_ALLOWED
  DUPLICATE_KEY_UPDATE_WITH_SET
  COLUMN_JOIN_MARKS_SUPPORTED
  EXTRACT_ALLOWS_QUOTES
  TZ_TO_WITH_TIME_ZONE
  VALUES_AS_TABLE
  STAR_MAPPING
  TIME_PART_SINGULARS
  TOKEN_MAPPING
  STRUCT_DELIMITER
  PARAMETER_TOKEN
  RESERVED_KEYWORDS
  WITH_SEPARATED_COMMENTS
  UNWRAPPED_INTERVAL_VALUES
  SENTINEL_LINE_BREAK
  INDEX_OFFSET
  UNNEST_COLUMN_ONLY
  ALIAS_POST_TABLESAMPLE
  IDENTIFIERS_CAN_START_WITH_DIGIT
  STRICT_STRING_CONCAT
  NORMALIZE_FUNCTIONS
  ESCAPE_LINE_BREAK
  pretty
  identify
  normalize
  pad
  unsupported_level
  max_unsupported
  leading_comma
  max_text_width
  comments
  normalize_functions
  unsupported_messages
  generate
  unsupported
  sep
  seg
  pad_comment
  maybe_comment
  wrap
  no_identify
  normalize_func
  indent
  sql
  uncache_sql
  cache_sql
  characterset_sql
  column_sql
  columnposition_sql
  columndef_sql
  columnconstraint_sql
  computedcolumnconstraint_sql
  autoincrementcolumnconstraint_sql
  compresscolumnconstraint_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_sql
  likeproperty_sql
  fallbackproperty_sql
  journalproperty_sql
  freespaceproperty_sql
  checksumproperty_sql
  mergeblockratioproperty_sql
  datablocksizeproperty_sql
  blockcompressionproperty_sql
  isolatedloadingproperty_sql
  lockingproperty_sql
  withdataproperty_sql
  insert_sql
  intersect_sql
  intersect_op
  introducer_sql
  pseudotype_sql
  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
  setitem_sql
  set_sql
  pragma_sql
  lock_sql
  literal_sql
  escape_str
  loaddata_sql
  null_sql
  boolean_sql
  order_sql
  cluster_sql
  distribute_sql
  sort_sql
  ordered_sql
  matchrecognize_sql
  query_modifiers
  offset_limit_modifiers
  after_having_modifiers
  after_limit_modifiers
  select_sql
  schema_sql
  schema_columns_sql
  star_sql
  parameter_sql
  sessionparameter_sql
  placeholder_sql
  subquery_sql
  qualify_sql
  union_sql
  union_op
  unnest_sql
  where_sql
  window_sql
  partition_by_sql
  windowspec_sql
  withingroup_sql
  between_sql
  bracket_sql
  safebracket_sql
  all_sql
  any_sql
  exists_sql
  case_sql
  nextvaluefor_sql
  extract_sql
  trim_sql
  safeconcat_sql
  check_sql
  foreignkey_sql
  primarykey_sql
  if_sql
  matchagainst_sql
  jsonkeyvalue_sql
  jsonobject_sql
  openjsoncolumndef_sql
  openjson_sql
  in_sql
  in_unnest_op
  interval_sql
  return_sql
  reference_sql
  anonymous_sql
  paren_sql
  neg_sql
  not_sql
  alias_sql
  aliases_sql
  attimezone_sql
  add_sql
  and_sql
  xor_sql
  connector_sql
  bitwiseand_sql
  bitwiseleftshift_sql
  bitwisenot_sql
  bitwiseor_sql
  bitwiserightshift_sql
  bitwisexor_sql
  cast_sql
  currentdate_sql
  collate_sql
  command_sql
  comment_sql
  mergetreettlaction_sql
  mergetreettl_sql
  altercolumn_sql
  renametable_sql
  altertable_sql
  droppartition_sql
  addconstraint_sql
  distinct_sql
  ignorenulls_sql
  respectnulls_sql
  intdiv_sql
  dpipe_sql
  safedpipe_sql
  div_sql
  overlaps_sql
  distance_sql
  dot_sql
  eq_sql
  escape_sql
  glob_sql
  gt_sql
  gte_sql
  ilike_sql
  ilikeany_sql
  is_sql
  like_sql
  likeany_sql
  similarto_sql
  lt_sql
  lte_sql
  mod_sql
  mul_sql
  neq_sql
  nullsafeeq_sql
  nullsafeneq_sql
  or_sql
  slice_sql
  sub_sql
  trycast_sql
  use_sql
  binary
  function_fallback_sql
  func
  format_args
  text_width
  format_time
  expressions
  op_expressions
  naked_property
  set_operation
  tag_sql
  token_sql
  userdefinedfunction_sql
  joinhint_sql
  kwarg_sql
  when_sql
  merge_sql
  tochar_sql
  dictproperty_sql
  dictrange_sql
  dictsubproperty_sql
  oncluster_sql
  clusteredbyproperty_sql
  anyvalue_sql
  querytransform_sql
  indexconstraintoption_sql
  indexcolumnconstraint_sql
  nvl2_sql
  comprehension_sql