Edit on GitHub

sqlglot.dialects.tsql

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

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

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

Specifies the strategy according to which identifiers should be normalized.

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

Whether SEMI or ANTI joins are supported.

LOG_BASE_FIRST = False

Whether the base comes first in the LOG function.

TYPED_DIVISION = True

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

CONCAT_COALESCE = True

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

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

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

CONVERT_FORMAT_MAPPING = {'0': '%b %d %Y %-I:%M%p', '1': '%m/%d/%y', '2': '%y.%m.%d', '3': '%d/%m/%y', '4': '%d.%m.%y', '5': '%d-%m-%y', '6': '%d %b %y', '7': '%b %d, %y', '8': '%H:%M:%S', '9': '%b %d %Y %-I:%M:%S:%f%p', '10': 'mm-dd-yy', '11': 'yy/mm/dd', '12': 'yymmdd', '13': '%d %b %Y %H:%M:ss:%f', '14': '%H:%M:%S:%f', '20': '%Y-%m-%d %H:%M:%S', '21': '%Y-%m-%d %H:%M:%S.%f', '22': '%m/%d/%y %-I:%M:%S %p', '23': '%Y-%m-%d', '24': '%H:%M:%S', '25': '%Y-%m-%d %H:%M:%S.%f', '100': '%b %d %Y %-I:%M%p', '101': '%m/%d/%Y', '102': '%Y.%m.%d', '103': '%d/%m/%Y', '104': '%d.%m.%Y', '105': '%d-%m-%Y', '106': '%d %b %Y', '107': '%b %d, %Y', '108': '%H:%M:%S', '109': '%b %d %Y %-I:%M:%S:%f%p', '110': '%m-%d-%Y', '111': '%Y/%m/%d', '112': '%Y%m%d', '113': '%d %b %Y %H:%M:%S:%f', '114': '%H:%M:%S:%f', '120': '%Y-%m-%d %H:%M:%S', '121': '%Y-%m-%d %H:%M:%S.%f'}
FORMAT_TIME_MAPPING = {'y': '%B %Y', 'd': '%m/%d/%Y', 'H': '%-H', 'h': '%-I', 's': '%Y-%m-%d %H:%M:%S', 'D': '%A,%B,%Y', 'f': '%A,%B,%Y %-I:%M %p', 'F': '%A,%B,%Y %-I:%M:%S %p', 'g': '%m/%d/%Y %-I:%M %p', 'G': '%m/%d/%Y %-I:%M:%S %p', 'M': '%B %-d', 'm': '%B %-d', 'O': '%Y-%m-%dT%H:%M:%S', 'u': '%Y-%M-%D %H:%M:%S%z', 'U': '%A, %B %D, %Y %H:%M:%S%z', 'T': '%-I:%M:%S %p', 't': '%-I:%M', 'Y': '%a %Y'}
tokenizer_class = <class 'TSQL.Tokenizer'>
parser_class = <class 'TSQL.Parser'>
generator_class = <class 'TSQL.Generator'>
TIME_TRIE: Dict = {'y': {'e': {'a': {'r': {0: True}}}, 0: True, 'y': {'y': {'y': {0: True}}, 0: True}}, 'd': {'a': {'y': {'o': {'f': {'y': {'e': {'a': {'r': {0: True}}}}}}, 0: True}}, 'y': {0: True}, 'w': {0: True}, 'd': {'d': {'d': {0: True}}, 0: True}, 0: True}, 'w': {'e': {'e': {'k': {0: True, 'd': {'a': {'y': {0: True}}}}}}, 'w': {0: True}, 'k': {0: True}}, 'h': {'o': {'u': {'r': {0: True}}}, 'h': {0: True}, 0: True}, 'm': {'i': {'n': {'u': {'t': {'e': {0: True}}}}, 0: True, 'l': {'l': {'i': {'s': {'e': {'c': {'o': {'n': {'d': {0: True}}}}}}}}}}, 's': {0: True}, 'o': {'n': {'t': {'h': {0: True}}}}, 'm': {0: True}, 0: True}, 'n': {0: True}, 's': {'e': {'c': {'o': {'n': {'d': {0: True}}}}}, 's': {0: True}, 0: True}, 'Y': {0: True, 'Y': {'Y': {'Y': {0: True}}, 0: True}}, 'M': {'M': {'M': {'M': {0: True}, 0: True}, 0: True}, 0: True}, 'H': {'H': {0: True}, 0: True}, 'S': {0: True}}
FORMAT_TRIE: Dict = {'y': {'e': {'a': {'r': {0: True}}}, 0: True, 'y': {'y': {'y': {0: True}}, 0: True}}, 'd': {'a': {'y': {'o': {'f': {'y': {'e': {'a': {'r': {0: True}}}}}}, 0: True}}, 'y': {0: True}, 'w': {0: True}, 'd': {'d': {'d': {0: True}}, 0: True}, 0: True}, 'w': {'e': {'e': {'k': {0: True, 'd': {'a': {'y': {0: True}}}}}}, 'w': {0: True}, 'k': {0: True}}, 'h': {'o': {'u': {'r': {0: True}}}, 'h': {0: True}, 0: True}, 'm': {'i': {'n': {'u': {'t': {'e': {0: True}}}}, 0: True, 'l': {'l': {'i': {'s': {'e': {'c': {'o': {'n': {'d': {0: True}}}}}}}}}}, 's': {0: True}, 'o': {'n': {'t': {'h': {0: True}}}}, 'm': {0: True}, 0: True}, 'n': {0: True}, 's': {'e': {'c': {'o': {'n': {'d': {0: True}}}}}, 's': {0: True}, 0: True}, 'Y': {0: True, 'Y': {'Y': {'Y': {0: True}}, 0: True}}, 'M': {'M': {'M': {'M': {0: True}, 0: True}, 0: True}, 0: True}, 'H': {'H': {0: True}, 0: True}, 'S': {0: True}}
INVERSE_TIME_MAPPING: Dict[str, str] = {'%Y': 'yyyy', '%j': 'dayofyear', '%d': 'dd', '%W': 'dw', '%h': 'hour', '%I': 'hh', '%M': 'mm', '%S': 'ss', '%-S': 's', '%f': 'S', '%m': 'MM', '%-M': 'm', '%y': 'yy', '%B': 'MMMM', '%b': 'MMM', '%-m': 'M', '%A': 'dddd', '%-d': 'd', '%H': 'HH', '%-H': 'H', '%-I': 'h'}
INVERSE_TIME_TRIE: Dict = {'%': {'Y': {0: True}, 'j': {0: True}, 'd': {0: True}, 'W': {0: True}, 'h': {0: True}, 'I': {0: True}, 'M': {0: True}, 'S': {0: True}, '-': {'S': {0: True}, 'M': {0: True}, 'm': {0: True}, 'd': {0: True}, 'H': {0: True}, 'I': {0: True}}, 'f': {0: True}, 'm': {0: True}, 'y': {0: True}, 'B': {0: True}, 'b': {0: True}, 'A': {0: True}, 'H': {0: True}}}
INVERSE_ESCAPE_SEQUENCES: Dict[str, str] = {}
QUOTE_START = "'"
QUOTE_END = "'"
IDENTIFIER_START = '['
IDENTIFIER_END = ']'
BIT_START: Optional[str] = None
BIT_END: Optional[str] = None
HEX_START: Optional[str] = '0x'
HEX_END: Optional[str] = ''
BYTE_START: Optional[str] = None
BYTE_END: Optional[str] = None
UNICODE_START: Optional[str] = None
UNICODE_END: Optional[str] = None
class TSQL.Tokenizer(sqlglot.tokens.Tokenizer):
444    class Tokenizer(tokens.Tokenizer):
445        IDENTIFIERS = [("[", "]"), '"']
446        QUOTES = ["'", '"']
447        HEX_STRINGS = [("0x", ""), ("0X", "")]
448        VAR_SINGLE_TOKENS = {"@", "$", "#"}
449
450        KEYWORDS = {
451            **tokens.Tokenizer.KEYWORDS,
452            "DATETIME2": TokenType.DATETIME,
453            "DATETIMEOFFSET": TokenType.TIMESTAMPTZ,
454            "DECLARE": TokenType.COMMAND,
455            "EXEC": TokenType.COMMAND,
456            "IMAGE": TokenType.IMAGE,
457            "MONEY": TokenType.MONEY,
458            "NTEXT": TokenType.TEXT,
459            "PRINT": TokenType.COMMAND,
460            "PROC": TokenType.PROCEDURE,
461            "REAL": TokenType.FLOAT,
462            "ROWVERSION": TokenType.ROWVERSION,
463            "SMALLDATETIME": TokenType.DATETIME,
464            "SMALLMONEY": TokenType.SMALLMONEY,
465            "SQL_VARIANT": TokenType.VARIANT,
466            "TOP": TokenType.TOP,
467            "UNIQUEIDENTIFIER": TokenType.UNIQUEIDENTIFIER,
468            "UPDATE STATISTICS": TokenType.COMMAND,
469            "XML": TokenType.XML,
470            "OUTPUT": TokenType.RETURNING,
471            "SYSTEM_USER": TokenType.CURRENT_USER,
472            "FOR SYSTEM_TIME": TokenType.TIMESTAMP_SNAPSHOT,
473            "OPTION": TokenType.OPTION,
474        }
IDENTIFIERS = [('[', ']'), '"']
QUOTES = ["'", '"']
HEX_STRINGS = [('0x', ''), ('0X', '')]
VAR_SINGLE_TOKENS = {'@', '#', '$'}
KEYWORDS = {'{%': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{%-': <TokenType.BLOCK_START: 'BLOCK_START'>, '%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '+%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-%}': <TokenType.BLOCK_END: 'BLOCK_END'>, '{{+': <TokenType.BLOCK_START: 'BLOCK_START'>, '{{-': <TokenType.BLOCK_START: 'BLOCK_START'>, '+}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '-}}': <TokenType.BLOCK_END: 'BLOCK_END'>, '/*+': <TokenType.HINT: 'HINT'>, '==': <TokenType.EQ: 'EQ'>, '::': <TokenType.DCOLON: 'DCOLON'>, '||': <TokenType.DPIPE: 'DPIPE'>, '>=': <TokenType.GTE: 'GTE'>, '<=': <TokenType.LTE: 'LTE'>, '<>': <TokenType.NEQ: 'NEQ'>, '!=': <TokenType.NEQ: 'NEQ'>, ':=': <TokenType.COLON_EQ: 'COLON_EQ'>, '<=>': <TokenType.NULLSAFE_EQ: 'NULLSAFE_EQ'>, '->': <TokenType.ARROW: 'ARROW'>, '->>': <TokenType.DARROW: 'DARROW'>, '=>': <TokenType.FARROW: 'FARROW'>, '#>': <TokenType.HASH_ARROW: 'HASH_ARROW'>, '#>>': <TokenType.DHASH_ARROW: 'DHASH_ARROW'>, '<->': <TokenType.LR_ARROW: 'LR_ARROW'>, '&&': <TokenType.DAMP: 'DAMP'>, '??': <TokenType.DQMARK: 'DQMARK'>, 'ALL': <TokenType.ALL: 'ALL'>, 'ALWAYS': <TokenType.ALWAYS: 'ALWAYS'>, 'AND': <TokenType.AND: 'AND'>, 'ANTI': <TokenType.ANTI: 'ANTI'>, 'ANY': <TokenType.ANY: 'ANY'>, 'ASC': <TokenType.ASC: 'ASC'>, 'AS': <TokenType.ALIAS: 'ALIAS'>, 'ASOF': <TokenType.ASOF: 'ASOF'>, 'AUTOINCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'AUTO_INCREMENT': <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, 'BEGIN': <TokenType.BEGIN: 'BEGIN'>, 'BETWEEN': <TokenType.BETWEEN: 'BETWEEN'>, 'CACHE': <TokenType.CACHE: 'CACHE'>, 'UNCACHE': <TokenType.UNCACHE: 'UNCACHE'>, 'CASE': <TokenType.CASE: 'CASE'>, 'CHARACTER SET': <TokenType.CHARACTER_SET: 'CHARACTER_SET'>, 'CLUSTER BY': <TokenType.CLUSTER_BY: 'CLUSTER_BY'>, 'COLLATE': <TokenType.COLLATE: 'COLLATE'>, 'COLUMN': <TokenType.COLUMN: 'COLUMN'>, 'COMMIT': <TokenType.COMMIT: 'COMMIT'>, 'CONNECT BY': <TokenType.CONNECT_BY: 'CONNECT_BY'>, 'CONSTRAINT': <TokenType.CONSTRAINT: 'CONSTRAINT'>, 'CREATE': <TokenType.CREATE: 'CREATE'>, 'CROSS': <TokenType.CROSS: 'CROSS'>, 'CUBE': <TokenType.CUBE: 'CUBE'>, 'CURRENT_DATE': <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, 'CURRENT_TIME': <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, 'CURRENT_TIMESTAMP': <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, 'CURRENT_USER': <TokenType.CURRENT_USER: 'CURRENT_USER'>, 'DATABASE': <TokenType.DATABASE: 'DATABASE'>, 'DEFAULT': <TokenType.DEFAULT: 'DEFAULT'>, 'DELETE': <TokenType.DELETE: 'DELETE'>, 'DESC': <TokenType.DESC: 'DESC'>, 'DESCRIBE': <TokenType.DESCRIBE: 'DESCRIBE'>, 'DISTINCT': <TokenType.DISTINCT: 'DISTINCT'>, 'DISTRIBUTE BY': <TokenType.DISTRIBUTE_BY: 'DISTRIBUTE_BY'>, 'DIV': <TokenType.DIV: 'DIV'>, 'DROP': <TokenType.DROP: 'DROP'>, 'ELSE': <TokenType.ELSE: 'ELSE'>, 'END': <TokenType.END: 'END'>, 'ENUM': <TokenType.ENUM: 'ENUM'>, 'ESCAPE': <TokenType.ESCAPE: 'ESCAPE'>, 'EXCEPT': <TokenType.EXCEPT: 'EXCEPT'>, 'EXECUTE': <TokenType.EXECUTE: 'EXECUTE'>, 'EXISTS': <TokenType.EXISTS: 'EXISTS'>, 'FALSE': <TokenType.FALSE: 'FALSE'>, 'FETCH': <TokenType.FETCH: 'FETCH'>, 'FILTER': <TokenType.FILTER: 'FILTER'>, 'FIRST': <TokenType.FIRST: 'FIRST'>, 'FULL': <TokenType.FULL: 'FULL'>, 'FUNCTION': <TokenType.FUNCTION: 'FUNCTION'>, 'FOR': <TokenType.FOR: 'FOR'>, 'FOREIGN KEY': <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>, 'FORMAT': <TokenType.FORMAT: 'FORMAT'>, 'FROM': <TokenType.FROM: 'FROM'>, 'GEOGRAPHY': <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, 'GEOMETRY': <TokenType.GEOMETRY: 'GEOMETRY'>, 'GLOB': <TokenType.GLOB: 'GLOB'>, 'GROUP BY': <TokenType.GROUP_BY: 'GROUP_BY'>, 'GROUPING SETS': <TokenType.GROUPING_SETS: 'GROUPING_SETS'>, 'HAVING': <TokenType.HAVING: 'HAVING'>, 'ILIKE': <TokenType.ILIKE: 'ILIKE'>, 'IN': <TokenType.IN: 'IN'>, 'INDEX': <TokenType.INDEX: 'INDEX'>, 'INET': <TokenType.INET: 'INET'>, 'INNER': <TokenType.INNER: 'INNER'>, 'INSERT': <TokenType.INSERT: 'INSERT'>, 'INTERVAL': <TokenType.INTERVAL: 'INTERVAL'>, 'INTERSECT': <TokenType.INTERSECT: 'INTERSECT'>, 'INTO': <TokenType.INTO: 'INTO'>, 'IS': <TokenType.IS: 'IS'>, 'ISNULL': <TokenType.ISNULL: 'ISNULL'>, 'JOIN': <TokenType.JOIN: 'JOIN'>, 'KEEP': <TokenType.KEEP: 'KEEP'>, 'KILL': <TokenType.KILL: 'KILL'>, 'LATERAL': <TokenType.LATERAL: 'LATERAL'>, 'LEFT': <TokenType.LEFT: 'LEFT'>, 'LIKE': <TokenType.LIKE: 'LIKE'>, 'LIMIT': <TokenType.LIMIT: 'LIMIT'>, 'LOAD': <TokenType.LOAD: 'LOAD'>, 'LOCK': <TokenType.LOCK: 'LOCK'>, 'MERGE': <TokenType.MERGE: 'MERGE'>, 'NATURAL': <TokenType.NATURAL: 'NATURAL'>, 'NEXT': <TokenType.NEXT: 'NEXT'>, 'NOT': <TokenType.NOT: 'NOT'>, 'NOTNULL': <TokenType.NOTNULL: 'NOTNULL'>, 'NULL': <TokenType.NULL: 'NULL'>, 'OBJECT': <TokenType.OBJECT: 'OBJECT'>, 'OFFSET': <TokenType.OFFSET: 'OFFSET'>, 'ON': <TokenType.ON: 'ON'>, 'OR': <TokenType.OR: 'OR'>, 'XOR': <TokenType.XOR: 'XOR'>, 'ORDER BY': <TokenType.ORDER_BY: 'ORDER_BY'>, 'ORDINALITY': <TokenType.ORDINALITY: 'ORDINALITY'>, 'OUTER': <TokenType.OUTER: 'OUTER'>, 'OVER': <TokenType.OVER: 'OVER'>, 'OVERLAPS': <TokenType.OVERLAPS: 'OVERLAPS'>, 'OVERWRITE': <TokenType.OVERWRITE: 'OVERWRITE'>, 'PARTITION': <TokenType.PARTITION: 'PARTITION'>, 'PARTITION BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PARTITIONED_BY': <TokenType.PARTITION_BY: 'PARTITION_BY'>, 'PERCENT': <TokenType.PERCENT: 'PERCENT'>, 'PIVOT': <TokenType.PIVOT: 'PIVOT'>, 'PRAGMA': <TokenType.PRAGMA: 'PRAGMA'>, 'PRIMARY KEY': <TokenType.PRIMARY_KEY: 'PRIMARY_KEY'>, 'PROCEDURE': <TokenType.PROCEDURE: 'PROCEDURE'>, 'QUALIFY': <TokenType.QUALIFY: 'QUALIFY'>, 'RANGE': <TokenType.RANGE: 'RANGE'>, 'RECURSIVE': <TokenType.RECURSIVE: 'RECURSIVE'>, 'REGEXP': <TokenType.RLIKE: 'RLIKE'>, 'REPLACE': <TokenType.REPLACE: 'REPLACE'>, 'RETURNING': <TokenType.RETURNING: 'RETURNING'>, 'REFERENCES': <TokenType.REFERENCES: 'REFERENCES'>, 'RIGHT': <TokenType.RIGHT: 'RIGHT'>, 'RLIKE': <TokenType.RLIKE: 'RLIKE'>, 'ROLLBACK': <TokenType.ROLLBACK: 'ROLLBACK'>, 'ROLLUP': <TokenType.ROLLUP: 'ROLLUP'>, 'ROW': <TokenType.ROW: 'ROW'>, 'ROWS': <TokenType.ROWS: 'ROWS'>, 'SCHEMA': <TokenType.SCHEMA: 'SCHEMA'>, 'SELECT': <TokenType.SELECT: 'SELECT'>, 'SEMI': <TokenType.SEMI: 'SEMI'>, 'SET': <TokenType.SET: 'SET'>, 'SETTINGS': <TokenType.SETTINGS: 'SETTINGS'>, 'SHOW': <TokenType.SHOW: 'SHOW'>, 'SIMILAR TO': <TokenType.SIMILAR_TO: 'SIMILAR_TO'>, 'SOME': <TokenType.SOME: 'SOME'>, 'SORT BY': <TokenType.SORT_BY: 'SORT_BY'>, 'START WITH': <TokenType.START_WITH: 'START_WITH'>, 'TABLE': <TokenType.TABLE: 'TABLE'>, 'TABLESAMPLE': <TokenType.TABLE_SAMPLE: 'TABLE_SAMPLE'>, 'TEMP': <TokenType.TEMPORARY: 'TEMPORARY'>, 'TEMPORARY': <TokenType.TEMPORARY: 'TEMPORARY'>, 'THEN': <TokenType.THEN: 'THEN'>, 'TRUE': <TokenType.TRUE: 'TRUE'>, 'TRUNCATE': <TokenType.TRUNCATE: 'TRUNCATE'>, 'UNION': <TokenType.UNION: 'UNION'>, 'UNKNOWN': <TokenType.UNKNOWN: 'UNKNOWN'>, 'UNNEST': <TokenType.UNNEST: 'UNNEST'>, 'UNPIVOT': <TokenType.UNPIVOT: 'UNPIVOT'>, 'UPDATE': <TokenType.UPDATE: 'UPDATE'>, 'USE': <TokenType.USE: 'USE'>, 'USING': <TokenType.USING: 'USING'>, 'UUID': <TokenType.UUID: 'UUID'>, 'VALUES': <TokenType.VALUES: 'VALUES'>, 'VIEW': <TokenType.VIEW: 'VIEW'>, 'VOLATILE': <TokenType.VOLATILE: 'VOLATILE'>, 'WHEN': <TokenType.WHEN: 'WHEN'>, 'WHERE': <TokenType.WHERE: 'WHERE'>, 'WINDOW': <TokenType.WINDOW: 'WINDOW'>, 'WITH': <TokenType.WITH: 'WITH'>, 'APPLY': <TokenType.APPLY: 'APPLY'>, 'ARRAY': <TokenType.ARRAY: 'ARRAY'>, 'BIT': <TokenType.BIT: 'BIT'>, 'BOOL': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BOOLEAN': <TokenType.BOOLEAN: 'BOOLEAN'>, 'BYTE': <TokenType.TINYINT: 'TINYINT'>, 'MEDIUMINT': <TokenType.MEDIUMINT: 'MEDIUMINT'>, 'INT1': <TokenType.TINYINT: 'TINYINT'>, 'TINYINT': <TokenType.TINYINT: 'TINYINT'>, 'INT16': <TokenType.SMALLINT: 'SMALLINT'>, 'SHORT': <TokenType.SMALLINT: 'SMALLINT'>, 'SMALLINT': <TokenType.SMALLINT: 'SMALLINT'>, 'INT128': <TokenType.INT128: 'INT128'>, 'HUGEINT': <TokenType.INT128: 'INT128'>, 'INT2': <TokenType.SMALLINT: 'SMALLINT'>, 'INTEGER': <TokenType.INT: 'INT'>, 'INT': <TokenType.INT: 'INT'>, 'INT4': <TokenType.INT: 'INT'>, 'INT32': <TokenType.INT: 'INT'>, 'INT64': <TokenType.BIGINT: 'BIGINT'>, 'LONG': <TokenType.BIGINT: 'BIGINT'>, 'BIGINT': <TokenType.BIGINT: 'BIGINT'>, 'INT8': <TokenType.TINYINT: 'TINYINT'>, 'DEC': <TokenType.DECIMAL: 'DECIMAL'>, 'DECIMAL': <TokenType.DECIMAL: 'DECIMAL'>, 'BIGDECIMAL': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, 'BIGNUMERIC': <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, 'MAP': <TokenType.MAP: 'MAP'>, 'NULLABLE': <TokenType.NULLABLE: 'NULLABLE'>, 'NUMBER': <TokenType.DECIMAL: 'DECIMAL'>, 'NUMERIC': <TokenType.DECIMAL: 'DECIMAL'>, 'FIXED': <TokenType.DECIMAL: 'DECIMAL'>, 'REAL': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT4': <TokenType.FLOAT: 'FLOAT'>, 'FLOAT8': <TokenType.DOUBLE: 'DOUBLE'>, 'DOUBLE': <TokenType.DOUBLE: 'DOUBLE'>, 'DOUBLE PRECISION': <TokenType.DOUBLE: 'DOUBLE'>, 'JSON': <TokenType.JSON: 'JSON'>, 'CHAR': <TokenType.CHAR: 'CHAR'>, 'CHARACTER': <TokenType.CHAR: 'CHAR'>, 'NCHAR': <TokenType.NCHAR: 'NCHAR'>, 'VARCHAR': <TokenType.VARCHAR: 'VARCHAR'>, 'VARCHAR2': <TokenType.VARCHAR: 'VARCHAR'>, 'NVARCHAR': <TokenType.NVARCHAR: 'NVARCHAR'>, 'NVARCHAR2': <TokenType.NVARCHAR: 'NVARCHAR'>, 'BPCHAR': <TokenType.BPCHAR: 'BPCHAR'>, 'STR': <TokenType.TEXT: 'TEXT'>, 'STRING': <TokenType.TEXT: 'TEXT'>, 'TEXT': <TokenType.TEXT: 'TEXT'>, 'LONGTEXT': <TokenType.LONGTEXT: 'LONGTEXT'>, 'MEDIUMTEXT': <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, 'TINYTEXT': <TokenType.TINYTEXT: 'TINYTEXT'>, 'CLOB': <TokenType.TEXT: 'TEXT'>, 'LONGVARCHAR': <TokenType.TEXT: 'TEXT'>, 'BINARY': <TokenType.BINARY: 'BINARY'>, 'BLOB': <TokenType.VARBINARY: 'VARBINARY'>, 'LONGBLOB': <TokenType.LONGBLOB: 'LONGBLOB'>, 'MEDIUMBLOB': <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, 'TINYBLOB': <TokenType.TINYBLOB: 'TINYBLOB'>, 'BYTEA': <TokenType.VARBINARY: 'VARBINARY'>, 'VARBINARY': <TokenType.VARBINARY: 'VARBINARY'>, 'TIME': <TokenType.TIME: 'TIME'>, 'TIMETZ': <TokenType.TIMETZ: 'TIMETZ'>, 'TIMESTAMP': <TokenType.TIMESTAMP: 'TIMESTAMP'>, 'TIMESTAMPTZ': <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, 'TIMESTAMPLTZ': <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, 'DATE': <TokenType.DATE: 'DATE'>, 'DATETIME': <TokenType.DATETIME: 'DATETIME'>, 'INT4RANGE': <TokenType.INT4RANGE: 'INT4RANGE'>, 'INT4MULTIRANGE': <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, 'INT8RANGE': <TokenType.INT8RANGE: 'INT8RANGE'>, 'INT8MULTIRANGE': <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, 'NUMRANGE': <TokenType.NUMRANGE: 'NUMRANGE'>, 'NUMMULTIRANGE': <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, 'TSRANGE': <TokenType.TSRANGE: 'TSRANGE'>, 'TSMULTIRANGE': <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, 'TSTZRANGE': <TokenType.TSTZRANGE: 'TSTZRANGE'>, 'TSTZMULTIRANGE': <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, 'DATERANGE': <TokenType.DATERANGE: 'DATERANGE'>, 'DATEMULTIRANGE': <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, 'UNIQUE': <TokenType.UNIQUE: 'UNIQUE'>, 'STRUCT': <TokenType.STRUCT: 'STRUCT'>, 'VARIANT': <TokenType.VARIANT: 'VARIANT'>, 'ALTER': <TokenType.ALTER: 'ALTER'>, 'ANALYZE': <TokenType.COMMAND: 'COMMAND'>, 'CALL': <TokenType.COMMAND: 'COMMAND'>, 'COMMENT': <TokenType.COMMENT: 'COMMENT'>, 'COPY': <TokenType.COMMAND: 'COMMAND'>, 'EXPLAIN': <TokenType.COMMAND: 'COMMAND'>, 'GRANT': <TokenType.COMMAND: 'COMMAND'>, 'OPTIMIZE': <TokenType.COMMAND: 'COMMAND'>, 'PREPARE': <TokenType.COMMAND: 'COMMAND'>, 'VACUUM': <TokenType.COMMAND: 'COMMAND'>, 'USER-DEFINED': <TokenType.USERDEFINED: 'USERDEFINED'>, 'FOR VERSION': <TokenType.VERSION_SNAPSHOT: 'VERSION_SNAPSHOT'>, 'FOR TIMESTAMP': <TokenType.TIMESTAMP_SNAPSHOT: 'TIMESTAMP_SNAPSHOT'>, 'DATETIME2': <TokenType.DATETIME: 'DATETIME'>, 'DATETIMEOFFSET': <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, 'DECLARE': <TokenType.COMMAND: 'COMMAND'>, 'EXEC': <TokenType.COMMAND: 'COMMAND'>, 'IMAGE': <TokenType.IMAGE: 'IMAGE'>, 'MONEY': <TokenType.MONEY: 'MONEY'>, 'NTEXT': <TokenType.TEXT: 'TEXT'>, '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'>, 'XML': <TokenType.XML: 'XML'>, 'OUTPUT': <TokenType.RETURNING: 'RETURNING'>, 'SYSTEM_USER': <TokenType.CURRENT_USER: 'CURRENT_USER'>, 'FOR SYSTEM_TIME': <TokenType.TIMESTAMP_SNAPSHOT: 'TIMESTAMP_SNAPSHOT'>, 'OPTION': <TokenType.OPTION: 'OPTION'>}
class TSQL.Parser(sqlglot.parser.Parser):
476    class Parser(parser.Parser):
477        SET_REQUIRES_ASSIGNMENT_DELIMITER = False
478        LOG_DEFAULTS_TO_LN = True
479        ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN = False
480        STRING_ALIASES = True
481        NO_PAREN_IF_COMMANDS = False
482
483        QUERY_MODIFIER_PARSERS = {
484            **parser.Parser.QUERY_MODIFIER_PARSERS,
485            TokenType.OPTION: lambda self: ("options", self._parse_options()),
486        }
487
488        FUNCTIONS = {
489            **parser.Parser.FUNCTIONS,
490            "CHARINDEX": lambda args: exp.StrPosition(
491                this=seq_get(args, 1),
492                substr=seq_get(args, 0),
493                position=seq_get(args, 2),
494            ),
495            "DATEADD": build_date_delta(exp.DateAdd, unit_mapping=DATE_DELTA_INTERVAL),
496            "DATEDIFF": _build_date_delta(exp.DateDiff, unit_mapping=DATE_DELTA_INTERVAL),
497            "DATENAME": _build_formatted_time(exp.TimeToStr, full_format_mapping=True),
498            "DATEPART": _build_formatted_time(exp.TimeToStr),
499            "DATETIMEFROMPARTS": _build_datetimefromparts,
500            "EOMONTH": _build_eomonth,
501            "FORMAT": _build_format,
502            "GETDATE": exp.CurrentTimestamp.from_arg_list,
503            "HASHBYTES": _build_hashbytes,
504            "ISNULL": exp.Coalesce.from_arg_list,
505            "JSON_QUERY": parser.build_extract_json_with_path(exp.JSONExtract),
506            "JSON_VALUE": parser.build_extract_json_with_path(exp.JSONExtractScalar),
507            "LEN": _build_with_arg_as_text(exp.Length),
508            "LEFT": _build_with_arg_as_text(exp.Left),
509            "RIGHT": _build_with_arg_as_text(exp.Right),
510            "REPLICATE": exp.Repeat.from_arg_list,
511            "SQUARE": lambda args: exp.Pow(this=seq_get(args, 0), expression=exp.Literal.number(2)),
512            "SYSDATETIME": exp.CurrentTimestamp.from_arg_list,
513            "SUSER_NAME": exp.CurrentUser.from_arg_list,
514            "SUSER_SNAME": exp.CurrentUser.from_arg_list,
515            "SYSTEM_USER": exp.CurrentUser.from_arg_list,
516            "TIMEFROMPARTS": _build_timefromparts,
517        }
518
519        JOIN_HINTS = {"LOOP", "HASH", "MERGE", "REMOTE"}
520
521        RETURNS_TABLE_TOKENS = parser.Parser.ID_VAR_TOKENS - {
522            TokenType.TABLE,
523            *parser.Parser.TYPE_TOKENS,
524        }
525
526        STATEMENT_PARSERS = {
527            **parser.Parser.STATEMENT_PARSERS,
528            TokenType.END: lambda self: self._parse_command(),
529        }
530
531        def _parse_options(self) -> t.Optional[t.List[exp.Expression]]:
532            if not self._match(TokenType.OPTION):
533                return None
534
535            def _parse_option() -> t.Optional[exp.Expression]:
536                option = self._parse_var_from_options(OPTIONS)
537                if not option:
538                    return None
539
540                self._match(TokenType.EQ)
541                return self.expression(
542                    exp.QueryOption, this=option, expression=self._parse_primary_or_var()
543                )
544
545            return self._parse_wrapped_csv(_parse_option)
546
547        def _parse_projections(self) -> t.List[exp.Expression]:
548            """
549            T-SQL supports the syntax alias = expression in the SELECT's projection list,
550            so we transform all parsed Selects to convert their EQ projections into Aliases.
551
552            See: https://learn.microsoft.com/en-us/sql/t-sql/queries/select-clause-transact-sql?view=sql-server-ver16#syntax
553            """
554            return [
555                (
556                    exp.alias_(projection.expression, projection.this.this, copy=False)
557                    if isinstance(projection, exp.EQ) and isinstance(projection.this, exp.Column)
558                    else projection
559                )
560                for projection in super()._parse_projections()
561            ]
562
563        def _parse_commit_or_rollback(self) -> exp.Commit | exp.Rollback:
564            """Applies to SQL Server and Azure SQL Database
565            COMMIT [ { TRAN | TRANSACTION }
566                [ transaction_name | @tran_name_variable ] ]
567                [ WITH ( DELAYED_DURABILITY = { OFF | ON } ) ]
568
569            ROLLBACK { TRAN | TRANSACTION }
570                [ transaction_name | @tran_name_variable
571                | savepoint_name | @savepoint_variable ]
572            """
573            rollback = self._prev.token_type == TokenType.ROLLBACK
574
575            self._match_texts(("TRAN", "TRANSACTION"))
576            this = self._parse_id_var()
577
578            if rollback:
579                return self.expression(exp.Rollback, this=this)
580
581            durability = None
582            if self._match_pair(TokenType.WITH, TokenType.L_PAREN):
583                self._match_text_seq("DELAYED_DURABILITY")
584                self._match(TokenType.EQ)
585
586                if self._match_text_seq("OFF"):
587                    durability = False
588                else:
589                    self._match(TokenType.ON)
590                    durability = True
591
592                self._match_r_paren()
593
594            return self.expression(exp.Commit, this=this, durability=durability)
595
596        def _parse_transaction(self) -> exp.Transaction | exp.Command:
597            """Applies to SQL Server and Azure SQL Database
598            BEGIN { TRAN | TRANSACTION }
599            [ { transaction_name | @tran_name_variable }
600            [ WITH MARK [ 'description' ] ]
601            ]
602            """
603            if self._match_texts(("TRAN", "TRANSACTION")):
604                transaction = self.expression(exp.Transaction, this=self._parse_id_var())
605                if self._match_text_seq("WITH", "MARK"):
606                    transaction.set("mark", self._parse_string())
607
608                return transaction
609
610            return self._parse_as_command(self._prev)
611
612        def _parse_returns(self) -> exp.ReturnsProperty:
613            table = self._parse_id_var(any_token=False, tokens=self.RETURNS_TABLE_TOKENS)
614            returns = super()._parse_returns()
615            returns.set("table", table)
616            return returns
617
618        def _parse_convert(
619            self, strict: bool, safe: t.Optional[bool] = None
620        ) -> t.Optional[exp.Expression]:
621            this = self._parse_types()
622            self._match(TokenType.COMMA)
623            args = [this, *self._parse_csv(self._parse_conjunction)]
624            convert = exp.Convert.from_arg_list(args)
625            convert.set("safe", safe)
626            convert.set("strict", strict)
627            return convert
628
629        def _parse_user_defined_function(
630            self, kind: t.Optional[TokenType] = None
631        ) -> t.Optional[exp.Expression]:
632            this = super()._parse_user_defined_function(kind=kind)
633
634            if (
635                kind == TokenType.FUNCTION
636                or isinstance(this, exp.UserDefinedFunction)
637                or self._match(TokenType.ALIAS, advance=False)
638            ):
639                return this
640
641            expressions = self._parse_csv(self._parse_function_parameter)
642            return self.expression(exp.UserDefinedFunction, this=this, expressions=expressions)
643
644        def _parse_id_var(
645            self,
646            any_token: bool = True,
647            tokens: t.Optional[t.Collection[TokenType]] = None,
648        ) -> t.Optional[exp.Expression]:
649            is_temporary = self._match(TokenType.HASH)
650            is_global = is_temporary and self._match(TokenType.HASH)
651
652            this = super()._parse_id_var(any_token=any_token, tokens=tokens)
653            if this:
654                if is_global:
655                    this.set("global", True)
656                elif is_temporary:
657                    this.set("temporary", True)
658
659            return this
660
661        def _parse_create(self) -> exp.Create | exp.Command:
662            create = super()._parse_create()
663
664            if isinstance(create, exp.Create):
665                table = create.this.this if isinstance(create.this, exp.Schema) else create.this
666                if isinstance(table, exp.Table) and table.this.args.get("temporary"):
667                    if not create.args.get("properties"):
668                        create.set("properties", exp.Properties(expressions=[]))
669
670                    create.args["properties"].append("expressions", exp.TemporaryProperty())
671
672            return create
673
674        def _parse_if(self) -> t.Optional[exp.Expression]:
675            index = self._index
676
677            if self._match_text_seq("OBJECT_ID"):
678                self._parse_wrapped_csv(self._parse_string)
679                if self._match_text_seq("IS", "NOT", "NULL") and self._match(TokenType.DROP):
680                    return self._parse_drop(exists=True)
681                self._retreat(index)
682
683            return super()._parse_if()
684
685        def _parse_unique(self) -> exp.UniqueColumnConstraint:
686            if self._match_texts(("CLUSTERED", "NONCLUSTERED")):
687                this = self.CONSTRAINT_PARSERS[self._prev.text.upper()](self)
688            else:
689                this = self._parse_schema(self._parse_id_var(any_token=False))
690
691            return self.expression(exp.UniqueColumnConstraint, this=this)
692
693        def _parse_partition(self) -> t.Optional[exp.Partition]:
694            if not self._match_text_seq("WITH", "(", "PARTITIONS"):
695                return None
696
697            def parse_range():
698                low = self._parse_bitwise()
699                high = self._parse_bitwise() if self._match_text_seq("TO") else None
700
701                return (
702                    self.expression(exp.PartitionRange, this=low, expression=high) if high else low
703                )
704
705            partition = self.expression(
706                exp.Partition, expressions=self._parse_wrapped_csv(parse_range)
707            )
708
709            self._match_r_paren()
710
711            return partition

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: The amount of context to capture from a query string when displaying the error message (in number of characters). Default: 100
  • max_errors: Maximum number of error messages to include in a raised ParseError. This is only relevant if error_level is ErrorLevel.RAISE. Default: 3
SET_REQUIRES_ASSIGNMENT_DELIMITER = False
LOG_DEFAULTS_TO_LN = True
ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN = False
STRING_ALIASES = True
NO_PAREN_IF_COMMANDS = False
QUERY_MODIFIER_PARSERS = {<TokenType.MATCH_RECOGNIZE: 'MATCH_RECOGNIZE'>: <function Parser.<lambda>>, <TokenType.PREWHERE: 'PREWHERE'>: <function Parser.<lambda>>, <TokenType.WHERE: 'WHERE'>: <function Parser.<lambda>>, <TokenType.GROUP_BY: 'GROUP_BY'>: <function Parser.<lambda>>, <TokenType.HAVING: 'HAVING'>: <function Parser.<lambda>>, <TokenType.QUALIFY: 'QUALIFY'>: <function Parser.<lambda>>, <TokenType.WINDOW: 'WINDOW'>: <function Parser.<lambda>>, <TokenType.ORDER_BY: 'ORDER_BY'>: <function Parser.<lambda>>, <TokenType.LIMIT: 'LIMIT'>: <function Parser.<lambda>>, <TokenType.FETCH: 'FETCH'>: <function Parser.<lambda>>, <TokenType.OFFSET: 'OFFSET'>: <function Parser.<lambda>>, <TokenType.FOR: 'FOR'>: <function Parser.<lambda>>, <TokenType.LOCK: 'LOCK'>: <function Parser.<lambda>>, <TokenType.TABLE_SAMPLE: 'TABLE_SAMPLE'>: <function Parser.<lambda>>, <TokenType.USING: 'USING'>: <function Parser.<lambda>>, <TokenType.CLUSTER_BY: 'CLUSTER_BY'>: <function Parser.<lambda>>, <TokenType.DISTRIBUTE_BY: 'DISTRIBUTE_BY'>: <function Parser.<lambda>>, <TokenType.SORT_BY: 'SORT_BY'>: <function Parser.<lambda>>, <TokenType.CONNECT_BY: 'CONNECT_BY'>: <function Parser.<lambda>>, <TokenType.START_WITH: 'START_WITH'>: <function Parser.<lambda>>, <TokenType.OPTION: 'OPTION'>: <function TSQL.Parser.<lambda>>}
FUNCTIONS = {'ABS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Abs'>>, 'ADD_MONTHS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.AddMonths'>>, 'ANONYMOUS_AGG_FUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.AnonymousAggFunc'>>, 'ANY_VALUE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.AnyValue'>>, 'APPROX_DISTINCT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxDistinct'>>, 'APPROX_COUNT_DISTINCT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxDistinct'>>, 'APPROX_QUANTILE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxQuantile'>>, 'APPROX_TOP_K': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ApproxTopK'>>, 'ARG_MAX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMax'>>, 'ARGMAX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMax'>>, 'MAX_BY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMax'>>, 'ARG_MIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMin'>>, 'ARGMIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMin'>>, 'MIN_BY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArgMin'>>, 'ARRAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Array'>>, 'ARRAY_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayAgg'>>, 'ARRAY_ALL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayAll'>>, 'ARRAY_ANY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayAny'>>, 'ARRAY_CONCAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayConcat'>>, 'ARRAY_CAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayConcat'>>, 'ARRAY_CONTAINS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayContains'>>, 'FILTER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayFilter'>>, 'ARRAY_FILTER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayFilter'>>, 'ARRAY_JOIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayJoin'>>, 'ARRAY_OVERLAPS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayOverlaps'>>, 'ARRAY_SIZE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArraySize'>>, 'ARRAY_LENGTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArraySize'>>, 'ARRAY_SORT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArraySort'>>, 'ARRAY_SUM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArraySum'>>, 'ARRAY_UNION_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayUnionAgg'>>, 'ARRAY_UNIQUE_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ArrayUniqueAgg'>>, 'AVG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Avg'>>, 'CASE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Case'>>, 'CAST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Cast'>>, 'CAST_TO_STR_TYPE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CastToStrType'>>, 'CBRT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Cbrt'>>, 'CEIL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Ceil'>>, 'CEILING': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Ceil'>>, 'CHR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Chr'>>, 'CHAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Chr'>>, 'COALESCE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'IFNULL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'NVL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'COLLATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Collate'>>, 'COMBINED_AGG_FUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CombinedAggFunc'>>, 'COMBINED_PARAMETERIZED_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CombinedParameterizedAgg'>>, 'CONCAT': <function Parser.<lambda>>, 'CONCAT_WS': <function Parser.<lambda>>, 'CONNECT_BY_ROOT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ConnectByRoot'>>, 'CONVERT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Convert'>>, 'COUNT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Count'>>, 'COUNT_IF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CountIf'>>, 'COUNTIF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CountIf'>>, 'CURRENT_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentDate'>>, 'CURRENT_DATETIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentDatetime'>>, 'CURRENT_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentTime'>>, 'CURRENT_TIMESTAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentTimestamp'>>, 'CURRENT_USER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentUser'>>, 'DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Date'>>, 'DATE_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateAdd'>>, 'DATEDIFF': <function _build_date_delta.<locals>._builder>, 'DATE_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateDiff'>>, 'DATE_FROM_PARTS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateFromParts'>>, 'DATEFROMPARTS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateFromParts'>>, 'DATE_STR_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateStrToDate'>>, 'DATE_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateSub'>>, 'DATE_TO_DATE_STR': <function Parser.<lambda>>, 'DATE_TO_DI': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateToDi'>>, 'DATE_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DateTrunc'>>, 'DATETIME_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeAdd'>>, 'DATETIME_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeDiff'>>, 'DATETIME_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeSub'>>, 'DATETIME_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DatetimeTrunc'>>, 'DAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Day'>>, 'DAY_OF_MONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfMonth'>>, 'DAYOFMONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfMonth'>>, 'DAY_OF_WEEK': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfWeek'>>, 'DAYOFWEEK': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfWeek'>>, 'DAY_OF_YEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfYear'>>, 'DAYOFYEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DayOfYear'>>, 'DECODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Decode'>>, 'DI_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.DiToDate'>>, 'ENCODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Encode'>>, 'EXP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Exp'>>, 'EXPLODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Explode'>>, 'EXPLODE_OUTER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ExplodeOuter'>>, 'EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Extract'>>, 'FIRST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.First'>>, 'FIRST_VALUE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.FirstValue'>>, 'FLATTEN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Flatten'>>, 'FLOOR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Floor'>>, 'FROM_BASE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.FromBase'>>, 'FROM_BASE64': <bound method Func.from_arg_list of <class 'sqlglot.expressions.FromBase64'>>, 'GENERATE_SERIES': <bound method Func.from_arg_list of <class 'sqlglot.expressions.GenerateSeries'>>, 'GREATEST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Greatest'>>, 'GROUP_CONCAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.GroupConcat'>>, 'HEX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Hex'>>, 'HLL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Hll'>>, 'IF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.If'>>, 'IIF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.If'>>, 'INITCAP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Initcap'>>, 'IS_INF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.IsInf'>>, 'ISINF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.IsInf'>>, 'IS_NAN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.IsNan'>>, 'ISNAN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.IsNan'>>, 'J_S_O_N_ARRAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONArray'>>, 'J_S_O_N_ARRAY_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONArrayAgg'>>, 'JSON_ARRAY_CONTAINS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONArrayContains'>>, 'JSONB_EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONBExtract'>>, 'JSONB_EXTRACT_SCALAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONBExtractScalar'>>, 'JSON_EXTRACT': <function build_extract_json_with_path.<locals>._builder>, 'JSON_EXTRACT_SCALAR': <function build_extract_json_with_path.<locals>._builder>, 'JSON_FORMAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONFormat'>>, 'J_S_O_N_OBJECT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONObject'>>, 'J_S_O_N_OBJECT_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONObjectAgg'>>, 'J_S_O_N_TABLE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.JSONTable'>>, 'LAG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Lag'>>, 'LAST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Last'>>, 'LAST_DAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LastDay'>>, 'LAST_DAY_OF_MONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LastDay'>>, 'LAST_VALUE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LastValue'>>, 'LEAD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Lead'>>, 'LEAST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Least'>>, 'LEFT': <function _build_with_arg_as_text.<locals>._parse>, 'LENGTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Length'>>, 'LEN': <function _build_with_arg_as_text.<locals>._parse>, 'LEVENSHTEIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Levenshtein'>>, 'LN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Ln'>>, 'LOG': <function build_logarithm>, 'LOG10': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Log10'>>, 'LOG2': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Log2'>>, 'LOGICAL_AND': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalAnd'>>, 'BOOL_AND': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalAnd'>>, 'BOOLAND_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalAnd'>>, 'LOGICAL_OR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalOr'>>, 'BOOL_OR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalOr'>>, 'BOOLOR_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.LogicalOr'>>, 'LOWER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Lower'>>, 'LCASE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Lower'>>, 'MD5': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MD5'>>, 'MD5_DIGEST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MD5Digest'>>, 'MAP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Map'>>, 'MAP_FROM_ENTRIES': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MapFromEntries'>>, 'MATCH_AGAINST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MatchAgainst'>>, 'MAX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Max'>>, 'MIN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Min'>>, 'MONTH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Month'>>, 'MONTHS_BETWEEN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.MonthsBetween'>>, 'NEXT_VALUE_FOR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.NextValueFor'>>, 'NTH_VALUE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.NthValue'>>, 'NULLIF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Nullif'>>, 'NUMBER_TO_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.NumberToStr'>>, 'NVL2': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Nvl2'>>, 'OPEN_J_S_O_N': <bound method Func.from_arg_list of <class 'sqlglot.expressions.OpenJSON'>>, 'PARAMETERIZED_AGG': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ParameterizedAgg'>>, 'PARSE_JSON': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ParseJSON'>>, 'JSON_PARSE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ParseJSON'>>, 'PERCENTILE_CONT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.PercentileCont'>>, 'PERCENTILE_DISC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.PercentileDisc'>>, 'POSEXPLODE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Posexplode'>>, 'POSEXPLODE_OUTER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.PosexplodeOuter'>>, 'POWER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Pow'>>, 'POW': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Pow'>>, 'PREDICT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Predict'>>, 'QUANTILE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Quantile'>>, 'RAND': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Rand'>>, 'RANDOM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Rand'>>, 'RANDN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Randn'>>, 'RANGE_N': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RangeN'>>, 'READ_CSV': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ReadCSV'>>, 'REDUCE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Reduce'>>, 'REGEXP_EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpExtract'>>, 'REGEXP_I_LIKE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpILike'>>, 'REGEXP_LIKE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpLike'>>, 'REGEXP_REPLACE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpReplace'>>, 'REGEXP_SPLIT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RegexpSplit'>>, 'REPEAT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Repeat'>>, 'RIGHT': <function _build_with_arg_as_text.<locals>._parse>, 'ROUND': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Round'>>, 'ROW_NUMBER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.RowNumber'>>, 'SHA': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SHA'>>, 'SHA1': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SHA'>>, 'SHA2': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SHA2'>>, 'SAFE_DIVIDE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SafeDivide'>>, 'SIGN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Sign'>>, 'SIGNUM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Sign'>>, 'SORT_ARRAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.SortArray'>>, 'SPLIT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Split'>>, 'SQRT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Sqrt'>>, 'STANDARD_HASH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StandardHash'>>, 'STAR_MAP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StarMap'>>, 'STARTS_WITH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StartsWith'>>, 'STARTSWITH': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StartsWith'>>, 'STDDEV': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Stddev'>>, 'STDDEV_POP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StddevPop'>>, 'STDDEV_SAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StddevSamp'>>, 'STR_POSITION': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrPosition'>>, 'STR_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrToDate'>>, 'STR_TO_MAP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrToMap'>>, 'STR_TO_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrToTime'>>, 'STR_TO_UNIX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StrToUnix'>>, 'STRUCT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Struct'>>, 'STRUCT_EXTRACT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.StructExtract'>>, 'STUFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Stuff'>>, 'INSERT': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Stuff'>>, 'SUBSTRING': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Substring'>>, 'SUM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Sum'>>, 'TIME_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeAdd'>>, 'TIME_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeDiff'>>, 'TIME_FROM_PARTS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeFromParts'>>, 'TIMEFROMPARTS': <function _build_timefromparts>, 'TIME_STR_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeStrToDate'>>, 'TIME_STR_TO_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeStrToTime'>>, 'TIME_STR_TO_UNIX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeStrToUnix'>>, 'TIME_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeSub'>>, 'TIME_TO_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeToStr'>>, 'TIME_TO_TIME_STR': <function Parser.<lambda>>, 'TIME_TO_UNIX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeToUnix'>>, 'TIME_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimeTrunc'>>, 'TIMESTAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Timestamp'>>, 'TIMESTAMP_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampAdd'>>, 'TIMESTAMPDIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampDiff'>>, 'TIMESTAMP_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampDiff'>>, 'TIMESTAMP_FROM_PARTS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampFromParts'>>, 'TIMESTAMPFROMPARTS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampFromParts'>>, 'TIMESTAMP_SUB': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampSub'>>, 'TIMESTAMP_TRUNC': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TimestampTrunc'>>, 'TO_ARRAY': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ToArray'>>, 'TO_BASE64': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ToBase64'>>, 'TO_CHAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ToChar'>>, 'TO_DAYS': <bound method Func.from_arg_list of <class 'sqlglot.expressions.ToDays'>>, 'TRANSFORM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Transform'>>, 'TRIM': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Trim'>>, 'TRY_CAST': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TryCast'>>, 'TS_OR_DI_TO_DI': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDiToDi'>>, 'TS_OR_DS_ADD': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDsAdd'>>, 'TS_OR_DS_DIFF': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDsDiff'>>, 'TS_OR_DS_TO_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDsToDate'>>, 'TS_OR_DS_TO_DATE_STR': <function Parser.<lambda>>, 'TS_OR_DS_TO_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.TsOrDsToTime'>>, 'UNHEX': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Unhex'>>, 'UNIX_DATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.UnixDate'>>, 'UNIX_TO_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.UnixToStr'>>, 'UNIX_TO_TIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.UnixToTime'>>, 'UNIX_TO_TIME_STR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.UnixToTimeStr'>>, 'UPPER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Upper'>>, 'UCASE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Upper'>>, 'VAR_MAP': <function build_var_map>, 'VARIANCE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Variance'>>, 'VARIANCE_SAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Variance'>>, 'VAR_SAMP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Variance'>>, 'VARIANCE_POP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.VariancePop'>>, 'VAR_POP': <bound method Func.from_arg_list of <class 'sqlglot.expressions.VariancePop'>>, 'WEEK': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Week'>>, 'WEEK_OF_YEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.WeekOfYear'>>, 'WEEKOFYEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.WeekOfYear'>>, 'WHEN': <bound method Func.from_arg_list of <class 'sqlglot.expressions.When'>>, 'X_M_L_TABLE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.XMLTable'>>, 'XOR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Xor'>>, 'YEAR': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Year'>>, 'GLOB': <function Parser.<lambda>>, 'JSON_EXTRACT_PATH_TEXT': <function build_extract_json_with_path.<locals>._builder>, 'LIKE': <function build_like>, 'CHARINDEX': <function TSQL.Parser.<lambda>>, 'DATEADD': <function build_date_delta.<locals>._builder>, 'DATENAME': <function _build_formatted_time.<locals>._builder>, 'DATEPART': <function _build_formatted_time.<locals>._builder>, 'DATETIMEFROMPARTS': <function _build_datetimefromparts>, 'EOMONTH': <function _build_eomonth>, 'FORMAT': <function _build_format>, 'GETDATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentTimestamp'>>, 'HASHBYTES': <function _build_hashbytes>, 'ISNULL': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Coalesce'>>, 'JSON_QUERY': <function build_extract_json_with_path.<locals>._builder>, 'JSON_VALUE': <function build_extract_json_with_path.<locals>._builder>, 'REPLICATE': <bound method Func.from_arg_list of <class 'sqlglot.expressions.Repeat'>>, 'SQUARE': <function TSQL.Parser.<lambda>>, 'SYSDATETIME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentTimestamp'>>, 'SUSER_NAME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentUser'>>, 'SUSER_SNAME': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentUser'>>, 'SYSTEM_USER': <bound method Func.from_arg_list of <class 'sqlglot.expressions.CurrentUser'>>}
JOIN_HINTS = {'MERGE', 'HASH', 'LOOP', 'REMOTE'}
RETURNS_TABLE_TOKENS = {<TokenType.COMMIT: 'COMMIT'>, <TokenType.STORAGE_INTEGRATION: 'STORAGE_INTEGRATION'>, <TokenType.OPERATOR: 'OPERATOR'>, <TokenType.FORMAT: 'FORMAT'>, <TokenType.REPLACE: 'REPLACE'>, <TokenType.FINAL: 'FINAL'>, <TokenType.PIVOT: 'PIVOT'>, <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>, <TokenType.VIEW: 'VIEW'>, <TokenType.DESC: 'DESC'>, <TokenType.APPLY: 'APPLY'>, <TokenType.OVERWRITE: 'OVERWRITE'>, <TokenType.DICTIONARY: 'DICTIONARY'>, <TokenType.CURRENT_USER: 'CURRENT_USER'>, <TokenType.ESCAPE: 'ESCAPE'>, <TokenType.PARTITION: 'PARTITION'>, <TokenType.SEMI: 'SEMI'>, <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, <TokenType.ASC: 'ASC'>, <TokenType.PERCENT: 'PERCENT'>, <TokenType.REFRESH: 'REFRESH'>, <TokenType.FULL: 'FULL'>, <TokenType.INDEX: 'INDEX'>, <TokenType.USE: 'USE'>, <TokenType.ROW: 'ROW'>, <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>, <TokenType.RIGHT: 'RIGHT'>, <TokenType.TRUNCATE: 'TRUNCATE'>, <TokenType.COMMENT: 'COMMENT'>, <TokenType.PROCEDURE: 'PROCEDURE'>, <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, <TokenType.DIV: 'DIV'>, <TokenType.UNPIVOT: 'UNPIVOT'>, <TokenType.SHOW: 'SHOW'>, <TokenType.RANGE: 'RANGE'>, <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, <TokenType.RECURSIVE: 'RECURSIVE'>, <TokenType.FIRST: 'FIRST'>, <TokenType.IS: 'IS'>, <TokenType.FUNCTION: 'FUNCTION'>, <TokenType.ANY: 'ANY'>, <TokenType.VAR: 'VAR'>, <TokenType.FALSE: 'FALSE'>, <TokenType.COLUMN: 'COLUMN'>, <TokenType.FILTER: 'FILTER'>, <TokenType.COLLATE: 'COLLATE'>, <TokenType.KILL: 'KILL'>, <TokenType.ROWS: 'ROWS'>, <TokenType.TRUE: 'TRUE'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.PRAGMA: 'PRAGMA'>, <TokenType.TOP: 'TOP'>, <TokenType.NATURAL: 'NATURAL'>, <TokenType.REFERENCES: 'REFERENCES'>, <TokenType.UNIQUE: 'UNIQUE'>, <TokenType.SET: 'SET'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.ORDINALITY: 'ORDINALITY'>, <TokenType.CONSTRAINT: 'CONSTRAINT'>, <TokenType.UPDATE: 'UPDATE'>, <TokenType.NEXT: 'NEXT'>, <TokenType.LOAD: 'LOAD'>, <TokenType.OVERLAPS: 'OVERLAPS'>, <TokenType.DELETE: 'DELETE'>, <TokenType.END: 'END'>, <TokenType.ALL: 'ALL'>, <TokenType.WINDOW: 'WINDOW'>, <TokenType.SOME: 'SOME'>, <TokenType.DATABASE: 'DATABASE'>, <TokenType.ANTI: 'ANTI'>, <TokenType.DEFAULT: 'DEFAULT'>, <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, <TokenType.MODEL: 'MODEL'>, <TokenType.KEEP: 'KEEP'>, <TokenType.CASE: 'CASE'>, <TokenType.ISNULL: 'ISNULL'>, <TokenType.SCHEMA: 'SCHEMA'>, <TokenType.OFFSET: 'OFFSET'>, <TokenType.BEGIN: 'BEGIN'>, <TokenType.CACHE: 'CACHE'>, <TokenType.MERGE: 'MERGE'>, <TokenType.SETTINGS: 'SETTINGS'>, <TokenType.VOLATILE: 'VOLATILE'>, <TokenType.EXISTS: 'EXISTS'>, <TokenType.TEMPORARY: 'TEMPORARY'>, <TokenType.LEFT: 'LEFT'>, <TokenType.DESCRIBE: 'DESCRIBE'>}
STATEMENT_PARSERS = {<TokenType.ALTER: 'ALTER'>: <function Parser.<lambda>>, <TokenType.BEGIN: 'BEGIN'>: <function Parser.<lambda>>, <TokenType.CACHE: 'CACHE'>: <function Parser.<lambda>>, <TokenType.COMMIT: 'COMMIT'>: <function Parser.<lambda>>, <TokenType.COMMENT: 'COMMENT'>: <function Parser.<lambda>>, <TokenType.CREATE: 'CREATE'>: <function Parser.<lambda>>, <TokenType.DELETE: 'DELETE'>: <function Parser.<lambda>>, <TokenType.DESC: 'DESC'>: <function Parser.<lambda>>, <TokenType.DESCRIBE: 'DESCRIBE'>: <function Parser.<lambda>>, <TokenType.DROP: 'DROP'>: <function Parser.<lambda>>, <TokenType.INSERT: 'INSERT'>: <function Parser.<lambda>>, <TokenType.KILL: 'KILL'>: <function Parser.<lambda>>, <TokenType.LOAD: 'LOAD'>: <function Parser.<lambda>>, <TokenType.MERGE: 'MERGE'>: <function Parser.<lambda>>, <TokenType.PIVOT: 'PIVOT'>: <function Parser.<lambda>>, <TokenType.PRAGMA: 'PRAGMA'>: <function Parser.<lambda>>, <TokenType.REFRESH: 'REFRESH'>: <function Parser.<lambda>>, <TokenType.ROLLBACK: 'ROLLBACK'>: <function Parser.<lambda>>, <TokenType.SET: 'SET'>: <function Parser.<lambda>>, <TokenType.UNCACHE: 'UNCACHE'>: <function Parser.<lambda>>, <TokenType.UPDATE: 'UPDATE'>: <function Parser.<lambda>>, <TokenType.TRUNCATE: 'TRUNCATE'>: <function Parser.<lambda>>, <TokenType.USE: 'USE'>: <function Parser.<lambda>>, <TokenType.END: 'END'>: <function TSQL.Parser.<lambda>>}
TABLE_ALIAS_TOKENS = {<TokenType.COMMIT: 'COMMIT'>, <TokenType.NVARCHAR: 'NVARCHAR'>, <TokenType.STORAGE_INTEGRATION: 'STORAGE_INTEGRATION'>, <TokenType.INTERVAL: 'INTERVAL'>, <TokenType.OPERATOR: 'OPERATOR'>, <TokenType.UNKNOWN: 'UNKNOWN'>, <TokenType.FORMAT: 'FORMAT'>, <TokenType.TINYTEXT: 'TINYTEXT'>, <TokenType.STRUCT: 'STRUCT'>, <TokenType.REPLACE: 'REPLACE'>, <TokenType.FINAL: 'FINAL'>, <TokenType.DATETIME64: 'DATETIME64'>, <TokenType.CHAR: 'CHAR'>, <TokenType.PIVOT: 'PIVOT'>, <TokenType.FOREIGN_KEY: 'FOREIGN_KEY'>, <TokenType.SMALLINT: 'SMALLINT'>, <TokenType.VIEW: 'VIEW'>, <TokenType.INT128: 'INT128'>, <TokenType.INT256: 'INT256'>, <TokenType.DESC: 'DESC'>, <TokenType.INT4MULTIRANGE: 'INT4MULTIRANGE'>, <TokenType.TEXT: 'TEXT'>, <TokenType.OBJECT_IDENTIFIER: 'OBJECT_IDENTIFIER'>, <TokenType.UTINYINT: 'UTINYINT'>, <TokenType.OVERWRITE: 'OVERWRITE'>, <TokenType.YEAR: 'YEAR'>, <TokenType.TIME: 'TIME'>, <TokenType.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>, <TokenType.BIGINT: 'BIGINT'>, <TokenType.DICTIONARY: 'DICTIONARY'>, <TokenType.CURRENT_USER: 'CURRENT_USER'>, <TokenType.NUMRANGE: 'NUMRANGE'>, <TokenType.ESCAPE: 'ESCAPE'>, <TokenType.PARTITION: 'PARTITION'>, <TokenType.IPV4: 'IPV4'>, <TokenType.AUTO_INCREMENT: 'AUTO_INCREMENT'>, <TokenType.ASC: 'ASC'>, <TokenType.DATE32: 'DATE32'>, <TokenType.IMAGE: 'IMAGE'>, <TokenType.SEMI: 'SEMI'>, <TokenType.BPCHAR: 'BPCHAR'>, <TokenType.INT8MULTIRANGE: 'INT8MULTIRANGE'>, <TokenType.PERCENT: 'PERCENT'>, <TokenType.REFRESH: 'REFRESH'>, <TokenType.INDEX: 'INDEX'>, <TokenType.USE: 'USE'>, <TokenType.PSEUDO_TYPE: 'PSEUDO_TYPE'>, <TokenType.SUPER: 'SUPER'>, <TokenType.ROW: 'ROW'>, <TokenType.TIMETZ: 'TIMETZ'>, <TokenType.CURRENT_DATETIME: 'CURRENT_DATETIME'>, <TokenType.FIXEDSTRING: 'FIXEDSTRING'>, <TokenType.DATEMULTIRANGE: 'DATEMULTIRANGE'>, <TokenType.DECIMAL: 'DECIMAL'>, <TokenType.AGGREGATEFUNCTION: 'AGGREGATEFUNCTION'>, <TokenType.SMALLMONEY: 'SMALLMONEY'>, <TokenType.USMALLINT: 'USMALLINT'>, <TokenType.INT4RANGE: 'INT4RANGE'>, <TokenType.TRUNCATE: 'TRUNCATE'>, <TokenType.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>, <TokenType.UINT128: 'UINT128'>, <TokenType.UBIGINT: 'UBIGINT'>, <TokenType.COMMENT: 'COMMENT'>, <TokenType.PROCEDURE: 'PROCEDURE'>, <TokenType.VARBINARY: 'VARBINARY'>, <TokenType.NCHAR: 'NCHAR'>, <TokenType.TIMESTAMP_MS: 'TIMESTAMP_MS'>, <TokenType.USERDEFINED: 'USERDEFINED'>, <TokenType.DIV: 'DIV'>, <TokenType.ENUM16: 'ENUM16'>, <TokenType.UNPIVOT: 'UNPIVOT'>, <TokenType.CURRENT_TIME: 'CURRENT_TIME'>, <TokenType.TSMULTIRANGE: 'TSMULTIRANGE'>, <TokenType.NUMMULTIRANGE: 'NUMMULTIRANGE'>, <TokenType.SHOW: 'SHOW'>, <TokenType.RANGE: 'RANGE'>, <TokenType.FLOAT: 'FLOAT'>, <TokenType.MEDIUMTEXT: 'MEDIUMTEXT'>, <TokenType.ENUM8: 'ENUM8'>, <TokenType.CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'>, <TokenType.TINYBLOB: 'TINYBLOB'>, <TokenType.NESTED: 'NESTED'>, <TokenType.UUID: 'UUID'>, <TokenType.RECURSIVE: 'RECURSIVE'>, <TokenType.FIRST: 'FIRST'>, <TokenType.TIMESTAMP: 'TIMESTAMP'>, <TokenType.IS: 'IS'>, <TokenType.INT: 'INT'>, <TokenType.FUNCTION: 'FUNCTION'>, <TokenType.ANY: 'ANY'>, <TokenType.VAR: 'VAR'>, <TokenType.BIGDECIMAL: 'BIGDECIMAL'>, <TokenType.MAP: 'MAP'>, <TokenType.UDECIMAL: 'UDECIMAL'>, <TokenType.MEDIUMBLOB: 'MEDIUMBLOB'>, <TokenType.FALSE: 'FALSE'>, <TokenType.SERIAL: 'SERIAL'>, <TokenType.COLUMN: 'COLUMN'>, <TokenType.BIT: 'BIT'>, <TokenType.BIGSERIAL: 'BIGSERIAL'>, <TokenType.FILTER: 'FILTER'>, <TokenType.COLLATE: 'COLLATE'>, <TokenType.IPADDRESS: 'IPADDRESS'>, <TokenType.KILL: 'KILL'>, <TokenType.ROWS: 'ROWS'>, <TokenType.TRUE: 'TRUE'>, <TokenType.COMMAND: 'COMMAND'>, <TokenType.PRAGMA: 'PRAGMA'>, <TokenType.BOOLEAN: 'BOOLEAN'>, <TokenType.TOP: 'TOP'>, <TokenType.TIMESTAMP_NS: 'TIMESTAMP_NS'>, <TokenType.HSTORE: 'HSTORE'>, <TokenType.DATERANGE: 'DATERANGE'>, <TokenType.REFERENCES: 'REFERENCES'>, <TokenType.UNIQUE: 'UNIQUE'>, <TokenType.MEDIUMINT: 'MEDIUMINT'>, <TokenType.SET: 'SET'>, <TokenType.INET: 'INET'>, <TokenType.UMEDIUMINT: 'UMEDIUMINT'>, <TokenType.DATE: 'DATE'>, <TokenType.NULLABLE: 'NULLABLE'>, <TokenType.LONGBLOB: 'LONGBLOB'>, <TokenType.NULL: 'NULL'>, <TokenType.EXECUTE: 'EXECUTE'>, <TokenType.MONEY: 'MONEY'>, <TokenType.LONGTEXT: 'LONGTEXT'>, <TokenType.JSONB: 'JSONB'>, <TokenType.SMALLSERIAL: 'SMALLSERIAL'>, <TokenType.ORDINALITY: 'ORDINALITY'>, <TokenType.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <TokenType.CONSTRAINT: 'CONSTRAINT'>, <TokenType.TSTZRANGE: 'TSTZRANGE'>, <TokenType.UPDATE: 'UPDATE'>, <TokenType.BINARY: 'BINARY'>, <TokenType.NEXT: 'NEXT'>, <TokenType.SIMPLEAGGREGATEFUNCTION: 'SIMPLEAGGREGATEFUNCTION'>, <TokenType.LOAD: 'LOAD'>, <TokenType.OVERLAPS: 'OVERLAPS'>, <TokenType.DELETE: 'DELETE'>, <TokenType.GEOGRAPHY: 'GEOGRAPHY'>, <TokenType.END: 'END'>, <TokenType.DOUBLE: 'DOUBLE'>, <TokenType.ALL: 'ALL'>, <TokenType.SOME: 'SOME'>, <TokenType.ARRAY: 'ARRAY'>, <TokenType.DATABASE: 'DATABASE'>, <TokenType.ANTI: 'ANTI'>, <TokenType.DEFAULT: 'DEFAULT'>, <TokenType.UINT256: 'UINT256'>, <TokenType.INT8RANGE: 'INT8RANGE'>, <TokenType.CURRENT_DATE: 'CURRENT_DATE'>, <TokenType.TIMESTAMP_S: 'TIMESTAMP_S'>, <TokenType.MODEL: 'MODEL'>, <TokenType.KEEP: 'KEEP'>, <TokenType.CASE: 'CASE'>, <TokenType.ISNULL: 'ISNULL'>, <TokenType.TINYINT: 'TINYINT'>, <TokenType.SCHEMA: 'SCHEMA'>, <TokenType.GEOMETRY: 'GEOMETRY'>, <TokenType.VARIANT: 'VARIANT'>, <TokenType.LOWCARDINALITY: 'LOWCARDINALITY'>, <TokenType.BEGIN: 'BEGIN'>, <TokenType.CACHE: 'CACHE'>, <TokenType.MERGE: 'MERGE'>, <TokenType.SETTINGS: 'SETTINGS'>, <TokenType.HLLSKETCH: 'HLLSKETCH'>, <TokenType.ROWVERSION: 'ROWVERSION'>, <TokenType.TABLE: 'TABLE'>, <TokenType.VARCHAR: 'VARCHAR'>, <TokenType.ENUM: 'ENUM'>, <TokenType.XML: 'XML'>, <TokenType.VOLATILE: 'VOLATILE'>, <TokenType.IPPREFIX: 'IPPREFIX'>, <TokenType.DATETIME: 'DATETIME'>, <TokenType.TSRANGE: 'TSRANGE'>, <TokenType.EXISTS: 'EXISTS'>, <TokenType.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <TokenType.TEMPORARY: 'TEMPORARY'>, <TokenType.JSON: 'JSON'>, <TokenType.UINT: 'UINT'>, <TokenType.OBJECT: 'OBJECT'>, <TokenType.DESCRIBE: 'DESCRIBE'>, <TokenType.IPV6: 'IPV6'>}
SHOW_TRIE: Dict = {}
SET_TRIE: Dict = {'GLOBAL': {0: True}, 'LOCAL': {0: True}, 'SESSION': {0: True}, 'TRANSACTION': {0: True}}
Inherited Members
sqlglot.parser.Parser
Parser
NO_PAREN_FUNCTIONS
STRUCT_TYPE_TOKENS
NESTED_TYPE_TOKENS
ENUM_TYPE_TOKENS
AGGREGATE_TYPE_TOKENS
TYPE_TOKENS
SIGNED_TO_UNSIGNED_TYPE_TOKEN
SUBQUERY_PREDICATES
RESERVED_TOKENS
DB_CREATABLES
CREATABLES
ID_VAR_TOKENS
INTERVAL_VARS
COMMENT_TABLE_ALIAS_TOKENS
UPDATE_ALIAS_TOKENS
TRIM_TYPES
FUNC_TOKENS
CONJUNCTION
EQUALITY
COMPARISON
BITWISE
TERM
FACTOR
EXPONENT
TIMES
TIMESTAMPS
SET_OPERATIONS
JOIN_METHODS
JOIN_SIDES
JOIN_KINDS
LAMBDAS
COLUMN_OPERATORS
EXPRESSION_PARSERS
UNARY_PARSERS
STRING_PARSERS
NUMERIC_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
KEY_VALUE_DEFINITIONS
FUNCTION_PARSERS
SET_PARSERS
SHOW_PARSERS
TYPE_LITERAL_PARSERS
DDL_SELECT_TOKENS
PRE_VOLATILE_TOKENS
TRANSACTION_KIND
TRANSACTION_CHARACTERISTICS
USABLES
INSERT_ALTERNATIVES
CLONE_KEYWORDS
HISTORICAL_DATA_KIND
OPCLASS_FOLLOW_KEYWORDS
OPTYPE_FOLLOW_TOKENS
TABLE_INDEX_HINT_TOKENS
WINDOW_ALIAS_TOKENS
WINDOW_BEFORE_PAREN_TOKENS
WINDOW_SIDES
JSON_KEY_VALUE_SEPARATOR_TOKENS
FETCH_TOKENS
ADD_CONSTRAINT_TOKENS
DISTINCT_TOKENS
NULL_TOKENS
UNNEST_OFFSET_ALIAS_TOKENS
STRICT_CAST
PREFIXED_PIVOT_COLUMNS
IDENTIFY_PIVOT_STRINGS
TABLESAMPLE_CSV
TRIM_PATTERN_FIRST
MODIFIERS_ATTACHED_TO_UNION
UNION_MODIFIERS
JSON_ARROWS_REQUIRE_JSON_TYPE
VALUES_FOLLOWED_BY_PAREN
SUPPORTS_IMPLICIT_UNNEST
error_level
error_message_context
max_errors
dialect
reset
parse
parse_into
check_errors
raise_error
expression
validate_expression
errors
sql
class TSQL.Generator(sqlglot.generator.Generator):
 713    class Generator(generator.Generator):
 714        LIMIT_IS_TOP = True
 715        QUERY_HINTS = False
 716        RETURNING_END = False
 717        NVL2_SUPPORTED = False
 718        ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = False
 719        LIMIT_FETCH = "FETCH"
 720        COMPUTED_COLUMN_WITH_TYPE = False
 721        CTE_RECURSIVE_KEYWORD_REQUIRED = False
 722        ENSURE_BOOLS = True
 723        NULL_ORDERING_SUPPORTED = None
 724        SUPPORTS_SINGLE_ARG_CONCAT = False
 725        TABLESAMPLE_SEED_KEYWORD = "REPEATABLE"
 726        SUPPORTS_SELECT_INTO = True
 727        JSON_PATH_BRACKETED_KEY_SUPPORTED = False
 728
 729        EXPRESSIONS_WITHOUT_NESTED_CTES = {
 730            exp.Delete,
 731            exp.Insert,
 732            exp.Merge,
 733            exp.Select,
 734            exp.Subquery,
 735            exp.Union,
 736            exp.Update,
 737        }
 738
 739        SUPPORTED_JSON_PATH_PARTS = {
 740            exp.JSONPathKey,
 741            exp.JSONPathRoot,
 742            exp.JSONPathSubscript,
 743        }
 744
 745        TYPE_MAPPING = {
 746            **generator.Generator.TYPE_MAPPING,
 747            exp.DataType.Type.BOOLEAN: "BIT",
 748            exp.DataType.Type.DECIMAL: "NUMERIC",
 749            exp.DataType.Type.DATETIME: "DATETIME2",
 750            exp.DataType.Type.DOUBLE: "FLOAT",
 751            exp.DataType.Type.INT: "INTEGER",
 752            exp.DataType.Type.TEXT: "VARCHAR(MAX)",
 753            exp.DataType.Type.TIMESTAMP: "DATETIME2",
 754            exp.DataType.Type.TIMESTAMPTZ: "DATETIMEOFFSET",
 755            exp.DataType.Type.VARIANT: "SQL_VARIANT",
 756        }
 757
 758        TYPE_MAPPING.pop(exp.DataType.Type.NCHAR)
 759        TYPE_MAPPING.pop(exp.DataType.Type.NVARCHAR)
 760
 761        TRANSFORMS = {
 762            **generator.Generator.TRANSFORMS,
 763            exp.AnyValue: any_value_to_max_sql,
 764            exp.AutoIncrementColumnConstraint: lambda *_: "IDENTITY",
 765            exp.DateAdd: date_delta_sql("DATEADD"),
 766            exp.DateDiff: date_delta_sql("DATEDIFF"),
 767            exp.CTE: transforms.preprocess([qualify_derived_table_outputs]),
 768            exp.CurrentDate: rename_func("GETDATE"),
 769            exp.CurrentTimestamp: rename_func("GETDATE"),
 770            exp.Extract: rename_func("DATEPART"),
 771            exp.GeneratedAsIdentityColumnConstraint: generatedasidentitycolumnconstraint_sql,
 772            exp.GroupConcat: _string_agg_sql,
 773            exp.If: rename_func("IIF"),
 774            exp.JSONExtract: _json_extract_sql,
 775            exp.JSONExtractScalar: _json_extract_sql,
 776            exp.LastDay: lambda self, e: self.func("EOMONTH", e.this),
 777            exp.Max: max_or_greatest,
 778            exp.MD5: lambda self, e: self.func("HASHBYTES", exp.Literal.string("MD5"), e.this),
 779            exp.Min: min_or_least,
 780            exp.NumberToStr: _format_sql,
 781            exp.ParseJSON: lambda self, e: self.sql(e, "this"),
 782            exp.Select: transforms.preprocess(
 783                [
 784                    transforms.eliminate_distinct_on,
 785                    transforms.eliminate_semi_and_anti_joins,
 786                    transforms.eliminate_qualify,
 787                ]
 788            ),
 789            exp.StrPosition: lambda self, e: self.func(
 790                "CHARINDEX", e.args.get("substr"), e.this, e.args.get("position")
 791            ),
 792            exp.Subquery: transforms.preprocess([qualify_derived_table_outputs]),
 793            exp.SHA: lambda self, e: self.func("HASHBYTES", exp.Literal.string("SHA1"), e.this),
 794            exp.SHA2: lambda self, e: self.func(
 795                "HASHBYTES", exp.Literal.string(f"SHA2_{e.args.get('length', 256)}"), e.this
 796            ),
 797            exp.TemporaryProperty: lambda self, e: "",
 798            exp.TimeStrToTime: timestrtotime_sql,
 799            exp.TimeToStr: _format_sql,
 800            exp.Trim: trim_sql,
 801            exp.TsOrDsAdd: date_delta_sql("DATEADD", cast=True),
 802            exp.TsOrDsDiff: date_delta_sql("DATEDIFF"),
 803        }
 804
 805        TRANSFORMS.pop(exp.ReturnsProperty)
 806
 807        PROPERTIES_LOCATION = {
 808            **generator.Generator.PROPERTIES_LOCATION,
 809            exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED,
 810        }
 811
 812        def convert_sql(self, expression: exp.Convert) -> str:
 813            name = "TRY_CONVERT" if expression.args.get("safe") else "CONVERT"
 814            return self.func(
 815                name, expression.this, expression.expression, expression.args.get("style")
 816            )
 817
 818        def queryoption_sql(self, expression: exp.QueryOption) -> str:
 819            option = self.sql(expression, "this")
 820            value = self.sql(expression, "expression")
 821            if value:
 822                optional_equal_sign = "= " if option in OPTIONS_THAT_REQUIRE_EQUAL else ""
 823                return f"{option} {optional_equal_sign}{value}"
 824            return option
 825
 826        def lateral_op(self, expression: exp.Lateral) -> str:
 827            cross_apply = expression.args.get("cross_apply")
 828            if cross_apply is True:
 829                return "CROSS APPLY"
 830            if cross_apply is False:
 831                return "OUTER APPLY"
 832
 833            # TODO: perhaps we can check if the parent is a Join and transpile it appropriately
 834            self.unsupported("LATERAL clause is not supported.")
 835            return "LATERAL"
 836
 837        def timefromparts_sql(self, expression: exp.TimeFromParts) -> str:
 838            nano = expression.args.get("nano")
 839            if nano is not None:
 840                nano.pop()
 841                self.unsupported("Specifying nanoseconds is not supported in TIMEFROMPARTS.")
 842
 843            if expression.args.get("fractions") is None:
 844                expression.set("fractions", exp.Literal.number(0))
 845            if expression.args.get("precision") is None:
 846                expression.set("precision", exp.Literal.number(0))
 847
 848            return rename_func("TIMEFROMPARTS")(self, expression)
 849
 850        def timestampfromparts_sql(self, expression: exp.TimestampFromParts) -> str:
 851            zone = expression.args.get("zone")
 852            if zone is not None:
 853                zone.pop()
 854                self.unsupported("Time zone is not supported in DATETIMEFROMPARTS.")
 855
 856            nano = expression.args.get("nano")
 857            if nano is not None:
 858                nano.pop()
 859                self.unsupported("Specifying nanoseconds is not supported in DATETIMEFROMPARTS.")
 860
 861            if expression.args.get("milli") is None:
 862                expression.set("milli", exp.Literal.number(0))
 863
 864            return rename_func("DATETIMEFROMPARTS")(self, expression)
 865
 866        def set_operation(self, expression: exp.Union, op: str) -> str:
 867            limit = expression.args.get("limit")
 868            if limit:
 869                return self.sql(expression.limit(limit.pop(), copy=False))
 870
 871            return super().set_operation(expression, op)
 872
 873        def setitem_sql(self, expression: exp.SetItem) -> str:
 874            this = expression.this
 875            if isinstance(this, exp.EQ) and not isinstance(this.left, exp.Parameter):
 876                # T-SQL does not use '=' in SET command, except when the LHS is a variable.
 877                return f"{self.sql(this.left)} {self.sql(this.right)}"
 878
 879            return super().setitem_sql(expression)
 880
 881        def boolean_sql(self, expression: exp.Boolean) -> str:
 882            if type(expression.parent) in BIT_TYPES:
 883                return "1" if expression.this else "0"
 884
 885            return "(1 = 1)" if expression.this else "(1 = 0)"
 886
 887        def is_sql(self, expression: exp.Is) -> str:
 888            if isinstance(expression.expression, exp.Boolean):
 889                return self.binary(expression, "=")
 890            return self.binary(expression, "IS")
 891
 892        def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
 893            sql = self.sql(expression, "this")
 894            properties = expression.args.get("properties")
 895
 896            if sql[:1] != "#" and any(
 897                isinstance(prop, exp.TemporaryProperty)
 898                for prop in (properties.expressions if properties else [])
 899            ):
 900                sql = f"#{sql}"
 901
 902            return sql
 903
 904        def create_sql(self, expression: exp.Create) -> str:
 905            kind = expression.kind
 906            exists = expression.args.pop("exists", None)
 907            sql = super().create_sql(expression)
 908
 909            like_property = expression.find(exp.LikeProperty)
 910            if like_property:
 911                ctas_expression = like_property.this
 912            else:
 913                ctas_expression = expression.expression
 914
 915            table = expression.find(exp.Table)
 916
 917            # Convert CTAS statement to SELECT .. INTO ..
 918            if kind == "TABLE" and ctas_expression:
 919                ctas_with = ctas_expression.args.get("with")
 920                if ctas_with:
 921                    ctas_with = ctas_with.pop()
 922
 923                if isinstance(ctas_expression, exp.UNWRAPPED_QUERIES):
 924                    ctas_expression = ctas_expression.subquery()
 925
 926                select_into = exp.select("*").from_(exp.alias_(ctas_expression, "temp", table=True))
 927                select_into.set("into", exp.Into(this=table))
 928                select_into.set("with", ctas_with)
 929
 930                if like_property:
 931                    select_into.limit(0, copy=False)
 932
 933                sql = self.sql(select_into)
 934
 935            if exists:
 936                identifier = self.sql(exp.Literal.string(exp.table_name(table) if table else ""))
 937                sql = self.sql(exp.Literal.string(sql))
 938                if kind == "SCHEMA":
 939                    sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.schemata WHERE schema_name = {identifier}) EXEC({sql})"""
 940                elif kind == "TABLE":
 941                    assert table
 942                    where = exp.and_(
 943                        exp.column("table_name").eq(table.name),
 944                        exp.column("table_schema").eq(table.db) if table.db else None,
 945                        exp.column("table_catalog").eq(table.catalog) if table.catalog else None,
 946                    )
 947                    sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.tables WHERE {where}) EXEC({sql})"""
 948                elif kind == "INDEX":
 949                    index = self.sql(exp.Literal.string(expression.this.text("this")))
 950                    sql = f"""IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id({identifier}) AND name = {index}) EXEC({sql})"""
 951            elif expression.args.get("replace"):
 952                sql = sql.replace("CREATE OR REPLACE ", "CREATE OR ALTER ", 1)
 953
 954            return self.prepend_ctes(expression, sql)
 955
 956        def offset_sql(self, expression: exp.Offset) -> str:
 957            return f"{super().offset_sql(expression)} ROWS"
 958
 959        def version_sql(self, expression: exp.Version) -> str:
 960            name = "SYSTEM_TIME" if expression.name == "TIMESTAMP" else expression.name
 961            this = f"FOR {name}"
 962            expr = expression.expression
 963            kind = expression.text("kind")
 964            if kind in ("FROM", "BETWEEN"):
 965                args = expr.expressions
 966                sep = "TO" if kind == "FROM" else "AND"
 967                expr_sql = f"{self.sql(seq_get(args, 0))} {sep} {self.sql(seq_get(args, 1))}"
 968            else:
 969                expr_sql = self.sql(expr)
 970
 971            expr_sql = f" {expr_sql}" if expr_sql else ""
 972            return f"{this} {kind}{expr_sql}"
 973
 974        def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str:
 975            table = expression.args.get("table")
 976            table = f"{table} " if table else ""
 977            return f"RETURNS {table}{self.sql(expression, 'this')}"
 978
 979        def returning_sql(self, expression: exp.Returning) -> str:
 980            into = self.sql(expression, "into")
 981            into = self.seg(f"INTO {into}") if into else ""
 982            return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}"
 983
 984        def transaction_sql(self, expression: exp.Transaction) -> str:
 985            this = self.sql(expression, "this")
 986            this = f" {this}" if this else ""
 987            mark = self.sql(expression, "mark")
 988            mark = f" WITH MARK {mark}" if mark else ""
 989            return f"BEGIN TRANSACTION{this}{mark}"
 990
 991        def commit_sql(self, expression: exp.Commit) -> str:
 992            this = self.sql(expression, "this")
 993            this = f" {this}" if this else ""
 994            durability = expression.args.get("durability")
 995            durability = (
 996                f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})"
 997                if durability is not None
 998                else ""
 999            )
1000            return f"COMMIT TRANSACTION{this}{durability}"
1001
1002        def rollback_sql(self, expression: exp.Rollback) -> str:
1003            this = self.sql(expression, "this")
1004            this = f" {this}" if this else ""
1005            return f"ROLLBACK TRANSACTION{this}"
1006
1007        def identifier_sql(self, expression: exp.Identifier) -> str:
1008            identifier = super().identifier_sql(expression)
1009
1010            if expression.args.get("global"):
1011                identifier = f"##{identifier}"
1012            elif expression.args.get("temporary"):
1013                identifier = f"#{identifier}"
1014
1015            return identifier
1016
1017        def constraint_sql(self, expression: exp.Constraint) -> str:
1018            this = self.sql(expression, "this")
1019            expressions = self.expressions(expression, flat=True, sep=" ")
1020            return f"CONSTRAINT {this} {expressions}"
1021
1022        def length_sql(self, expression: exp.Length) -> str:
1023            return self._uncast_text(expression, "LEN")
1024
1025        def right_sql(self, expression: exp.Right) -> str:
1026            return self._uncast_text(expression, "RIGHT")
1027
1028        def left_sql(self, expression: exp.Left) -> str:
1029            return self._uncast_text(expression, "LEFT")
1030
1031        def _uncast_text(self, expression: exp.Expression, name: str) -> str:
1032            this = expression.this
1033            if isinstance(this, exp.Cast) and this.is_type(exp.DataType.Type.TEXT):
1034                this_sql = self.sql(this, "this")
1035            else:
1036                this_sql = self.sql(this)
1037            expression_sql = self.sql(expression, "expression")
1038            return self.func(name, this_sql, expression_sql if expression_sql else None)
1039
1040        def partition_sql(self, expression: exp.Partition) -> str:
1041            return f"WITH (PARTITIONS({self.expressions(expression, flat=True)}))"

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

Arguments:
  • pretty: Whether 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 to normalize identifiers to lowercase. Default: False.
  • pad: The pad size in a formatted string. Default: 2.
  • indent: The indentation size in a formatted string. Default: 2.
  • normalize_functions: How to normalize 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: Whether 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 to preserve comments in the output SQL code. Default: True
LIMIT_IS_TOP = True
QUERY_HINTS = False
RETURNING_END = False
NVL2_SUPPORTED = False
ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = False
LIMIT_FETCH = 'FETCH'
COMPUTED_COLUMN_WITH_TYPE = False
CTE_RECURSIVE_KEYWORD_REQUIRED = False
ENSURE_BOOLS = True
NULL_ORDERING_SUPPORTED = None
SUPPORTS_SINGLE_ARG_CONCAT = False
TABLESAMPLE_SEED_KEYWORD = 'REPEATABLE'
SUPPORTS_SELECT_INTO = True
JSON_PATH_BRACKETED_KEY_SUPPORTED = False
TYPE_MAPPING = {<Type.MEDIUMTEXT: 'MEDIUMTEXT'>: 'TEXT', <Type.LONGTEXT: 'LONGTEXT'>: 'TEXT', <Type.TINYTEXT: 'TINYTEXT'>: 'TEXT', <Type.MEDIUMBLOB: 'MEDIUMBLOB'>: 'BLOB', <Type.LONGBLOB: 'LONGBLOB'>: 'BLOB', <Type.TINYBLOB: 'TINYBLOB'>: 'BLOB', <Type.INET: 'INET'>: 'INET', <Type.BOOLEAN: 'BOOLEAN'>: 'BIT', <Type.DECIMAL: 'DECIMAL'>: 'NUMERIC', <Type.DATETIME: 'DATETIME'>: 'DATETIME2', <Type.DOUBLE: 'DOUBLE'>: 'FLOAT', <Type.INT: 'INT'>: 'INTEGER', <Type.TEXT: 'TEXT'>: 'VARCHAR(MAX)', <Type.TIMESTAMP: 'TIMESTAMP'>: 'DATETIME2', <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>: 'DATETIMEOFFSET', <Type.VARIANT: 'VARIANT'>: 'SQL_VARIANT'}
TRANSFORMS = {<class 'sqlglot.expressions.JSONPathKey'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathRoot'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSubscript'>: <function <lambda>>, <class 'sqlglot.expressions.AutoRefreshProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CaseSpecificColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CommentColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DateAdd'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.DateFormatColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DefaultColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EncodeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExternalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.HeapProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InheritsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InlineLengthColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.IntervalSpan'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.JSONExtract'>: <function _json_extract_sql>, <class 'sqlglot.expressions.JSONExtractScalar'>: <function _json_extract_sql>, <class 'sqlglot.expressions.LanguageProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LocationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.MaterializedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NonClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NotForReplicationColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnCommitProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnUpdateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OutputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SampleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetConfigProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlReadWriteProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StabilityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TemporaryProperty'>: <function TSQL.Generator.<lambda>>, <class 'sqlglot.expressions.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Timestamp'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VarMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AnyValue'>: <function any_value_to_max_sql>, <class 'sqlglot.expressions.AutoIncrementColumnConstraint'>: <function TSQL.Generator.<lambda>>, <class 'sqlglot.expressions.DateDiff'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.CTE'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.CurrentDate'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.CurrentTimestamp'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.Extract'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.GeneratedAsIdentityColumnConstraint'>: <function generatedasidentitycolumnconstraint_sql>, <class 'sqlglot.expressions.GroupConcat'>: <function _string_agg_sql>, <class 'sqlglot.expressions.If'>: <function rename_func.<locals>.<lambda>>, <class 'sqlglot.expressions.LastDay'>: <function TSQL.Generator.<lambda>>, <class 'sqlglot.expressions.Max'>: <function max_or_greatest>, <class 'sqlglot.expressions.MD5'>: <function TSQL.Generator.<lambda>>, <class 'sqlglot.expressions.Min'>: <function min_or_least>, <class 'sqlglot.expressions.NumberToStr'>: <function _format_sql>, <class 'sqlglot.expressions.ParseJSON'>: <function TSQL.Generator.<lambda>>, <class 'sqlglot.expressions.Select'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.StrPosition'>: <function TSQL.Generator.<lambda>>, <class 'sqlglot.expressions.Subquery'>: <function preprocess.<locals>._to_sql>, <class 'sqlglot.expressions.SHA'>: <function TSQL.Generator.<lambda>>, <class 'sqlglot.expressions.SHA2'>: <function TSQL.Generator.<lambda>>, <class 'sqlglot.expressions.TimeStrToTime'>: <function timestrtotime_sql>, <class 'sqlglot.expressions.TimeToStr'>: <function _format_sql>, <class 'sqlglot.expressions.Trim'>: <function trim_sql>, <class 'sqlglot.expressions.TsOrDsAdd'>: <function date_delta_sql.<locals>._delta_sql>, <class 'sqlglot.expressions.TsOrDsDiff'>: <function date_delta_sql.<locals>._delta_sql>}
PROPERTIES_LOCATION = {<class 'sqlglot.expressions.AlgorithmProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.AutoIncrementProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.AutoRefreshProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.BlockCompressionProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CharacterSetProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ChecksumProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CollateProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Cluster'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ClusteredByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DataBlocksizeProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.DefinerProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.DictRange'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DictProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistStyleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EngineProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExternalProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.FallbackProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.FileFormatProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.FreespaceProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.HeapProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.InheritsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.InputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.IsolatedLoadingProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.JournalProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.LanguageProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LikeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LocationProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LockProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LockingProperty'>: <Location.POST_ALIAS: 'POST_ALIAS'>, <class 'sqlglot.expressions.LogProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.MaterializedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.MergeBlockRatioProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.OnProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OnCommitProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.Order'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OutputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PartitionedByProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.PartitionedOfProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PrimaryKey'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Property'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ReturnsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatDelimitedProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatSerdeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SampleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SchemaCommentProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SerdeProperties'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Set'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SettingsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SetProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.SetConfigProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SortKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlReadWriteProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StabilityProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TemporaryProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.ToTableProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TransientProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.TransformModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.MergeTreeTTL'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.VolatileProperty'>: <Location.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.WithDataProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.WithSystemVersioningProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>}
def convert_sql(self, expression: sqlglot.expressions.Convert) -> str:
812        def convert_sql(self, expression: exp.Convert) -> str:
813            name = "TRY_CONVERT" if expression.args.get("safe") else "CONVERT"
814            return self.func(
815                name, expression.this, expression.expression, expression.args.get("style")
816            )
def queryoption_sql(self, expression: sqlglot.expressions.QueryOption) -> str:
818        def queryoption_sql(self, expression: exp.QueryOption) -> str:
819            option = self.sql(expression, "this")
820            value = self.sql(expression, "expression")
821            if value:
822                optional_equal_sign = "= " if option in OPTIONS_THAT_REQUIRE_EQUAL else ""
823                return f"{option} {optional_equal_sign}{value}"
824            return option
def lateral_op(self, expression: sqlglot.expressions.Lateral) -> str:
826        def lateral_op(self, expression: exp.Lateral) -> str:
827            cross_apply = expression.args.get("cross_apply")
828            if cross_apply is True:
829                return "CROSS APPLY"
830            if cross_apply is False:
831                return "OUTER APPLY"
832
833            # TODO: perhaps we can check if the parent is a Join and transpile it appropriately
834            self.unsupported("LATERAL clause is not supported.")
835            return "LATERAL"
def timefromparts_sql(self, expression: sqlglot.expressions.TimeFromParts) -> str:
837        def timefromparts_sql(self, expression: exp.TimeFromParts) -> str:
838            nano = expression.args.get("nano")
839            if nano is not None:
840                nano.pop()
841                self.unsupported("Specifying nanoseconds is not supported in TIMEFROMPARTS.")
842
843            if expression.args.get("fractions") is None:
844                expression.set("fractions", exp.Literal.number(0))
845            if expression.args.get("precision") is None:
846                expression.set("precision", exp.Literal.number(0))
847
848            return rename_func("TIMEFROMPARTS")(self, expression)
def timestampfromparts_sql(self, expression: sqlglot.expressions.TimestampFromParts) -> str:
850        def timestampfromparts_sql(self, expression: exp.TimestampFromParts) -> str:
851            zone = expression.args.get("zone")
852            if zone is not None:
853                zone.pop()
854                self.unsupported("Time zone is not supported in DATETIMEFROMPARTS.")
855
856            nano = expression.args.get("nano")
857            if nano is not None:
858                nano.pop()
859                self.unsupported("Specifying nanoseconds is not supported in DATETIMEFROMPARTS.")
860
861            if expression.args.get("milli") is None:
862                expression.set("milli", exp.Literal.number(0))
863
864            return rename_func("DATETIMEFROMPARTS")(self, expression)
def set_operation(self, expression: sqlglot.expressions.Union, op: str) -> str:
866        def set_operation(self, expression: exp.Union, op: str) -> str:
867            limit = expression.args.get("limit")
868            if limit:
869                return self.sql(expression.limit(limit.pop(), copy=False))
870
871            return super().set_operation(expression, op)
def setitem_sql(self, expression: sqlglot.expressions.SetItem) -> str:
873        def setitem_sql(self, expression: exp.SetItem) -> str:
874            this = expression.this
875            if isinstance(this, exp.EQ) and not isinstance(this.left, exp.Parameter):
876                # T-SQL does not use '=' in SET command, except when the LHS is a variable.
877                return f"{self.sql(this.left)} {self.sql(this.right)}"
878
879            return super().setitem_sql(expression)
def boolean_sql(self, expression: sqlglot.expressions.Boolean) -> str:
881        def boolean_sql(self, expression: exp.Boolean) -> str:
882            if type(expression.parent) in BIT_TYPES:
883                return "1" if expression.this else "0"
884
885            return "(1 = 1)" if expression.this else "(1 = 0)"
def is_sql(self, expression: sqlglot.expressions.Is) -> str:
887        def is_sql(self, expression: exp.Is) -> str:
888            if isinstance(expression.expression, exp.Boolean):
889                return self.binary(expression, "=")
890            return self.binary(expression, "IS")
def createable_sql( self, expression: sqlglot.expressions.Create, locations: DefaultDict) -> str:
892        def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
893            sql = self.sql(expression, "this")
894            properties = expression.args.get("properties")
895
896            if sql[:1] != "#" and any(
897                isinstance(prop, exp.TemporaryProperty)
898                for prop in (properties.expressions if properties else [])
899            ):
900                sql = f"#{sql}"
901
902            return sql
def create_sql(self, expression: sqlglot.expressions.Create) -> str:
904        def create_sql(self, expression: exp.Create) -> str:
905            kind = expression.kind
906            exists = expression.args.pop("exists", None)
907            sql = super().create_sql(expression)
908
909            like_property = expression.find(exp.LikeProperty)
910            if like_property:
911                ctas_expression = like_property.this
912            else:
913                ctas_expression = expression.expression
914
915            table = expression.find(exp.Table)
916
917            # Convert CTAS statement to SELECT .. INTO ..
918            if kind == "TABLE" and ctas_expression:
919                ctas_with = ctas_expression.args.get("with")
920                if ctas_with:
921                    ctas_with = ctas_with.pop()
922
923                if isinstance(ctas_expression, exp.UNWRAPPED_QUERIES):
924                    ctas_expression = ctas_expression.subquery()
925
926                select_into = exp.select("*").from_(exp.alias_(ctas_expression, "temp", table=True))
927                select_into.set("into", exp.Into(this=table))
928                select_into.set("with", ctas_with)
929
930                if like_property:
931                    select_into.limit(0, copy=False)
932
933                sql = self.sql(select_into)
934
935            if exists:
936                identifier = self.sql(exp.Literal.string(exp.table_name(table) if table else ""))
937                sql = self.sql(exp.Literal.string(sql))
938                if kind == "SCHEMA":
939                    sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.schemata WHERE schema_name = {identifier}) EXEC({sql})"""
940                elif kind == "TABLE":
941                    assert table
942                    where = exp.and_(
943                        exp.column("table_name").eq(table.name),
944                        exp.column("table_schema").eq(table.db) if table.db else None,
945                        exp.column("table_catalog").eq(table.catalog) if table.catalog else None,
946                    )
947                    sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.tables WHERE {where}) EXEC({sql})"""
948                elif kind == "INDEX":
949                    index = self.sql(exp.Literal.string(expression.this.text("this")))
950                    sql = f"""IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id({identifier}) AND name = {index}) EXEC({sql})"""
951            elif expression.args.get("replace"):
952                sql = sql.replace("CREATE OR REPLACE ", "CREATE OR ALTER ", 1)
953
954            return self.prepend_ctes(expression, sql)
def offset_sql(self, expression: sqlglot.expressions.Offset) -> str:
956        def offset_sql(self, expression: exp.Offset) -> str:
957            return f"{super().offset_sql(expression)} ROWS"
def version_sql(self, expression: sqlglot.expressions.Version) -> str:
959        def version_sql(self, expression: exp.Version) -> str:
960            name = "SYSTEM_TIME" if expression.name == "TIMESTAMP" else expression.name
961            this = f"FOR {name}"
962            expr = expression.expression
963            kind = expression.text("kind")
964            if kind in ("FROM", "BETWEEN"):
965                args = expr.expressions
966                sep = "TO" if kind == "FROM" else "AND"
967                expr_sql = f"{self.sql(seq_get(args, 0))} {sep} {self.sql(seq_get(args, 1))}"
968            else:
969                expr_sql = self.sql(expr)
970
971            expr_sql = f" {expr_sql}" if expr_sql else ""
972            return f"{this} {kind}{expr_sql}"
def returnsproperty_sql(self, expression: sqlglot.expressions.ReturnsProperty) -> str:
974        def returnsproperty_sql(self, expression: exp.ReturnsProperty) -> str:
975            table = expression.args.get("table")
976            table = f"{table} " if table else ""
977            return f"RETURNS {table}{self.sql(expression, 'this')}"
def returning_sql(self, expression: sqlglot.expressions.Returning) -> str:
979        def returning_sql(self, expression: exp.Returning) -> str:
980            into = self.sql(expression, "into")
981            into = self.seg(f"INTO {into}") if into else ""
982            return f"{self.seg('OUTPUT')} {self.expressions(expression, flat=True)}{into}"
def transaction_sql(self, expression: sqlglot.expressions.Transaction) -> str:
984        def transaction_sql(self, expression: exp.Transaction) -> str:
985            this = self.sql(expression, "this")
986            this = f" {this}" if this else ""
987            mark = self.sql(expression, "mark")
988            mark = f" WITH MARK {mark}" if mark else ""
989            return f"BEGIN TRANSACTION{this}{mark}"
def commit_sql(self, expression: sqlglot.expressions.Commit) -> str:
 991        def commit_sql(self, expression: exp.Commit) -> str:
 992            this = self.sql(expression, "this")
 993            this = f" {this}" if this else ""
 994            durability = expression.args.get("durability")
 995            durability = (
 996                f" WITH (DELAYED_DURABILITY = {'ON' if durability else 'OFF'})"
 997                if durability is not None
 998                else ""
 999            )
1000            return f"COMMIT TRANSACTION{this}{durability}"
def rollback_sql(self, expression: sqlglot.expressions.Rollback) -> str:
1002        def rollback_sql(self, expression: exp.Rollback) -> str:
1003            this = self.sql(expression, "this")
1004            this = f" {this}" if this else ""
1005            return f"ROLLBACK TRANSACTION{this}"
def identifier_sql(self, expression: sqlglot.expressions.Identifier) -> str:
1007        def identifier_sql(self, expression: exp.Identifier) -> str:
1008            identifier = super().identifier_sql(expression)
1009
1010            if expression.args.get("global"):
1011                identifier = f"##{identifier}"
1012            elif expression.args.get("temporary"):
1013                identifier = f"#{identifier}"
1014
1015            return identifier
def constraint_sql(self, expression: sqlglot.expressions.Constraint) -> str:
1017        def constraint_sql(self, expression: exp.Constraint) -> str:
1018            this = self.sql(expression, "this")
1019            expressions = self.expressions(expression, flat=True, sep=" ")
1020            return f"CONSTRAINT {this} {expressions}"
def length_sql(self, expression: sqlglot.expressions.Length) -> str:
1022        def length_sql(self, expression: exp.Length) -> str:
1023            return self._uncast_text(expression, "LEN")
def right_sql(self, expression: sqlglot.expressions.Right) -> str:
1025        def right_sql(self, expression: exp.Right) -> str:
1026            return self._uncast_text(expression, "RIGHT")
def left_sql(self, expression: sqlglot.expressions.Left) -> str:
1028        def left_sql(self, expression: exp.Left) -> str:
1029            return self._uncast_text(expression, "LEFT")
def partition_sql(self, expression: sqlglot.expressions.Partition) -> str:
1040        def partition_sql(self, expression: exp.Partition) -> str:
1041            return f"WITH (PARTITIONS({self.expressions(expression, flat=True)}))"
SELECT_KINDS: Tuple[str, ...] = ()
Inherited Members
sqlglot.generator.Generator
Generator
IGNORE_NULLS_IN_FUNC
LOCKING_READS_SUPPORTED
EXPLICIT_UNION
WRAP_DERIVED_VALUES
CREATE_FUNCTION_RETURN_AS
MATCHED_BY_SOURCE
SINGLE_STRING_INTERVAL
INTERVAL_ALLOWS_PLURAL_FORM
LIMIT_ONLY_LITERALS
RENAME_TABLE_WITH_DB
GROUPINGS_SEP
INDEX_ON
JOIN_HINTS
TABLE_HINTS
QUERY_HINT_SEP
IS_BOOL_ALLOWED
DUPLICATE_KEY_UPDATE_WITH_SET
COLUMN_JOIN_MARKS_SUPPORTED
EXTRACT_ALLOWS_QUOTES
TZ_TO_WITH_TIME_ZONE
VALUES_AS_TABLE
UNNEST_WITH_ORDINALITY
AGGREGATE_FILTER_SUPPORTED
SEMI_ANTI_JOIN_WITH_SIDE
SUPPORTS_TABLE_COPY
TABLESAMPLE_REQUIRES_PARENS
TABLESAMPLE_SIZE_IS_ROWS
TABLESAMPLE_KEYWORDS
TABLESAMPLE_WITH_METHOD
COLLATE_IS_FUNC
DATA_TYPE_SPECIFIERS_ALLOWED
LAST_DAY_SUPPORTS_DATE_PART
SUPPORTS_TABLE_ALIAS_COLUMNS
UNPIVOT_ALIASES_ARE_IDENTIFIERS
JSON_KEY_VALUE_PAIR_SEP
INSERT_OVERWRITE
SUPPORTS_UNLOGGED_TABLES
SUPPORTS_CREATE_TABLE_LIKE
LIKE_PROPERTY_INSIDE_SCHEMA
MULTI_ARG_DISTINCT
JSON_TYPE_REQUIRED_FOR_EXTRACTION
JSON_PATH_SINGLE_QUOTE_ESCAPE
CAN_IMPLEMENT_ARRAY_ANY
STAR_MAPPING
TIME_PART_SINGULARS
TOKEN_MAPPING
STRUCT_DELIMITER
PARAMETER_TOKEN
NAMED_PLACEHOLDER_TOKEN
RESERVED_KEYWORDS
WITH_SEPARATED_COMMENTS
EXCLUDE_COMMENTS
UNWRAPPED_INTERVAL_VALUES
PARAMETERIZABLE_TEXT_TYPES
SENTINEL_LINE_BREAK
pretty
identify
normalize
pad
unsupported_level
max_unsupported
leading_comma
max_text_width
comments
dialect
normalize_functions
unsupported_messages
generate
preprocess
unsupported
sep
seg
pad_comment
maybe_comment
wrap
no_identify
normalize_func
indent
sql
uncache_sql
cache_sql
characterset_sql
column_sql
columnposition_sql
columndef_sql
columnconstraint_sql
computedcolumnconstraint_sql
autoincrementcolumnconstraint_sql
compresscolumnconstraint_sql
generatedasidentitycolumnconstraint_sql
generatedasrowcolumnconstraint_sql
periodforsystemtimeconstraint_sql
notnullcolumnconstraint_sql
transformcolumnconstraint_sql
primarykeycolumnconstraint_sql
uniquecolumnconstraint_sql
clone_sql
describe_sql
heredoc_sql
prepend_ctes
with_sql
cte_sql
tablealias_sql
bitstring_sql
hexstring_sql
bytestring_sql
unicodestring_sql
rawstring_sql
datatypeparam_sql
datatype_sql
directory_sql
delete_sql
drop_sql
except_sql
except_op
fetch_sql
filter_sql
hint_sql
index_sql
inputoutputformat_sql
national_sql
properties_sql
root_properties
properties
with_properties
locate_properties
property_name
property_sql
likeproperty_sql
fallbackproperty_sql
journalproperty_sql
freespaceproperty_sql
checksumproperty_sql
mergeblockratioproperty_sql
datablocksizeproperty_sql
blockcompressionproperty_sql
isolatedloadingproperty_sql
partitionboundspec_sql
partitionedofproperty_sql
lockingproperty_sql
withdataproperty_sql
withsystemversioningproperty_sql
insert_sql
intersect_sql
intersect_op
introducer_sql
kill_sql
pseudotype_sql
objectidentifier_sql
onconflict_sql
rowformatdelimitedproperty_sql
withtablehint_sql
indextablehint_sql
historicaldata_sql
table_parts
table_sql
tablesample_sql
pivot_sql
tuple_sql
update_sql
values_sql
var_sql
into_sql
from_sql
group_sql
having_sql
connect_sql
prior_sql
join_sql
lambda_sql
lateral_sql
limit_sql
set_sql
pragma_sql
lock_sql
literal_sql
escape_str
loaddata_sql
null_sql
order_sql
withfill_sql
cluster_sql
distribute_sql
sort_sql
ordered_sql
matchrecognize_sql
query_modifiers
offset_limit_modifiers
after_having_modifiers
after_limit_modifiers
select_sql
schema_sql
schema_columns_sql
star_sql
parameter_sql
sessionparameter_sql
placeholder_sql
subquery_sql
qualify_sql
union_sql
union_op
unnest_sql
prewhere_sql
where_sql
window_sql
partition_by_sql
windowspec_sql
withingroup_sql
between_sql
bracket_sql
all_sql
any_sql
exists_sql
case_sql
nextvaluefor_sql
extract_sql
trim_sql
convert_concat_args
concat_sql
concatws_sql
check_sql
foreignkey_sql
primarykey_sql
if_sql
matchagainst_sql
jsonkeyvalue_sql
jsonpath_sql
json_path_part
formatjson_sql
jsonobject_sql
jsonobjectagg_sql
jsonarray_sql
jsonarrayagg_sql
jsoncolumndef_sql
jsonschema_sql
jsontable_sql
openjsoncolumndef_sql
openjson_sql
in_sql
in_unnest_op
interval_sql
return_sql
reference_sql
anonymous_sql
paren_sql
neg_sql
not_sql
alias_sql
pivotalias_sql
aliases_sql
atindex_sql
attimezone_sql
fromtimezone_sql
add_sql
and_sql
xor_sql
connector_sql
bitwiseand_sql
bitwiseleftshift_sql
bitwisenot_sql
bitwiseor_sql
bitwiserightshift_sql
bitwisexor_sql
cast_sql
currentdate_sql
currenttimestamp_sql
collate_sql
command_sql
comment_sql
mergetreettlaction_sql
mergetreettl_sql
altercolumn_sql
renametable_sql
renamecolumn_sql
altertable_sql
add_column_sql
droppartition_sql
addconstraint_sql
distinct_sql
ignorenulls_sql
respectnulls_sql
havingmax_sql
intdiv_sql
dpipe_sql
div_sql
overlaps_sql
distance_sql
dot_sql
eq_sql
propertyeq_sql
escape_sql
glob_sql
gt_sql
gte_sql
ilike_sql
ilikeany_sql
like_sql
likeany_sql
similarto_sql
lt_sql
lte_sql
mod_sql
mul_sql
neq_sql
nullsafeeq_sql
nullsafeneq_sql
or_sql
slice_sql
sub_sql
trycast_sql
log_sql
use_sql
binary
function_fallback_sql
func
format_args
text_width
format_time
expressions
op_expressions
naked_property
tag_sql
token_sql
userdefinedfunction_sql
joinhint_sql
kwarg_sql
when_sql
merge_sql
tochar_sql
dictproperty_sql
dictrange_sql
dictsubproperty_sql
oncluster_sql
clusteredbyproperty_sql
anyvalue_sql
querytransform_sql
indexconstraintoption_sql
checkcolumnconstraint_sql
indexcolumnconstraint_sql
nvl2_sql
comprehension_sql
columnprefix_sql
opclass_sql
predict_sql
forin_sql
refresh_sql
operator_sql
toarray_sql
tsordstotime_sql
tsordstodate_sql
unixdate_sql
lastday_sql
arrayany_sql
generateseries_sql
struct_sql
partitionrange_sql
truncatetable_sql