sqlglot.generator API documentation

Edit on GitHub

# sqlglot.generator

View Source

       1from __future__ import annotations
       2
       3import logging
       4import typing as t
       5
       6from sqlglot import exp
       7from sqlglot.errors import ErrorLevel, UnsupportedError, concat_messages
       8from sqlglot.helper import apply_index_offset, csv, seq_get
       9from sqlglot.time import format_time
      10from sqlglot.tokens import TokenType
      11
      12logger = logging.getLogger("sqlglot")
      13
      14
      15class Generator:
      16    """
      17    Generator converts a given syntax tree to the corresponding SQL string.
      18
      19    Args:
      20        pretty: Whether or not to format the produced SQL string.
      21            Default: False.
      22        identify: Determines when an identifier should be quoted. Possible values are:
      23            False (default): Never quote, except in cases where it's mandatory by the dialect.
      24            True or 'always': Always quote.
      25            'safe': Only quote identifiers that are case insensitive.
      26        normalize: Whether or not to normalize identifiers to lowercase.
      27            Default: False.
      28        pad: Determines the pad size in a formatted string.
      29            Default: 2.
      30        indent: Determines the indentation size in a formatted string.
      31            Default: 2.
      32        normalize_functions: Whether or not to normalize all function names. Possible values are:
      33            "upper" or True (default): Convert names to uppercase.
      34            "lower": Convert names to lowercase.
      35            False: Disables function name normalization.
      36        unsupported_level: Determines the generator's behavior when it encounters unsupported expressions.
      37            Default ErrorLevel.WARN.
      38        max_unsupported: Maximum number of unsupported messages to include in a raised UnsupportedError.
      39            This is only relevant if unsupported_level is ErrorLevel.RAISE.
      40            Default: 3
      41        leading_comma: Determines whether or not the comma is leading or trailing in select expressions.
      42            This is only relevant when generating in pretty mode.
      43            Default: False
      44        max_text_width: The max number of characters in a segment before creating new lines in pretty mode.
      45            The default is on the smaller end because the length only represents a segment and not the true
      46            line length.
      47            Default: 80
      48        comments: Whether or not to preserve comments in the output SQL code.
      49            Default: True
      50    """
      51
      52    TRANSFORMS = {
      53        exp.DateAdd: lambda self, e: self.func(
      54            "DATE_ADD", e.this, e.expression, exp.Literal.string(e.text("unit"))
      55        ),
      56        exp.TsOrDsAdd: lambda self, e: self.func(
      57            "TS_OR_DS_ADD", e.this, e.expression, exp.Literal.string(e.text("unit"))
      58        ),
      59        exp.CaseSpecificColumnConstraint: lambda self, e: f"{'NOT ' if e.args.get('not_') else ''}CASESPECIFIC",
      60        exp.CharacterSetColumnConstraint: lambda self, e: f"CHARACTER SET {self.sql(e, 'this')}",
      61        exp.CharacterSetProperty: lambda self, e: f"{'DEFAULT ' if e.args.get('default') else ''}CHARACTER SET={self.sql(e, 'this')}",
      62        exp.CheckColumnConstraint: lambda self, e: f"CHECK ({self.sql(e, 'this')})",
      63        exp.CollateColumnConstraint: lambda self, e: f"COLLATE {self.sql(e, 'this')}",
      64        exp.CopyGrantsProperty: lambda self, e: "COPY GRANTS",
      65        exp.CommentColumnConstraint: lambda self, e: f"COMMENT {self.sql(e, 'this')}",
      66        exp.DateFormatColumnConstraint: lambda self, e: f"FORMAT {self.sql(e, 'this')}",
      67        exp.DefaultColumnConstraint: lambda self, e: f"DEFAULT {self.sql(e, 'this')}",
      68        exp.EncodeColumnConstraint: lambda self, e: f"ENCODE {self.sql(e, 'this')}",
      69        exp.ExecuteAsProperty: lambda self, e: self.naked_property(e),
      70        exp.ExternalProperty: lambda self, e: "EXTERNAL",
      71        exp.InlineLengthColumnConstraint: lambda self, e: f"INLINE LENGTH {self.sql(e, 'this')}",
      72        exp.LanguageProperty: lambda self, e: self.naked_property(e),
      73        exp.LocationProperty: lambda self, e: self.naked_property(e),
      74        exp.LogProperty: lambda self, e: f"{'NO ' if e.args.get('no') else ''}LOG",
      75        exp.MaterializedProperty: lambda self, e: "MATERIALIZED",
      76        exp.NoPrimaryIndexProperty: lambda self, e: "NO PRIMARY INDEX",
      77        exp.OnCommitProperty: lambda self, e: f"ON COMMIT {'DELETE' if e.args.get('delete') else 'PRESERVE'} ROWS",
      78        exp.OnUpdateColumnConstraint: lambda self, e: f"ON UPDATE {self.sql(e, 'this')}",
      79        exp.PathColumnConstraint: lambda self, e: f"PATH {self.sql(e, 'this')}",
      80        exp.ReturnsProperty: lambda self, e: self.naked_property(e),
      81        exp.SetProperty: lambda self, e: f"{'MULTI' if e.args.get('multi') else ''}SET",
      82        exp.SettingsProperty: lambda self, e: f"SETTINGS{self.seg('')}{(self.expressions(e))}",
      83        exp.SqlSecurityProperty: lambda self, e: f"SQL SECURITY {'DEFINER' if e.args.get('definer') else 'INVOKER'}",
      84        exp.StabilityProperty: lambda self, e: e.name,
      85        exp.TemporaryProperty: lambda self, e: f"TEMPORARY",
      86        exp.ToTableProperty: lambda self, e: f"TO {self.sql(e.this)}",
      87        exp.TransientProperty: lambda self, e: "TRANSIENT",
      88        exp.TitleColumnConstraint: lambda self, e: f"TITLE {self.sql(e, 'this')}",
      89        exp.UppercaseColumnConstraint: lambda self, e: f"UPPERCASE",
      90        exp.VarMap: lambda self, e: self.func("MAP", e.args["keys"], e.args["values"]),
      91        exp.VolatileProperty: lambda self, e: "VOLATILE",
      92        exp.WithJournalTableProperty: lambda self, e: f"WITH JOURNAL TABLE={self.sql(e, 'this')}",
      93    }
      94
      95    # Whether or not null ordering is supported in order by
      96    NULL_ORDERING_SUPPORTED = True
      97
      98    # Whether or not locking reads (i.e. SELECT ... FOR UPDATE/SHARE) are supported
      99    LOCKING_READS_SUPPORTED = False
     100
     101    # Always do union distinct or union all
     102    EXPLICIT_UNION = False
     103
     104    # Wrap derived values in parens, usually standard but spark doesn't support it
     105    WRAP_DERIVED_VALUES = True
     106
     107    # Whether or not create function uses an AS before the RETURN
     108    CREATE_FUNCTION_RETURN_AS = True
     109
     110    # Whether or not MERGE ... WHEN MATCHED BY SOURCE is allowed
     111    MATCHED_BY_SOURCE = True
     112
     113    # Whether or not the INTERVAL expression works only with values like '1 day'
     114    SINGLE_STRING_INTERVAL = False
     115
     116    # Whether or not the plural form of date parts like day (i.e. "days") is supported in INTERVALs
     117    INTERVAL_ALLOWS_PLURAL_FORM = True
     118
     119    # Whether or not the TABLESAMPLE clause supports a method name, like BERNOULLI
     120    TABLESAMPLE_WITH_METHOD = True
     121
     122    # Whether or not to treat the number in TABLESAMPLE (50) as a percentage
     123    TABLESAMPLE_SIZE_IS_PERCENT = False
     124
     125    # Whether or not limit and fetch are supported (possible values: "ALL", "LIMIT", "FETCH")
     126    LIMIT_FETCH = "ALL"
     127
     128    # Whether or not a table is allowed to be renamed with a db
     129    RENAME_TABLE_WITH_DB = True
     130
     131    # The separator for grouping sets and rollups
     132    GROUPINGS_SEP = ","
     133
     134    # The string used for creating an index on a table
     135    INDEX_ON = "ON"
     136
     137    # Whether or not join hints should be generated
     138    JOIN_HINTS = True
     139
     140    # Whether or not table hints should be generated
     141    TABLE_HINTS = True
     142
     143    # Whether or not comparing against booleans (e.g. x IS TRUE) is supported
     144    IS_BOOL_ALLOWED = True
     145
     146    # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax
     147    SELECT_KINDS: t.Tuple[str, ...] = ("STRUCT", "VALUE")
     148
     149    TYPE_MAPPING = {
     150        exp.DataType.Type.NCHAR: "CHAR",
     151        exp.DataType.Type.NVARCHAR: "VARCHAR",
     152        exp.DataType.Type.MEDIUMTEXT: "TEXT",
     153        exp.DataType.Type.LONGTEXT: "TEXT",
     154        exp.DataType.Type.MEDIUMBLOB: "BLOB",
     155        exp.DataType.Type.LONGBLOB: "BLOB",
     156        exp.DataType.Type.INET: "INET",
     157    }
     158
     159    STAR_MAPPING = {
     160        "except": "EXCEPT",
     161        "replace": "REPLACE",
     162    }
     163
     164    TIME_PART_SINGULARS = {
     165        "microseconds": "microsecond",
     166        "seconds": "second",
     167        "minutes": "minute",
     168        "hours": "hour",
     169        "days": "day",
     170        "weeks": "week",
     171        "months": "month",
     172        "quarters": "quarter",
     173        "years": "year",
     174    }
     175
     176    TOKEN_MAPPING: t.Dict[TokenType, str] = {}
     177
     178    STRUCT_DELIMITER = ("<", ">")
     179
     180    PARAMETER_TOKEN = "@"
     181
     182    PROPERTIES_LOCATION = {
     183        exp.AlgorithmProperty: exp.Properties.Location.POST_CREATE,
     184        exp.AutoIncrementProperty: exp.Properties.Location.POST_SCHEMA,
     185        exp.BlockCompressionProperty: exp.Properties.Location.POST_NAME,
     186        exp.CharacterSetProperty: exp.Properties.Location.POST_SCHEMA,
     187        exp.ChecksumProperty: exp.Properties.Location.POST_NAME,
     188        exp.CollateProperty: exp.Properties.Location.POST_SCHEMA,
     189        exp.CopyGrantsProperty: exp.Properties.Location.POST_SCHEMA,
     190        exp.Cluster: exp.Properties.Location.POST_SCHEMA,
     191        exp.ClusteredByProperty: exp.Properties.Location.POST_SCHEMA,
     192        exp.DataBlocksizeProperty: exp.Properties.Location.POST_NAME,
     193        exp.DefinerProperty: exp.Properties.Location.POST_CREATE,
     194        exp.DictRange: exp.Properties.Location.POST_SCHEMA,
     195        exp.DictProperty: exp.Properties.Location.POST_SCHEMA,
     196        exp.DistKeyProperty: exp.Properties.Location.POST_SCHEMA,
     197        exp.DistStyleProperty: exp.Properties.Location.POST_SCHEMA,
     198        exp.EngineProperty: exp.Properties.Location.POST_SCHEMA,
     199        exp.ExecuteAsProperty: exp.Properties.Location.POST_SCHEMA,
     200        exp.ExternalProperty: exp.Properties.Location.POST_CREATE,
     201        exp.FallbackProperty: exp.Properties.Location.POST_NAME,
     202        exp.FileFormatProperty: exp.Properties.Location.POST_WITH,
     203        exp.FreespaceProperty: exp.Properties.Location.POST_NAME,
     204        exp.IsolatedLoadingProperty: exp.Properties.Location.POST_NAME,
     205        exp.JournalProperty: exp.Properties.Location.POST_NAME,
     206        exp.LanguageProperty: exp.Properties.Location.POST_SCHEMA,
     207        exp.LikeProperty: exp.Properties.Location.POST_SCHEMA,
     208        exp.LocationProperty: exp.Properties.Location.POST_SCHEMA,
     209        exp.LockingProperty: exp.Properties.Location.POST_ALIAS,
     210        exp.LogProperty: exp.Properties.Location.POST_NAME,
     211        exp.MaterializedProperty: exp.Properties.Location.POST_CREATE,
     212        exp.MergeBlockRatioProperty: exp.Properties.Location.POST_NAME,
     213        exp.NoPrimaryIndexProperty: exp.Properties.Location.POST_EXPRESSION,
     214        exp.OnCommitProperty: exp.Properties.Location.POST_EXPRESSION,
     215        exp.Order: exp.Properties.Location.POST_SCHEMA,
     216        exp.PartitionedByProperty: exp.Properties.Location.POST_WITH,
     217        exp.PrimaryKey: exp.Properties.Location.POST_SCHEMA,
     218        exp.Property: exp.Properties.Location.POST_WITH,
     219        exp.ReturnsProperty: exp.Properties.Location.POST_SCHEMA,
     220        exp.RowFormatProperty: exp.Properties.Location.POST_SCHEMA,
     221        exp.RowFormatDelimitedProperty: exp.Properties.Location.POST_SCHEMA,
     222        exp.RowFormatSerdeProperty: exp.Properties.Location.POST_SCHEMA,
     223        exp.SchemaCommentProperty: exp.Properties.Location.POST_SCHEMA,
     224        exp.SerdeProperties: exp.Properties.Location.POST_SCHEMA,
     225        exp.Set: exp.Properties.Location.POST_SCHEMA,
     226        exp.SettingsProperty: exp.Properties.Location.POST_SCHEMA,
     227        exp.SetProperty: exp.Properties.Location.POST_CREATE,
     228        exp.SortKeyProperty: exp.Properties.Location.POST_SCHEMA,
     229        exp.SqlSecurityProperty: exp.Properties.Location.POST_CREATE,
     230        exp.StabilityProperty: exp.Properties.Location.POST_SCHEMA,
     231        exp.TemporaryProperty: exp.Properties.Location.POST_CREATE,
     232        exp.ToTableProperty: exp.Properties.Location.POST_SCHEMA,
     233        exp.TransientProperty: exp.Properties.Location.POST_CREATE,
     234        exp.MergeTreeTTL: exp.Properties.Location.POST_SCHEMA,
     235        exp.VolatileProperty: exp.Properties.Location.POST_CREATE,
     236        exp.WithDataProperty: exp.Properties.Location.POST_EXPRESSION,
     237        exp.WithJournalTableProperty: exp.Properties.Location.POST_NAME,
     238    }
     239
     240    # Keywords that can't be used as unquoted identifier names
     241    RESERVED_KEYWORDS: t.Set[str] = set()
     242
     243    # Expressions whose comments are separated from them for better formatting
     244    WITH_SEPARATED_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = (
     245        exp.Select,
     246        exp.From,
     247        exp.Where,
     248        exp.With,
     249    )
     250
     251    # Expressions that can remain unwrapped when appearing in the context of an INTERVAL
     252    UNWRAPPED_INTERVAL_VALUES: t.Tuple[t.Type[exp.Expression], ...] = (
     253        exp.Column,
     254        exp.Literal,
     255        exp.Neg,
     256        exp.Paren,
     257    )
     258
     259    SENTINEL_LINE_BREAK = "__SQLGLOT__LB__"
     260
     261    # Autofilled
     262    INVERSE_TIME_MAPPING: t.Dict[str, str] = {}
     263    INVERSE_TIME_TRIE: t.Dict = {}
     264    INDEX_OFFSET = 0
     265    UNNEST_COLUMN_ONLY = False
     266    ALIAS_POST_TABLESAMPLE = False
     267    IDENTIFIERS_CAN_START_WITH_DIGIT = False
     268    STRICT_STRING_CONCAT = False
     269    NORMALIZE_FUNCTIONS: bool | str = "upper"
     270    NULL_ORDERING = "nulls_are_small"
     271
     272    can_identify: t.Callable[[str, str | bool], bool]
     273
     274    # Delimiters for quotes, identifiers and the corresponding escape characters
     275    QUOTE_START = "'"
     276    QUOTE_END = "'"
     277    IDENTIFIER_START = '"'
     278    IDENTIFIER_END = '"'
     279    STRING_ESCAPE = "'"
     280    IDENTIFIER_ESCAPE = '"'
     281
     282    # Delimiters for bit, hex, byte and raw literals
     283    BIT_START: t.Optional[str] = None
     284    BIT_END: t.Optional[str] = None
     285    HEX_START: t.Optional[str] = None
     286    HEX_END: t.Optional[str] = None
     287    BYTE_START: t.Optional[str] = None
     288    BYTE_END: t.Optional[str] = None
     289    RAW_START: t.Optional[str] = None
     290    RAW_END: t.Optional[str] = None
     291
     292    __slots__ = (
     293        "pretty",
     294        "identify",
     295        "normalize",
     296        "pad",
     297        "_indent",
     298        "normalize_functions",
     299        "unsupported_level",
     300        "max_unsupported",
     301        "leading_comma",
     302        "max_text_width",
     303        "comments",
     304        "unsupported_messages",
     305        "_escaped_quote_end",
     306        "_escaped_identifier_end",
     307        "_cache",
     308    )
     309
     310    def __init__(
     311        self,
     312        pretty: t.Optional[bool] = None,
     313        identify: str | bool = False,
     314        normalize: bool = False,
     315        pad: int = 2,
     316        indent: int = 2,
     317        normalize_functions: t.Optional[str | bool] = None,
     318        unsupported_level: ErrorLevel = ErrorLevel.WARN,
     319        max_unsupported: int = 3,
     320        leading_comma: bool = False,
     321        max_text_width: int = 80,
     322        comments: bool = True,
     323    ):
     324        import sqlglot
     325
     326        self.pretty = pretty if pretty is not None else sqlglot.pretty
     327        self.identify = identify
     328        self.normalize = normalize
     329        self.pad = pad
     330        self._indent = indent
     331        self.unsupported_level = unsupported_level
     332        self.max_unsupported = max_unsupported
     333        self.leading_comma = leading_comma
     334        self.max_text_width = max_text_width
     335        self.comments = comments
     336
     337        # This is both a Dialect property and a Generator argument, so we prioritize the latter
     338        self.normalize_functions = (
     339            self.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions
     340        )
     341
     342        self.unsupported_messages: t.List[str] = []
     343        self._escaped_quote_end: str = self.STRING_ESCAPE + self.QUOTE_END
     344        self._escaped_identifier_end: str = self.IDENTIFIER_ESCAPE + self.IDENTIFIER_END
     345        self._cache: t.Optional[t.Dict[int, str]] = None
     346
     347    def generate(
     348        self,
     349        expression: t.Optional[exp.Expression],
     350        cache: t.Optional[t.Dict[int, str]] = None,
     351    ) -> str:
     352        """
     353        Generates the SQL string corresponding to the given syntax tree.
     354
     355        Args:
     356            expression: The syntax tree.
     357            cache: An optional sql string cache. This leverages the hash of an Expression
     358                which can be slow to compute, so only use it if you set _hash on each node.
     359
     360        Returns:
     361            The SQL string corresponding to `expression`.
     362        """
     363        if cache is not None:
     364            self._cache = cache
     365
     366        self.unsupported_messages = []
     367        sql = self.sql(expression).strip()
     368        self._cache = None
     369
     370        if self.unsupported_level == ErrorLevel.IGNORE:
     371            return sql
     372
     373        if self.unsupported_level == ErrorLevel.WARN:
     374            for msg in self.unsupported_messages:
     375                logger.warning(msg)
     376        elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages:
     377            raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported))
     378
     379        if self.pretty:
     380            sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n")
     381        return sql
     382
     383    def unsupported(self, message: str) -> None:
     384        if self.unsupported_level == ErrorLevel.IMMEDIATE:
     385            raise UnsupportedError(message)
     386        self.unsupported_messages.append(message)
     387
     388    def sep(self, sep: str = " ") -> str:
     389        return f"{sep.strip()}\n" if self.pretty else sep
     390
     391    def seg(self, sql: str, sep: str = " ") -> str:
     392        return f"{self.sep(sep)}{sql}"
     393
     394    def pad_comment(self, comment: str) -> str:
     395        comment = " " + comment if comment[0].strip() else comment
     396        comment = comment + " " if comment[-1].strip() else comment
     397        return comment
     398
     399    def maybe_comment(
     400        self,
     401        sql: str,
     402        expression: t.Optional[exp.Expression] = None,
     403        comments: t.Optional[t.List[str]] = None,
     404    ) -> str:
     405        comments = (
     406            ((expression and expression.comments) if comments is None else comments)  # type: ignore
     407            if self.comments
     408            else None
     409        )
     410
     411        if not comments or isinstance(expression, exp.Binary):
     412            return sql
     413
     414        sep = "\n" if self.pretty else " "
     415        comments_sql = sep.join(
     416            f"/*{self.pad_comment(comment)}*/" for comment in comments if comment
     417        )
     418
     419        if not comments_sql:
     420            return sql
     421
     422        if isinstance(expression, self.WITH_SEPARATED_COMMENTS):
     423            return (
     424                f"{self.sep()}{comments_sql}{sql}"
     425                if sql[0].isspace()
     426                else f"{comments_sql}{self.sep()}{sql}"
     427            )
     428
     429        return f"{sql} {comments_sql}"
     430
     431    def wrap(self, expression: exp.Expression | str) -> str:
     432        this_sql = self.indent(
     433            self.sql(expression)
     434            if isinstance(expression, (exp.Select, exp.Union))
     435            else self.sql(expression, "this"),
     436            level=1,
     437            pad=0,
     438        )
     439        return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"
     440
     441    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
     442        original = self.identify
     443        self.identify = False
     444        result = func(*args, **kwargs)
     445        self.identify = original
     446        return result
     447
     448    def normalize_func(self, name: str) -> str:
     449        if self.normalize_functions == "upper" or self.normalize_functions is True:
     450            return name.upper()
     451        if self.normalize_functions == "lower":
     452            return name.lower()
     453        return name
     454
     455    def indent(
     456        self,
     457        sql: str,
     458        level: int = 0,
     459        pad: t.Optional[int] = None,
     460        skip_first: bool = False,
     461        skip_last: bool = False,
     462    ) -> str:
     463        if not self.pretty:
     464            return sql
     465
     466        pad = self.pad if pad is None else pad
     467        lines = sql.split("\n")
     468
     469        return "\n".join(
     470            line
     471            if (skip_first and i == 0) or (skip_last and i == len(lines) - 1)
     472            else f"{' ' * (level * self._indent + pad)}{line}"
     473            for i, line in enumerate(lines)
     474        )
     475
     476    def sql(
     477        self,
     478        expression: t.Optional[str | exp.Expression],
     479        key: t.Optional[str] = None,
     480        comment: bool = True,
     481    ) -> str:
     482        if not expression:
     483            return ""
     484
     485        if isinstance(expression, str):
     486            return expression
     487
     488        if key:
     489            return self.sql(expression.args.get(key))
     490
     491        if self._cache is not None:
     492            expression_id = hash(expression)
     493
     494            if expression_id in self._cache:
     495                return self._cache[expression_id]
     496
     497        transform = self.TRANSFORMS.get(expression.__class__)
     498
     499        if callable(transform):
     500            sql = transform(self, expression)
     501        elif transform:
     502            sql = transform
     503        elif isinstance(expression, exp.Expression):
     504            exp_handler_name = f"{expression.key}_sql"
     505
     506            if hasattr(self, exp_handler_name):
     507                sql = getattr(self, exp_handler_name)(expression)
     508            elif isinstance(expression, exp.Func):
     509                sql = self.function_fallback_sql(expression)
     510            elif isinstance(expression, exp.Property):
     511                sql = self.property_sql(expression)
     512            else:
     513                raise ValueError(f"Unsupported expression type {expression.__class__.__name__}")
     514        else:
     515            raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}")
     516
     517        sql = self.maybe_comment(sql, expression) if self.comments and comment else sql
     518
     519        if self._cache is not None:
     520            self._cache[expression_id] = sql
     521        return sql
     522
     523    def uncache_sql(self, expression: exp.Uncache) -> str:
     524        table = self.sql(expression, "this")
     525        exists_sql = " IF EXISTS" if expression.args.get("exists") else ""
     526        return f"UNCACHE TABLE{exists_sql} {table}"
     527
     528    def cache_sql(self, expression: exp.Cache) -> str:
     529        lazy = " LAZY" if expression.args.get("lazy") else ""
     530        table = self.sql(expression, "this")
     531        options = expression.args.get("options")
     532        options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else ""
     533        sql = self.sql(expression, "expression")
     534        sql = f" AS{self.sep()}{sql}" if sql else ""
     535        sql = f"CACHE{lazy} TABLE {table}{options}{sql}"
     536        return self.prepend_ctes(expression, sql)
     537
     538    def characterset_sql(self, expression: exp.CharacterSet) -> str:
     539        if isinstance(expression.parent, exp.Cast):
     540            return f"CHAR CHARACTER SET {self.sql(expression, 'this')}"
     541        default = "DEFAULT " if expression.args.get("default") else ""
     542        return f"{default}CHARACTER SET={self.sql(expression, 'this')}"
     543
     544    def column_sql(self, expression: exp.Column) -> str:
     545        return ".".join(
     546            self.sql(part)
     547            for part in (
     548                expression.args.get("catalog"),
     549                expression.args.get("db"),
     550                expression.args.get("table"),
     551                expression.args.get("this"),
     552            )
     553            if part
     554        )
     555
     556    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
     557        this = self.sql(expression, "this")
     558        this = f" {this}" if this else ""
     559        position = self.sql(expression, "position")
     560        return f"{position}{this}"
     561
     562    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
     563        column = self.sql(expression, "this")
     564        kind = self.sql(expression, "kind")
     565        constraints = self.expressions(expression, key="constraints", sep=" ", flat=True)
     566        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
     567        kind = f"{sep}{kind}" if kind else ""
     568        constraints = f" {constraints}" if constraints else ""
     569        position = self.sql(expression, "position")
     570        position = f" {position}" if position else ""
     571
     572        return f"{exists}{column}{kind}{constraints}{position}"
     573
     574    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
     575        this = self.sql(expression, "this")
     576        kind_sql = self.sql(expression, "kind").strip()
     577        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql
     578
     579    def autoincrementcolumnconstraint_sql(self, _) -> str:
     580        return self.token_sql(TokenType.AUTO_INCREMENT)
     581
     582    def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str:
     583        if isinstance(expression.this, list):
     584            this = self.wrap(self.expressions(expression, key="this", flat=True))
     585        else:
     586            this = self.sql(expression, "this")
     587
     588        return f"COMPRESS {this}"
     589
     590    def generatedasidentitycolumnconstraint_sql(
     591        self, expression: exp.GeneratedAsIdentityColumnConstraint
     592    ) -> str:
     593        this = ""
     594        if expression.this is not None:
     595            on_null = "ON NULL " if expression.args.get("on_null") else ""
     596            this = " ALWAYS " if expression.this else f" BY DEFAULT {on_null}"
     597
     598        start = expression.args.get("start")
     599        start = f"START WITH {start}" if start else ""
     600        increment = expression.args.get("increment")
     601        increment = f" INCREMENT BY {increment}" if increment else ""
     602        minvalue = expression.args.get("minvalue")
     603        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
     604        maxvalue = expression.args.get("maxvalue")
     605        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
     606        cycle = expression.args.get("cycle")
     607        cycle_sql = ""
     608
     609        if cycle is not None:
     610            cycle_sql = f"{' NO' if not cycle else ''} CYCLE"
     611            cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql
     612
     613        sequence_opts = ""
     614        if start or increment or cycle_sql:
     615            sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}"
     616            sequence_opts = f" ({sequence_opts.strip()})"
     617
     618        expr = self.sql(expression, "expression")
     619        expr = f"({expr})" if expr else "IDENTITY"
     620
     621        return f"GENERATED{this}AS {expr}{sequence_opts}"
     622
     623    def notnullcolumnconstraint_sql(self, expression: exp.NotNullColumnConstraint) -> str:
     624        return f"{'' if expression.args.get('allow_null') else 'NOT '}NULL"
     625
     626    def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str:
     627        desc = expression.args.get("desc")
     628        if desc is not None:
     629            return f"PRIMARY KEY{' DESC' if desc else ' ASC'}"
     630        return f"PRIMARY KEY"
     631
     632    def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str:
     633        this = self.sql(expression, "this")
     634        this = f" {this}" if this else ""
     635        return f"UNIQUE{this}"
     636
     637    def createable_sql(
     638        self, expression: exp.Create, locations: dict[exp.Properties.Location, list[exp.Property]]
     639    ) -> str:
     640        return self.sql(expression, "this")
     641
     642    def create_sql(self, expression: exp.Create) -> str:
     643        kind = self.sql(expression, "kind").upper()
     644        properties = expression.args.get("properties")
     645        properties_locs = self.locate_properties(properties) if properties else {}
     646
     647        this = self.createable_sql(expression, properties_locs)
     648
     649        properties_sql = ""
     650        if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get(
     651            exp.Properties.Location.POST_WITH
     652        ):
     653            properties_sql = self.sql(
     654                exp.Properties(
     655                    expressions=[
     656                        *properties_locs[exp.Properties.Location.POST_SCHEMA],
     657                        *properties_locs[exp.Properties.Location.POST_WITH],
     658                    ]
     659                )
     660            )
     661
     662        begin = " BEGIN" if expression.args.get("begin") else ""
     663        expression_sql = self.sql(expression, "expression")
     664        if expression_sql:
     665            expression_sql = f"{begin}{self.sep()}{expression_sql}"
     666
     667            if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return):
     668                if properties_locs.get(exp.Properties.Location.POST_ALIAS):
     669                    postalias_props_sql = self.properties(
     670                        exp.Properties(
     671                            expressions=properties_locs[exp.Properties.Location.POST_ALIAS]
     672                        ),
     673                        wrapped=False,
     674                    )
     675                    expression_sql = f" AS {postalias_props_sql}{expression_sql}"
     676                else:
     677                    expression_sql = f" AS{expression_sql}"
     678
     679        postindex_props_sql = ""
     680        if properties_locs.get(exp.Properties.Location.POST_INDEX):
     681            postindex_props_sql = self.properties(
     682                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]),
     683                wrapped=False,
     684                prefix=" ",
     685            )
     686
     687        indexes = self.expressions(expression, key="indexes", indent=False, sep=" ")
     688        indexes = f" {indexes}" if indexes else ""
     689        index_sql = indexes + postindex_props_sql
     690
     691        replace = " OR REPLACE" if expression.args.get("replace") else ""
     692        unique = " UNIQUE" if expression.args.get("unique") else ""
     693
     694        postcreate_props_sql = ""
     695        if properties_locs.get(exp.Properties.Location.POST_CREATE):
     696            postcreate_props_sql = self.properties(
     697                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]),
     698                sep=" ",
     699                prefix=" ",
     700                wrapped=False,
     701            )
     702
     703        modifiers = "".join((replace, unique, postcreate_props_sql))
     704
     705        postexpression_props_sql = ""
     706        if properties_locs.get(exp.Properties.Location.POST_EXPRESSION):
     707            postexpression_props_sql = self.properties(
     708                exp.Properties(
     709                    expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION]
     710                ),
     711                sep=" ",
     712                prefix=" ",
     713                wrapped=False,
     714            )
     715
     716        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
     717        no_schema_binding = (
     718            " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else ""
     719        )
     720
     721        clone = self.sql(expression, "clone")
     722        clone = f" {clone}" if clone else ""
     723
     724        expression_sql = f"CREATE{modifiers} {kind}{exists_sql} {this}{properties_sql}{expression_sql}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}"
     725        return self.prepend_ctes(expression, expression_sql)
     726
     727    def clone_sql(self, expression: exp.Clone) -> str:
     728        this = self.sql(expression, "this")
     729        when = self.sql(expression, "when")
     730
     731        if when:
     732            kind = self.sql(expression, "kind")
     733            expr = self.sql(expression, "expression")
     734            return f"CLONE {this} {when} ({kind} => {expr})"
     735
     736        return f"CLONE {this}"
     737
     738    def describe_sql(self, expression: exp.Describe) -> str:
     739        return f"DESCRIBE {self.sql(expression, 'this')}"
     740
     741    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
     742        with_ = self.sql(expression, "with")
     743        if with_:
     744            sql = f"{with_}{self.sep()}{sql}"
     745        return sql
     746
     747    def with_sql(self, expression: exp.With) -> str:
     748        sql = self.expressions(expression, flat=True)
     749        recursive = "RECURSIVE " if expression.args.get("recursive") else ""
     750
     751        return f"WITH {recursive}{sql}"
     752
     753    def cte_sql(self, expression: exp.CTE) -> str:
     754        alias = self.sql(expression, "alias")
     755        return f"{alias} AS {self.wrap(expression)}"
     756
     757    def tablealias_sql(self, expression: exp.TableAlias) -> str:
     758        alias = self.sql(expression, "this")
     759        columns = self.expressions(expression, key="columns", flat=True)
     760        columns = f"({columns})" if columns else ""
     761        return f"{alias}{columns}"
     762
     763    def bitstring_sql(self, expression: exp.BitString) -> str:
     764        this = self.sql(expression, "this")
     765        if self.BIT_START:
     766            return f"{self.BIT_START}{this}{self.BIT_END}"
     767        return f"{int(this, 2)}"
     768
     769    def hexstring_sql(self, expression: exp.HexString) -> str:
     770        this = self.sql(expression, "this")
     771        if self.HEX_START:
     772            return f"{self.HEX_START}{this}{self.HEX_END}"
     773        return f"{int(this, 16)}"
     774
     775    def bytestring_sql(self, expression: exp.ByteString) -> str:
     776        this = self.sql(expression, "this")
     777        if self.BYTE_START:
     778            return f"{self.BYTE_START}{this}{self.BYTE_END}"
     779        return this
     780
     781    def rawstring_sql(self, expression: exp.RawString) -> str:
     782        string = expression.this
     783        if self.RAW_START:
     784            return f"{self.RAW_START}{self.escape_str(expression.this)}{self.RAW_END}"
     785        string = self.escape_str(string.replace("\\", "\\\\"))
     786        return f"{self.QUOTE_START}{string}{self.QUOTE_END}"
     787
     788    def datatypesize_sql(self, expression: exp.DataTypeSize) -> str:
     789        this = self.sql(expression, "this")
     790        specifier = self.sql(expression, "expression")
     791        specifier = f" {specifier}" if specifier else ""
     792        return f"{this}{specifier}"
     793
     794    def datatype_sql(self, expression: exp.DataType) -> str:
     795        type_value = expression.this
     796        type_sql = self.TYPE_MAPPING.get(type_value, type_value.value)
     797        nested = ""
     798        interior = self.expressions(expression, flat=True)
     799        values = ""
     800        if interior:
     801            if expression.args.get("nested"):
     802                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
     803                if expression.args.get("values") is not None:
     804                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
     805                    values = self.expressions(expression, key="values", flat=True)
     806                    values = f"{delimiters[0]}{values}{delimiters[1]}"
     807            else:
     808                nested = f"({interior})"
     809
     810        return f"{type_sql}{nested}{values}"
     811
     812    def directory_sql(self, expression: exp.Directory) -> str:
     813        local = "LOCAL " if expression.args.get("local") else ""
     814        row_format = self.sql(expression, "row_format")
     815        row_format = f" {row_format}" if row_format else ""
     816        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"
     817
     818    def delete_sql(self, expression: exp.Delete) -> str:
     819        this = self.sql(expression, "this")
     820        this = f" FROM {this}" if this else ""
     821        using_sql = (
     822            f" USING {self.expressions(expression, key='using', sep=', USING ')}"
     823            if expression.args.get("using")
     824            else ""
     825        )
     826        where_sql = self.sql(expression, "where")
     827        returning = self.sql(expression, "returning")
     828        limit = self.sql(expression, "limit")
     829        sql = f"DELETE{this}{using_sql}{where_sql}{returning}{limit}"
     830        return self.prepend_ctes(expression, sql)
     831
     832    def drop_sql(self, expression: exp.Drop) -> str:
     833        this = self.sql(expression, "this")
     834        kind = expression.args["kind"]
     835        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
     836        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
     837        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
     838        cascade = " CASCADE" if expression.args.get("cascade") else ""
     839        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
     840        purge = " PURGE" if expression.args.get("purge") else ""
     841        return (
     842            f"DROP{temporary}{materialized} {kind}{exists_sql}{this}{cascade}{constraints}{purge}"
     843        )
     844
     845    def except_sql(self, expression: exp.Except) -> str:
     846        return self.prepend_ctes(
     847            expression,
     848            self.set_operation(expression, self.except_op(expression)),
     849        )
     850
     851    def except_op(self, expression: exp.Except) -> str:
     852        return f"EXCEPT{'' if expression.args.get('distinct') else ' ALL'}"
     853
     854    def fetch_sql(self, expression: exp.Fetch) -> str:
     855        direction = expression.args.get("direction")
     856        direction = f" {direction.upper()}" if direction else ""
     857        count = expression.args.get("count")
     858        count = f" {count}" if count else ""
     859        if expression.args.get("percent"):
     860            count = f"{count} PERCENT"
     861        with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY"
     862        return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}"
     863
     864    def filter_sql(self, expression: exp.Filter) -> str:
     865        this = self.sql(expression, "this")
     866        where = self.sql(expression, "expression")[1:]  # where has a leading space
     867        return f"{this} FILTER({where})"
     868
     869    def hint_sql(self, expression: exp.Hint) -> str:
     870        if self.sql(expression, "this"):
     871            self.unsupported("Hints are not supported")
     872        return ""
     873
     874    def index_sql(self, expression: exp.Index) -> str:
     875        unique = "UNIQUE " if expression.args.get("unique") else ""
     876        primary = "PRIMARY " if expression.args.get("primary") else ""
     877        amp = "AMP " if expression.args.get("amp") else ""
     878        name = f"{expression.name} " if expression.name else ""
     879        table = self.sql(expression, "table")
     880        table = f"{self.INDEX_ON} {table} " if table else ""
     881        using = self.sql(expression, "using")
     882        using = f"USING {using} " if using else ""
     883        index = "INDEX " if not table else ""
     884        columns = self.expressions(expression, key="columns", flat=True)
     885        columns = f"({columns})" if columns else ""
     886        partition_by = self.expressions(expression, key="partition_by", flat=True)
     887        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
     888        return f"{unique}{primary}{amp}{index}{name}{table}{using}{columns}{partition_by}"
     889
     890    def identifier_sql(self, expression: exp.Identifier) -> str:
     891        text = expression.name
     892        lower = text.lower()
     893        text = lower if self.normalize and not expression.quoted else text
     894        text = text.replace(self.IDENTIFIER_END, self._escaped_identifier_end)
     895        if (
     896            expression.quoted
     897            or self.can_identify(text, self.identify)
     898            or lower in self.RESERVED_KEYWORDS
     899            or (not self.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
     900        ):
     901            text = f"{self.IDENTIFIER_START}{text}{self.IDENTIFIER_END}"
     902        return text
     903
     904    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
     905        input_format = self.sql(expression, "input_format")
     906        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
     907        output_format = self.sql(expression, "output_format")
     908        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
     909        return self.sep().join((input_format, output_format))
     910
     911    def national_sql(self, expression: exp.National, prefix: str = "N") -> str:
     912        string = self.sql(exp.Literal.string(expression.name))
     913        return f"{prefix}{string}"
     914
     915    def partition_sql(self, expression: exp.Partition) -> str:
     916        return f"PARTITION({self.expressions(expression, flat=True)})"
     917
     918    def properties_sql(self, expression: exp.Properties) -> str:
     919        root_properties = []
     920        with_properties = []
     921
     922        for p in expression.expressions:
     923            p_loc = self.PROPERTIES_LOCATION[p.__class__]
     924            if p_loc == exp.Properties.Location.POST_WITH:
     925                with_properties.append(p)
     926            elif p_loc == exp.Properties.Location.POST_SCHEMA:
     927                root_properties.append(p)
     928
     929        return self.root_properties(
     930            exp.Properties(expressions=root_properties)
     931        ) + self.with_properties(exp.Properties(expressions=with_properties))
     932
     933    def root_properties(self, properties: exp.Properties) -> str:
     934        if properties.expressions:
     935            return self.sep() + self.expressions(properties, indent=False, sep=" ")
     936        return ""
     937
     938    def properties(
     939        self,
     940        properties: exp.Properties,
     941        prefix: str = "",
     942        sep: str = ", ",
     943        suffix: str = "",
     944        wrapped: bool = True,
     945    ) -> str:
     946        if properties.expressions:
     947            expressions = self.expressions(properties, sep=sep, indent=False)
     948            expressions = self.wrap(expressions) if wrapped else expressions
     949            return f"{prefix}{' ' if prefix and prefix != ' ' else ''}{expressions}{suffix}"
     950        return ""
     951
     952    def with_properties(self, properties: exp.Properties) -> str:
     953        return self.properties(properties, prefix=self.seg("WITH"))
     954
     955    def locate_properties(
     956        self, properties: exp.Properties
     957    ) -> t.Dict[exp.Properties.Location, list[exp.Property]]:
     958        properties_locs: t.Dict[exp.Properties.Location, list[exp.Property]] = {
     959            key: [] for key in exp.Properties.Location
     960        }
     961
     962        for p in properties.expressions:
     963            p_loc = self.PROPERTIES_LOCATION[p.__class__]
     964            if p_loc == exp.Properties.Location.POST_NAME:
     965                properties_locs[exp.Properties.Location.POST_NAME].append(p)
     966            elif p_loc == exp.Properties.Location.POST_INDEX:
     967                properties_locs[exp.Properties.Location.POST_INDEX].append(p)
     968            elif p_loc == exp.Properties.Location.POST_SCHEMA:
     969                properties_locs[exp.Properties.Location.POST_SCHEMA].append(p)
     970            elif p_loc == exp.Properties.Location.POST_WITH:
     971                properties_locs[exp.Properties.Location.POST_WITH].append(p)
     972            elif p_loc == exp.Properties.Location.POST_CREATE:
     973                properties_locs[exp.Properties.Location.POST_CREATE].append(p)
     974            elif p_loc == exp.Properties.Location.POST_ALIAS:
     975                properties_locs[exp.Properties.Location.POST_ALIAS].append(p)
     976            elif p_loc == exp.Properties.Location.POST_EXPRESSION:
     977                properties_locs[exp.Properties.Location.POST_EXPRESSION].append(p)
     978            elif p_loc == exp.Properties.Location.UNSUPPORTED:
     979                self.unsupported(f"Unsupported property {p.key}")
     980
     981        return properties_locs
     982
     983    def property_sql(self, expression: exp.Property) -> str:
     984        property_cls = expression.__class__
     985        if property_cls == exp.Property:
     986            return f"{expression.name}={self.sql(expression, 'value')}"
     987
     988        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
     989        if not property_name:
     990            self.unsupported(f"Unsupported property {expression.key}")
     991
     992        return f"{property_name}={self.sql(expression, 'this')}"
     993
     994    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
     995        options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
     996        options = f" {options}" if options else ""
     997        return f"LIKE {self.sql(expression, 'this')}{options}"
     998
     999    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1000        no = "NO " if expression.args.get("no") else ""
    1001        protection = " PROTECTION" if expression.args.get("protection") else ""
    1002        return f"{no}FALLBACK{protection}"
    1003
    1004    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1005        no = "NO " if expression.args.get("no") else ""
    1006        local = expression.args.get("local")
    1007        local = f"{local} " if local else ""
    1008        dual = "DUAL " if expression.args.get("dual") else ""
    1009        before = "BEFORE " if expression.args.get("before") else ""
    1010        after = "AFTER " if expression.args.get("after") else ""
    1011        return f"{no}{local}{dual}{before}{after}JOURNAL"
    1012
    1013    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1014        freespace = self.sql(expression, "this")
    1015        percent = " PERCENT" if expression.args.get("percent") else ""
    1016        return f"FREESPACE={freespace}{percent}"
    1017
    1018    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1019        if expression.args.get("default"):
    1020            property = "DEFAULT"
    1021        elif expression.args.get("on"):
    1022            property = "ON"
    1023        else:
    1024            property = "OFF"
    1025        return f"CHECKSUM={property}"
    1026
    1027    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1028        if expression.args.get("no"):
    1029            return "NO MERGEBLOCKRATIO"
    1030        if expression.args.get("default"):
    1031            return "DEFAULT MERGEBLOCKRATIO"
    1032
    1033        percent = " PERCENT" if expression.args.get("percent") else ""
    1034        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"
    1035
    1036    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1037        default = expression.args.get("default")
    1038        minimum = expression.args.get("minimum")
    1039        maximum = expression.args.get("maximum")
    1040        if default or minimum or maximum:
    1041            if default:
    1042                prop = "DEFAULT"
    1043            elif minimum:
    1044                prop = "MINIMUM"
    1045            else:
    1046                prop = "MAXIMUM"
    1047            return f"{prop} DATABLOCKSIZE"
    1048        units = expression.args.get("units")
    1049        units = f" {units}" if units else ""
    1050        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"
    1051
    1052    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1053        autotemp = expression.args.get("autotemp")
    1054        always = expression.args.get("always")
    1055        default = expression.args.get("default")
    1056        manual = expression.args.get("manual")
    1057        never = expression.args.get("never")
    1058
    1059        if autotemp is not None:
    1060            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1061        elif always:
    1062            prop = "ALWAYS"
    1063        elif default:
    1064            prop = "DEFAULT"
    1065        elif manual:
    1066            prop = "MANUAL"
    1067        elif never:
    1068            prop = "NEVER"
    1069        return f"BLOCKCOMPRESSION={prop}"
    1070
    1071    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1072        no = expression.args.get("no")
    1073        no = " NO" if no else ""
    1074        concurrent = expression.args.get("concurrent")
    1075        concurrent = " CONCURRENT" if concurrent else ""
    1076
    1077        for_ = ""
    1078        if expression.args.get("for_all"):
    1079            for_ = " FOR ALL"
    1080        elif expression.args.get("for_insert"):
    1081            for_ = " FOR INSERT"
    1082        elif expression.args.get("for_none"):
    1083            for_ = " FOR NONE"
    1084        return f"WITH{no}{concurrent} ISOLATED LOADING{for_}"
    1085
    1086    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1087        kind = expression.args.get("kind")
    1088        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1089        for_or_in = expression.args.get("for_or_in")
    1090        lock_type = expression.args.get("lock_type")
    1091        override = " OVERRIDE" if expression.args.get("override") else ""
    1092        return f"LOCKING {kind}{this} {for_or_in} {lock_type}{override}"
    1093
    1094    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1095        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1096        statistics = expression.args.get("statistics")
    1097        statistics_sql = ""
    1098        if statistics is not None:
    1099            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1100        return f"{data_sql}{statistics_sql}"
    1101
    1102    def insert_sql(self, expression: exp.Insert) -> str:
    1103        overwrite = expression.args.get("overwrite")
    1104
    1105        if isinstance(expression.this, exp.Directory):
    1106            this = " OVERWRITE" if overwrite else " INTO"
    1107        else:
    1108            this = " OVERWRITE TABLE" if overwrite else " INTO"
    1109
    1110        alternative = expression.args.get("alternative")
    1111        alternative = f" OR {alternative}" if alternative else ""
    1112        this = f"{this} {self.sql(expression, 'this')}"
    1113
    1114        exists = " IF EXISTS" if expression.args.get("exists") else ""
    1115        partition_sql = (
    1116            f" {self.sql(expression, 'partition')}" if expression.args.get("partition") else ""
    1117        )
    1118        where = self.sql(expression, "where")
    1119        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
    1120        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
    1121        conflict = self.sql(expression, "conflict")
    1122        returning = self.sql(expression, "returning")
    1123        sql = f"INSERT{alternative}{this}{exists}{partition_sql}{where}{expression_sql}{conflict}{returning}"
    1124        return self.prepend_ctes(expression, sql)
    1125
    1126    def intersect_sql(self, expression: exp.Intersect) -> str:
    1127        return self.prepend_ctes(
    1128            expression,
    1129            self.set_operation(expression, self.intersect_op(expression)),
    1130        )
    1131
    1132    def intersect_op(self, expression: exp.Intersect) -> str:
    1133        return f"INTERSECT{'' if expression.args.get('distinct') else ' ALL'}"
    1134
    1135    def introducer_sql(self, expression: exp.Introducer) -> str:
    1136        return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}"
    1137
    1138    def pseudotype_sql(self, expression: exp.PseudoType) -> str:
    1139        return expression.name.upper()
    1140
    1141    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1142        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1143        constraint = self.sql(expression, "constraint")
    1144        if constraint:
    1145            constraint = f"ON CONSTRAINT {constraint}"
    1146        key = self.expressions(expression, key="key", flat=True)
    1147        do = "" if expression.args.get("duplicate") else " DO "
    1148        nothing = "NOTHING" if expression.args.get("nothing") else ""
    1149        expressions = self.expressions(expression, flat=True)
    1150        if expressions:
    1151            expressions = f"UPDATE SET {expressions}"
    1152        return f"{self.seg(conflict)} {constraint}{key}{do}{nothing}{expressions}"
    1153
    1154    def returning_sql(self, expression: exp.Returning) -> str:
    1155        return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}"
    1156
    1157    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1158        fields = expression.args.get("fields")
    1159        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1160        escaped = expression.args.get("escaped")
    1161        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1162        items = expression.args.get("collection_items")
    1163        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1164        keys = expression.args.get("map_keys")
    1165        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1166        lines = expression.args.get("lines")
    1167        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1168        null = expression.args.get("null")
    1169        null = f" NULL DEFINED AS {null}" if null else ""
    1170        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"
    1171
    1172    def withtablehint_sql(self, expression: exp.WithTableHint) -> str:
    1173        return f"WITH ({self.expressions(expression, flat=True)})"
    1174
    1175    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1176        this = f"{self.sql(expression, 'this')} INDEX"
    1177        target = self.sql(expression, "target")
    1178        target = f" FOR {target}" if target else ""
    1179        return f"{this}{target} ({self.expressions(expression, flat=True)})"
    1180
    1181    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1182        table = ".".join(
    1183            part
    1184            for part in [
    1185                self.sql(expression, "catalog"),
    1186                self.sql(expression, "db"),
    1187                self.sql(expression, "this"),
    1188            ]
    1189            if part
    1190        )
    1191
    1192        alias = self.sql(expression, "alias")
    1193        alias = f"{sep}{alias}" if alias else ""
    1194        hints = self.expressions(expression, key="hints", sep=" ")
    1195        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
    1196        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    1197        pivots = f" {pivots}" if pivots else ""
    1198        joins = self.expressions(expression, key="joins", sep="")
    1199        laterals = self.expressions(expression, key="laterals", sep="")
    1200        system_time = expression.args.get("system_time")
    1201        system_time = f" {self.sql(expression, 'system_time')}" if system_time else ""
    1202
    1203        return f"{table}{system_time}{alias}{hints}{pivots}{joins}{laterals}"
    1204
    1205    def tablesample_sql(
    1206        self, expression: exp.TableSample, seed_prefix: str = "SEED", sep=" AS "
    1207    ) -> str:
    1208        if self.ALIAS_POST_TABLESAMPLE and expression.this.alias:
    1209            table = expression.this.copy()
    1210            table.set("alias", None)
    1211            this = self.sql(table)
    1212            alias = f"{sep}{self.sql(expression.this, 'alias')}"
    1213        else:
    1214            this = self.sql(expression, "this")
    1215            alias = ""
    1216        method = self.sql(expression, "method")
    1217        method = f"{method.upper()} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    1218        numerator = self.sql(expression, "bucket_numerator")
    1219        denominator = self.sql(expression, "bucket_denominator")
    1220        field = self.sql(expression, "bucket_field")
    1221        field = f" ON {field}" if field else ""
    1222        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    1223        percent = self.sql(expression, "percent")
    1224        percent = f"{percent} PERCENT" if percent else ""
    1225        rows = self.sql(expression, "rows")
    1226        rows = f"{rows} ROWS" if rows else ""
    1227        size = self.sql(expression, "size")
    1228        if size and self.TABLESAMPLE_SIZE_IS_PERCENT:
    1229            size = f"{size} PERCENT"
    1230        seed = self.sql(expression, "seed")
    1231        seed = f" {seed_prefix} ({seed})" if seed else ""
    1232        kind = expression.args.get("kind", "TABLESAMPLE")
    1233        return f"{this} {kind} {method}({bucket}{percent}{rows}{size}){seed}{alias}"
    1234
    1235    def pivot_sql(self, expression: exp.Pivot) -> str:
    1236        expressions = self.expressions(expression, flat=True)
    1237
    1238        if expression.this:
    1239            this = self.sql(expression, "this")
    1240            on = f"{self.seg('ON')} {expressions}"
    1241            using = self.expressions(expression, key="using", flat=True)
    1242            using = f"{self.seg('USING')} {using}" if using else ""
    1243            group = self.sql(expression, "group")
    1244            return f"PIVOT {this}{on}{using}{group}"
    1245
    1246        alias = self.sql(expression, "alias")
    1247        alias = f" AS {alias}" if alias else ""
    1248        unpivot = expression.args.get("unpivot")
    1249        direction = "UNPIVOT" if unpivot else "PIVOT"
    1250        field = self.sql(expression, "field")
    1251        return f"{direction}({expressions} FOR {field}){alias}"
    1252
    1253    def tuple_sql(self, expression: exp.Tuple) -> str:
    1254        return f"({self.expressions(expression, flat=True)})"
    1255
    1256    def update_sql(self, expression: exp.Update) -> str:
    1257        this = self.sql(expression, "this")
    1258        set_sql = self.expressions(expression, flat=True)
    1259        from_sql = self.sql(expression, "from")
    1260        where_sql = self.sql(expression, "where")
    1261        returning = self.sql(expression, "returning")
    1262        limit = self.sql(expression, "limit")
    1263        sql = f"UPDATE {this} SET {set_sql}{from_sql}{where_sql}{returning}{limit}"
    1264        return self.prepend_ctes(expression, sql)
    1265
    1266    def values_sql(self, expression: exp.Values) -> str:
    1267        args = self.expressions(expression)
    1268        alias = self.sql(expression, "alias")
    1269        values = f"VALUES{self.seg('')}{args}"
    1270        values = (
    1271            f"({values})"
    1272            if self.WRAP_DERIVED_VALUES and (alias or isinstance(expression.parent, exp.From))
    1273            else values
    1274        )
    1275        return f"{values} AS {alias}" if alias else values
    1276
    1277    def var_sql(self, expression: exp.Var) -> str:
    1278        return self.sql(expression, "this")
    1279
    1280    def into_sql(self, expression: exp.Into) -> str:
    1281        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    1282        unlogged = " UNLOGGED" if expression.args.get("unlogged") else ""
    1283        return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"
    1284
    1285    def from_sql(self, expression: exp.From) -> str:
    1286        return f"{self.seg('FROM')} {self.sql(expression, 'this')}"
    1287
    1288    def group_sql(self, expression: exp.Group) -> str:
    1289        group_by = self.op_expressions("GROUP BY", expression)
    1290        grouping_sets = self.expressions(expression, key="grouping_sets", indent=False)
    1291        grouping_sets = (
    1292            f"{self.seg('GROUPING SETS')} {self.wrap(grouping_sets)}" if grouping_sets else ""
    1293        )
    1294
    1295        cube = expression.args.get("cube", [])
    1296        if seq_get(cube, 0) is True:
    1297            return f"{group_by}{self.seg('WITH CUBE')}"
    1298        else:
    1299            cube_sql = self.expressions(expression, key="cube", indent=False)
    1300            cube_sql = f"{self.seg('CUBE')} {self.wrap(cube_sql)}" if cube_sql else ""
    1301
    1302        rollup = expression.args.get("rollup", [])
    1303        if seq_get(rollup, 0) is True:
    1304            return f"{group_by}{self.seg('WITH ROLLUP')}"
    1305        else:
    1306            rollup_sql = self.expressions(expression, key="rollup", indent=False)
    1307            rollup_sql = f"{self.seg('ROLLUP')} {self.wrap(rollup_sql)}" if rollup_sql else ""
    1308
    1309        groupings = csv(
    1310            grouping_sets,
    1311            cube_sql,
    1312            rollup_sql,
    1313            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    1314            sep=self.GROUPINGS_SEP,
    1315        )
    1316
    1317        if expression.args.get("expressions") and groupings:
    1318            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    1319
    1320        return f"{group_by}{groupings}"
    1321
    1322    def having_sql(self, expression: exp.Having) -> str:
    1323        this = self.indent(self.sql(expression, "this"))
    1324        return f"{self.seg('HAVING')}{self.sep()}{this}"
    1325
    1326    def join_sql(self, expression: exp.Join) -> str:
    1327        op_sql = " ".join(
    1328            op
    1329            for op in (
    1330                expression.method,
    1331                "GLOBAL" if expression.args.get("global") else None,
    1332                expression.side,
    1333                expression.kind,
    1334                expression.hint if self.JOIN_HINTS else None,
    1335            )
    1336            if op
    1337        )
    1338        on_sql = self.sql(expression, "on")
    1339        using = expression.args.get("using")
    1340
    1341        if not on_sql and using:
    1342            on_sql = csv(*(self.sql(column) for column in using))
    1343
    1344        this_sql = self.sql(expression, "this")
    1345
    1346        if on_sql:
    1347            on_sql = self.indent(on_sql, skip_first=True)
    1348            space = self.seg(" " * self.pad) if self.pretty else " "
    1349            if using:
    1350                on_sql = f"{space}USING ({on_sql})"
    1351            else:
    1352                on_sql = f"{space}ON {on_sql}"
    1353        elif not op_sql:
    1354            return f", {this_sql}"
    1355
    1356        op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    1357        return f"{self.seg(op_sql)} {this_sql}{on_sql}"
    1358
    1359    def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->") -> str:
    1360        args = self.expressions(expression, flat=True)
    1361        args = f"({args})" if len(args.split(",")) > 1 else args
    1362        return f"{args} {arrow_sep} {self.sql(expression, 'this')}"
    1363
    1364    def lateral_sql(self, expression: exp.Lateral) -> str:
    1365        this = self.sql(expression, "this")
    1366
    1367        if isinstance(expression.this, exp.Subquery):
    1368            return f"LATERAL {this}"
    1369
    1370        if expression.args.get("view"):
    1371            alias = expression.args["alias"]
    1372            columns = self.expressions(alias, key="columns", flat=True)
    1373            table = f" {alias.name}" if alias.name else ""
    1374            columns = f" AS {columns}" if columns else ""
    1375            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    1376            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    1377
    1378        alias = self.sql(expression, "alias")
    1379        alias = f" AS {alias}" if alias else ""
    1380        return f"LATERAL {this}{alias}"
    1381
    1382    def limit_sql(self, expression: exp.Limit) -> str:
    1383        this = self.sql(expression, "this")
    1384        args = ", ".join(
    1385            sql
    1386            for sql in (
    1387                self.sql(expression, "offset"),
    1388                self.sql(expression, "expression"),
    1389            )
    1390            if sql
    1391        )
    1392        return f"{this}{self.seg('LIMIT')} {args}"
    1393
    1394    def offset_sql(self, expression: exp.Offset) -> str:
    1395        this = self.sql(expression, "this")
    1396        return f"{this}{self.seg('OFFSET')} {self.sql(expression, 'expression')}"
    1397
    1398    def setitem_sql(self, expression: exp.SetItem) -> str:
    1399        kind = self.sql(expression, "kind")
    1400        kind = f"{kind} " if kind else ""
    1401        this = self.sql(expression, "this")
    1402        expressions = self.expressions(expression)
    1403        collate = self.sql(expression, "collate")
    1404        collate = f" COLLATE {collate}" if collate else ""
    1405        global_ = "GLOBAL " if expression.args.get("global") else ""
    1406        return f"{global_}{kind}{this}{expressions}{collate}"
    1407
    1408    def set_sql(self, expression: exp.Set) -> str:
    1409        expressions = (
    1410            f" {self.expressions(expression, flat=True)}" if expression.expressions else ""
    1411        )
    1412        tag = " TAG" if expression.args.get("tag") else ""
    1413        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"
    1414
    1415    def pragma_sql(self, expression: exp.Pragma) -> str:
    1416        return f"PRAGMA {self.sql(expression, 'this')}"
    1417
    1418    def lock_sql(self, expression: exp.Lock) -> str:
    1419        if not self.LOCKING_READS_SUPPORTED:
    1420            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    1421            return ""
    1422
    1423        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    1424        expressions = self.expressions(expression, flat=True)
    1425        expressions = f" OF {expressions}" if expressions else ""
    1426        wait = expression.args.get("wait")
    1427
    1428        if wait is not None:
    1429            if isinstance(wait, exp.Literal):
    1430                wait = f" WAIT {self.sql(wait)}"
    1431            else:
    1432                wait = " NOWAIT" if wait else " SKIP LOCKED"
    1433
    1434        return f"{lock_type}{expressions}{wait or ''}"
    1435
    1436    def literal_sql(self, expression: exp.Literal) -> str:
    1437        text = expression.this or ""
    1438        if expression.is_string:
    1439            text = f"{self.QUOTE_START}{self.escape_str(text)}{self.QUOTE_END}"
    1440        return text
    1441
    1442    def escape_str(self, text: str) -> str:
    1443        text = text.replace(self.QUOTE_END, self._escaped_quote_end)
    1444        if self.pretty:
    1445            text = text.replace("\n", self.SENTINEL_LINE_BREAK)
    1446        return text
    1447
    1448    def loaddata_sql(self, expression: exp.LoadData) -> str:
    1449        local = " LOCAL" if expression.args.get("local") else ""
    1450        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    1451        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    1452        this = f" INTO TABLE {self.sql(expression, 'this')}"
    1453        partition = self.sql(expression, "partition")
    1454        partition = f" {partition}" if partition else ""
    1455        input_format = self.sql(expression, "input_format")
    1456        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    1457        serde = self.sql(expression, "serde")
    1458        serde = f" SERDE {serde}" if serde else ""
    1459        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"
    1460
    1461    def null_sql(self, *_) -> str:
    1462        return "NULL"
    1463
    1464    def boolean_sql(self, expression: exp.Boolean) -> str:
    1465        return "TRUE" if expression.this else "FALSE"
    1466
    1467    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    1468        this = self.sql(expression, "this")
    1469        this = f"{this} " if this else this
    1470        return self.op_expressions(f"{this}ORDER BY", expression, flat=this or flat)  # type: ignore
    1471
    1472    def cluster_sql(self, expression: exp.Cluster) -> str:
    1473        return self.op_expressions("CLUSTER BY", expression)
    1474
    1475    def distribute_sql(self, expression: exp.Distribute) -> str:
    1476        return self.op_expressions("DISTRIBUTE BY", expression)
    1477
    1478    def sort_sql(self, expression: exp.Sort) -> str:
    1479        return self.op_expressions("SORT BY", expression)
    1480
    1481    def ordered_sql(self, expression: exp.Ordered) -> str:
    1482        desc = expression.args.get("desc")
    1483        asc = not desc
    1484
    1485        nulls_first = expression.args.get("nulls_first")
    1486        nulls_last = not nulls_first
    1487        nulls_are_large = self.NULL_ORDERING == "nulls_are_large"
    1488        nulls_are_small = self.NULL_ORDERING == "nulls_are_small"
    1489        nulls_are_last = self.NULL_ORDERING == "nulls_are_last"
    1490
    1491        sort_order = " DESC" if desc else ""
    1492        nulls_sort_change = ""
    1493        if nulls_first and (
    1494            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
    1495        ):
    1496            nulls_sort_change = " NULLS FIRST"
    1497        elif (
    1498            nulls_last
    1499            and ((asc and nulls_are_small) or (desc and nulls_are_large))
    1500            and not nulls_are_last
    1501        ):
    1502            nulls_sort_change = " NULLS LAST"
    1503
    1504        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
    1505            self.unsupported(
    1506                "Sorting in an ORDER BY on NULLS FIRST/NULLS LAST is not supported by this dialect"
    1507            )
    1508            nulls_sort_change = ""
    1509
    1510        return f"{self.sql(expression, 'this')}{sort_order}{nulls_sort_change}"
    1511
    1512    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    1513        partition = self.partition_by_sql(expression)
    1514        order = self.sql(expression, "order")
    1515        measures = self.expressions(expression, key="measures")
    1516        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    1517        rows = self.sql(expression, "rows")
    1518        rows = self.seg(rows) if rows else ""
    1519        after = self.sql(expression, "after")
    1520        after = self.seg(after) if after else ""
    1521        pattern = self.sql(expression, "pattern")
    1522        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    1523        definition_sqls = [
    1524            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    1525            for definition in expression.args.get("define", [])
    1526        ]
    1527        definitions = self.expressions(sqls=definition_sqls)
    1528        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    1529        body = "".join(
    1530            (
    1531                partition,
    1532                order,
    1533                measures,
    1534                rows,
    1535                after,
    1536                pattern,
    1537                define,
    1538            )
    1539        )
    1540        alias = self.sql(expression, "alias")
    1541        alias = f" {alias}" if alias else ""
    1542        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"
    1543
    1544    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    1545        limit: t.Optional[exp.Fetch | exp.Limit] = expression.args.get("limit")
    1546
    1547        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    1548            limit = exp.Limit(expression=limit.args.get("count"))
    1549        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    1550            limit = exp.Fetch(direction="FIRST", count=limit.expression)
    1551
    1552        fetch = isinstance(limit, exp.Fetch)
    1553
    1554        return csv(
    1555            *sqls,
    1556            *[self.sql(join) for join in expression.args.get("joins") or []],
    1557            self.sql(expression, "match"),
    1558            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    1559            self.sql(expression, "where"),
    1560            self.sql(expression, "group"),
    1561            self.sql(expression, "having"),
    1562            *self.after_having_modifiers(expression),
    1563            self.sql(expression, "order"),
    1564            *self.offset_limit_modifiers(expression, fetch, limit),
    1565            *self.after_limit_modifiers(expression),
    1566            sep="",
    1567        )
    1568
    1569    def offset_limit_modifiers(
    1570        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    1571    ) -> t.List[str]:
    1572        return [
    1573            self.sql(expression, "offset") if fetch else self.sql(limit),
    1574            self.sql(limit) if fetch else self.sql(expression, "offset"),
    1575        ]
    1576
    1577    def after_having_modifiers(self, expression: exp.Expression) -> t.List[str]:
    1578        return [
    1579            self.sql(expression, "qualify"),
    1580            self.seg("WINDOW ") + self.expressions(expression, key="windows", flat=True)
    1581            if expression.args.get("windows")
    1582            else "",
    1583        ]
    1584
    1585    def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]:
    1586        locks = self.expressions(expression, key="locks", sep=" ")
    1587        locks = f" {locks}" if locks else ""
    1588        return [locks, self.sql(expression, "sample")]
    1589
    1590    def select_sql(self, expression: exp.Select) -> str:
    1591        hint = self.sql(expression, "hint")
    1592        distinct = self.sql(expression, "distinct")
    1593        distinct = f" {distinct}" if distinct else ""
    1594        kind = self.sql(expression, "kind").upper()
    1595        expressions = self.expressions(expression)
    1596
    1597        if kind:
    1598            if kind in self.SELECT_KINDS:
    1599                kind = f" AS {kind}"
    1600            else:
    1601                if kind == "STRUCT":
    1602                    expressions = self.expressions(
    1603                        sqls=[
    1604                            self.sql(
    1605                                exp.Struct(
    1606                                    expressions=[
    1607                                        exp.column(e.output_name).eq(
    1608                                            e.this if isinstance(e, exp.Alias) else e
    1609                                        )
    1610                                        for e in expression.expressions
    1611                                    ]
    1612                                )
    1613                            )
    1614                        ]
    1615                    )
    1616                kind = ""
    1617
    1618        expressions = f"{self.sep()}{expressions}" if expressions else expressions
    1619        sql = self.query_modifiers(
    1620            expression,
    1621            f"SELECT{hint}{distinct}{kind}{expressions}",
    1622            self.sql(expression, "into", comment=False),
    1623            self.sql(expression, "from", comment=False),
    1624        )
    1625        return self.prepend_ctes(expression, sql)
    1626
    1627    def schema_sql(self, expression: exp.Schema) -> str:
    1628        this = self.sql(expression, "this")
    1629        this = f"{this} " if this else ""
    1630        sql = self.schema_columns_sql(expression)
    1631        return f"{this}{sql}"
    1632
    1633    def schema_columns_sql(self, expression: exp.Schema) -> str:
    1634        return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
    1635
    1636    def star_sql(self, expression: exp.Star) -> str:
    1637        except_ = self.expressions(expression, key="except", flat=True)
    1638        except_ = f"{self.seg(self.STAR_MAPPING['except'])} ({except_})" if except_ else ""
    1639        replace = self.expressions(expression, key="replace", flat=True)
    1640        replace = f"{self.seg(self.STAR_MAPPING['replace'])} ({replace})" if replace else ""
    1641        return f"*{except_}{replace}"
    1642
    1643    def parameter_sql(self, expression: exp.Parameter) -> str:
    1644        this = self.sql(expression, "this")
    1645        this = f"{{{this}}}" if expression.args.get("wrapped") else f"{this}"
    1646        return f"{self.PARAMETER_TOKEN}{this}"
    1647
    1648    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    1649        this = self.sql(expression, "this")
    1650        kind = expression.text("kind")
    1651        if kind:
    1652            kind = f"{kind}."
    1653        return f"@@{kind}{this}"
    1654
    1655    def placeholder_sql(self, expression: exp.Placeholder) -> str:
    1656        return f":{expression.name}" if expression.name else "?"
    1657
    1658    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    1659        alias = self.sql(expression, "alias")
    1660        alias = f"{sep}{alias}" if alias else ""
    1661
    1662        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    1663        pivots = f" {pivots}" if pivots else ""
    1664
    1665        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    1666        return self.prepend_ctes(expression, sql)
    1667
    1668    def qualify_sql(self, expression: exp.Qualify) -> str:
    1669        this = self.indent(self.sql(expression, "this"))
    1670        return f"{self.seg('QUALIFY')}{self.sep()}{this}"
    1671
    1672    def union_sql(self, expression: exp.Union) -> str:
    1673        return self.prepend_ctes(
    1674            expression,
    1675            self.set_operation(expression, self.union_op(expression)),
    1676        )
    1677
    1678    def union_op(self, expression: exp.Union) -> str:
    1679        kind = " DISTINCT" if self.EXPLICIT_UNION else ""
    1680        kind = kind if expression.args.get("distinct") else " ALL"
    1681        return f"UNION{kind}"
    1682
    1683    def unnest_sql(self, expression: exp.Unnest) -> str:
    1684        args = self.expressions(expression, flat=True)
    1685        alias = expression.args.get("alias")
    1686        if alias and self.UNNEST_COLUMN_ONLY:
    1687            columns = alias.columns
    1688            alias = self.sql(columns[0]) if columns else ""
    1689        else:
    1690            alias = self.sql(expression, "alias")
    1691        alias = f" AS {alias}" if alias else alias
    1692        ordinality = " WITH ORDINALITY" if expression.args.get("ordinality") else ""
    1693        offset = expression.args.get("offset")
    1694        offset = f" WITH OFFSET AS {self.sql(offset)}" if offset else ""
    1695        return f"UNNEST({args}){ordinality}{alias}{offset}"
    1696
    1697    def where_sql(self, expression: exp.Where) -> str:
    1698        this = self.indent(self.sql(expression, "this"))
    1699        return f"{self.seg('WHERE')}{self.sep()}{this}"
    1700
    1701    def window_sql(self, expression: exp.Window) -> str:
    1702        this = self.sql(expression, "this")
    1703        partition = self.partition_by_sql(expression)
    1704        order = expression.args.get("order")
    1705        order = self.order_sql(order, flat=True) if order else ""
    1706        spec = self.sql(expression, "spec")
    1707        alias = self.sql(expression, "alias")
    1708        over = self.sql(expression, "over") or "OVER"
    1709
    1710        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    1711
    1712        first = expression.args.get("first")
    1713        if first is None:
    1714            first = ""
    1715        else:
    1716            first = "FIRST" if first else "LAST"
    1717
    1718        if not partition and not order and not spec and alias:
    1719            return f"{this} {alias}"
    1720
    1721        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
    1722        return f"{this} ({args})"
    1723
    1724    def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str:
    1725        partition = self.expressions(expression, key="partition_by", flat=True)
    1726        return f"PARTITION BY {partition}" if partition else ""
    1727
    1728    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    1729        kind = self.sql(expression, "kind")
    1730        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    1731        end = (
    1732            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    1733            or "CURRENT ROW"
    1734        )
    1735        return f"{kind} BETWEEN {start} AND {end}"
    1736
    1737    def withingroup_sql(self, expression: exp.WithinGroup) -> str:
    1738        this = self.sql(expression, "this")
    1739        expression_sql = self.sql(expression, "expression")[1:]  # order has a leading space
    1740        return f"{this} WITHIN GROUP ({expression_sql})"
    1741
    1742    def between_sql(self, expression: exp.Between) -> str:
    1743        this = self.sql(expression, "this")
    1744        low = self.sql(expression, "low")
    1745        high = self.sql(expression, "high")
    1746        return f"{this} BETWEEN {low} AND {high}"
    1747
    1748    def bracket_sql(self, expression: exp.Bracket) -> str:
    1749        expressions = apply_index_offset(expression.this, expression.expressions, self.INDEX_OFFSET)
    1750        expressions_sql = ", ".join(self.sql(e) for e in expressions)
    1751
    1752        return f"{self.sql(expression, 'this')}[{expressions_sql}]"
    1753
    1754    def safebracket_sql(self, expression: exp.SafeBracket) -> str:
    1755        return self.bracket_sql(expression)
    1756
    1757    def all_sql(self, expression: exp.All) -> str:
    1758        return f"ALL {self.wrap(expression)}"
    1759
    1760    def any_sql(self, expression: exp.Any) -> str:
    1761        this = self.sql(expression, "this")
    1762        if isinstance(expression.this, exp.Subqueryable):
    1763            this = self.wrap(this)
    1764        return f"ANY {this}"
    1765
    1766    def exists_sql(self, expression: exp.Exists) -> str:
    1767        return f"EXISTS{self.wrap(expression)}"
    1768
    1769    def case_sql(self, expression: exp.Case) -> str:
    1770        this = self.sql(expression, "this")
    1771        statements = [f"CASE {this}" if this else "CASE"]
    1772
    1773        for e in expression.args["ifs"]:
    1774            statements.append(f"WHEN {self.sql(e, 'this')}")
    1775            statements.append(f"THEN {self.sql(e, 'true')}")
    1776
    1777        default = self.sql(expression, "default")
    1778
    1779        if default:
    1780            statements.append(f"ELSE {default}")
    1781
    1782        statements.append("END")
    1783
    1784        if self.pretty and self.text_width(statements) > self.max_text_width:
    1785            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    1786
    1787        return " ".join(statements)
    1788
    1789    def constraint_sql(self, expression: exp.Constraint) -> str:
    1790        this = self.sql(expression, "this")
    1791        expressions = self.expressions(expression, flat=True)
    1792        return f"CONSTRAINT {this} {expressions}"
    1793
    1794    def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str:
    1795        order = expression.args.get("order")
    1796        order = f" OVER ({self.order_sql(order, flat=True)})" if order else ""
    1797        return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}"
    1798
    1799    def extract_sql(self, expression: exp.Extract) -> str:
    1800        this = self.sql(expression, "this")
    1801        expression_sql = self.sql(expression, "expression")
    1802        return f"EXTRACT({this} FROM {expression_sql})"
    1803
    1804    def trim_sql(self, expression: exp.Trim) -> str:
    1805        trim_type = self.sql(expression, "position")
    1806
    1807        if trim_type == "LEADING":
    1808            return self.func("LTRIM", expression.this)
    1809        elif trim_type == "TRAILING":
    1810            return self.func("RTRIM", expression.this)
    1811        else:
    1812            return self.func("TRIM", expression.this, expression.expression)
    1813
    1814    def safeconcat_sql(self, expression: exp.SafeConcat) -> str:
    1815        expressions = expression.expressions
    1816        if self.STRICT_STRING_CONCAT:
    1817            expressions = (exp.cast(e, "text") for e in expressions)
    1818        return self.func("CONCAT", *expressions)
    1819
    1820    def check_sql(self, expression: exp.Check) -> str:
    1821        this = self.sql(expression, key="this")
    1822        return f"CHECK ({this})"
    1823
    1824    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    1825        expressions = self.expressions(expression, flat=True)
    1826        reference = self.sql(expression, "reference")
    1827        reference = f" {reference}" if reference else ""
    1828        delete = self.sql(expression, "delete")
    1829        delete = f" ON DELETE {delete}" if delete else ""
    1830        update = self.sql(expression, "update")
    1831        update = f" ON UPDATE {update}" if update else ""
    1832        return f"FOREIGN KEY ({expressions}){reference}{delete}{update}"
    1833
    1834    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    1835        expressions = self.expressions(expression, flat=True)
    1836        options = self.expressions(expression, key="options", flat=True, sep=" ")
    1837        options = f" {options}" if options else ""
    1838        return f"PRIMARY KEY ({expressions}){options}"
    1839
    1840    def if_sql(self, expression: exp.If) -> str:
    1841        return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false")))
    1842
    1843    def matchagainst_sql(self, expression: exp.MatchAgainst) -> str:
    1844        modifier = expression.args.get("modifier")
    1845        modifier = f" {modifier}" if modifier else ""
    1846        return f"{self.func('MATCH', *expression.expressions)} AGAINST({self.sql(expression, 'this')}{modifier})"
    1847
    1848    def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str:
    1849        return f"{self.sql(expression, 'this')}: {self.sql(expression, 'expression')}"
    1850
    1851    def jsonobject_sql(self, expression: exp.JSONObject) -> str:
    1852        null_handling = expression.args.get("null_handling")
    1853        null_handling = f" {null_handling}" if null_handling else ""
    1854        unique_keys = expression.args.get("unique_keys")
    1855        if unique_keys is not None:
    1856            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    1857        else:
    1858            unique_keys = ""
    1859        return_type = self.sql(expression, "return_type")
    1860        return_type = f" RETURNING {return_type}" if return_type else ""
    1861        format_json = " FORMAT JSON" if expression.args.get("format_json") else ""
    1862        encoding = self.sql(expression, "encoding")
    1863        encoding = f" ENCODING {encoding}" if encoding else ""
    1864        return self.func(
    1865            "JSON_OBJECT",
    1866            *expression.expressions,
    1867            suffix=f"{null_handling}{unique_keys}{return_type}{format_json}{encoding})",
    1868        )
    1869
    1870    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    1871        this = self.sql(expression, "this")
    1872        kind = self.sql(expression, "kind")
    1873        path = self.sql(expression, "path")
    1874        path = f" {path}" if path else ""
    1875        as_json = " AS JSON" if expression.args.get("as_json") else ""
    1876        return f"{this} {kind}{path}{as_json}"
    1877
    1878    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    1879        this = self.sql(expression, "this")
    1880        path = self.sql(expression, "path")
    1881        path = f", {path}" if path else ""
    1882        expressions = self.expressions(expression)
    1883        with_ = (
    1884            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    1885            if expressions
    1886            else ""
    1887        )
    1888        return f"OPENJSON({this}{path}){with_}"
    1889
    1890    def in_sql(self, expression: exp.In) -> str:
    1891        query = expression.args.get("query")
    1892        unnest = expression.args.get("unnest")
    1893        field = expression.args.get("field")
    1894        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    1895
    1896        if query:
    1897            in_sql = self.wrap(query)
    1898        elif unnest:
    1899            in_sql = self.in_unnest_op(unnest)
    1900        elif field:
    1901            in_sql = self.sql(field)
    1902        else:
    1903            in_sql = f"({self.expressions(expression, flat=True)})"
    1904
    1905        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"
    1906
    1907    def in_unnest_op(self, unnest: exp.Unnest) -> str:
    1908        return f"(SELECT {self.sql(unnest)})"
    1909
    1910    def interval_sql(self, expression: exp.Interval) -> str:
    1911        unit = self.sql(expression, "unit")
    1912        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    1913            unit = self.TIME_PART_SINGULARS.get(unit.lower(), unit)
    1914        unit = f" {unit}" if unit else ""
    1915
    1916        if self.SINGLE_STRING_INTERVAL:
    1917            this = expression.this.name if expression.this else ""
    1918            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    1919
    1920        this = self.sql(expression, "this")
    1921        if this:
    1922            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    1923            this = f" {this}" if unwrapped else f" ({this})"
    1924
    1925        return f"INTERVAL{this}{unit}"
    1926
    1927    def return_sql(self, expression: exp.Return) -> str:
    1928        return f"RETURN {self.sql(expression, 'this')}"
    1929
    1930    def reference_sql(self, expression: exp.Reference) -> str:
    1931        this = self.sql(expression, "this")
    1932        expressions = self.expressions(expression, flat=True)
    1933        expressions = f"({expressions})" if expressions else ""
    1934        options = self.expressions(expression, key="options", flat=True, sep=" ")
    1935        options = f" {options}" if options else ""
    1936        return f"REFERENCES {this}{expressions}{options}"
    1937
    1938    def anonymous_sql(self, expression: exp.Anonymous) -> str:
    1939        return self.func(expression.name, *expression.expressions)
    1940
    1941    def paren_sql(self, expression: exp.Paren) -> str:
    1942        if isinstance(expression.unnest(), exp.Select):
    1943            sql = self.wrap(expression)
    1944        else:
    1945            sql = self.seg(self.indent(self.sql(expression, "this")), sep="")
    1946            sql = f"({sql}{self.seg(')', sep='')}"
    1947
    1948        return self.prepend_ctes(expression, sql)
    1949
    1950    def neg_sql(self, expression: exp.Neg) -> str:
    1951        # This makes sure we don't convert "- - 5" to "--5", which is a comment
    1952        this_sql = self.sql(expression, "this")
    1953        sep = " " if this_sql[0] == "-" else ""
    1954        return f"-{sep}{this_sql}"
    1955
    1956    def not_sql(self, expression: exp.Not) -> str:
    1957        return f"NOT {self.sql(expression, 'this')}"
    1958
    1959    def alias_sql(self, expression: exp.Alias) -> str:
    1960        alias = self.sql(expression, "alias")
    1961        alias = f" AS {alias}" if alias else ""
    1962        return f"{self.sql(expression, 'this')}{alias}"
    1963
    1964    def aliases_sql(self, expression: exp.Aliases) -> str:
    1965        return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})"
    1966
    1967    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    1968        this = self.sql(expression, "this")
    1969        zone = self.sql(expression, "zone")
    1970        return f"{this} AT TIME ZONE {zone}"
    1971
    1972    def add_sql(self, expression: exp.Add) -> str:
    1973        return self.binary(expression, "+")
    1974
    1975    def and_sql(self, expression: exp.And) -> str:
    1976        return self.connector_sql(expression, "AND")
    1977
    1978    def connector_sql(self, expression: exp.Connector, op: str) -> str:
    1979        if not self.pretty:
    1980            return self.binary(expression, op)
    1981
    1982        sqls = tuple(
    1983            self.maybe_comment(self.sql(e), e, e.parent.comments or []) if i != 1 else self.sql(e)
    1984            for i, e in enumerate(expression.flatten(unnest=False))
    1985        )
    1986
    1987        sep = "\n" if self.text_width(sqls) > self.max_text_width else " "
    1988        return f"{sep}{op} ".join(sqls)
    1989
    1990    def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str:
    1991        return self.binary(expression, "&")
    1992
    1993    def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str:
    1994        return self.binary(expression, "<<")
    1995
    1996    def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str:
    1997        return f"~{self.sql(expression, 'this')}"
    1998
    1999    def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str:
    2000        return self.binary(expression, "|")
    2001
    2002    def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str:
    2003        return self.binary(expression, ">>")
    2004
    2005    def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str:
    2006        return self.binary(expression, "^")
    2007
    2008    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    2009        format_sql = self.sql(expression, "format")
    2010        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    2011        return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS {self.sql(expression, 'to')}{format_sql})"
    2012
    2013    def currentdate_sql(self, expression: exp.CurrentDate) -> str:
    2014        zone = self.sql(expression, "this")
    2015        return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE"
    2016
    2017    def collate_sql(self, expression: exp.Collate) -> str:
    2018        return self.binary(expression, "COLLATE")
    2019
    2020    def command_sql(self, expression: exp.Command) -> str:
    2021        return f"{self.sql(expression, 'this').upper()} {expression.text('expression').strip()}"
    2022
    2023    def comment_sql(self, expression: exp.Comment) -> str:
    2024        this = self.sql(expression, "this")
    2025        kind = expression.args["kind"]
    2026        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    2027        expression_sql = self.sql(expression, "expression")
    2028        return f"COMMENT{exists_sql}ON {kind} {this} IS {expression_sql}"
    2029
    2030    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    2031        this = self.sql(expression, "this")
    2032        delete = " DELETE" if expression.args.get("delete") else ""
    2033        recompress = self.sql(expression, "recompress")
    2034        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    2035        to_disk = self.sql(expression, "to_disk")
    2036        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    2037        to_volume = self.sql(expression, "to_volume")
    2038        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    2039        return f"{this}{delete}{recompress}{to_disk}{to_volume}"
    2040
    2041    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    2042        where = self.sql(expression, "where")
    2043        group = self.sql(expression, "group")
    2044        aggregates = self.expressions(expression, key="aggregates")
    2045        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    2046
    2047        if not (where or group or aggregates) and len(expression.expressions) == 1:
    2048            return f"TTL {self.expressions(expression, flat=True)}"
    2049
    2050        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"
    2051
    2052    def transaction_sql(self, expression: exp.Transaction) -> str:
    2053        return "BEGIN"
    2054
    2055    def commit_sql(self, expression: exp.Commit) -> str:
    2056        chain = expression.args.get("chain")
    2057        if chain is not None:
    2058            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    2059
    2060        return f"COMMIT{chain or ''}"
    2061
    2062    def rollback_sql(self, expression: exp.Rollback) -> str:
    2063        savepoint = expression.args.get("savepoint")
    2064        savepoint = f" TO {savepoint}" if savepoint else ""
    2065        return f"ROLLBACK{savepoint}"
    2066
    2067    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    2068        this = self.sql(expression, "this")
    2069
    2070        dtype = self.sql(expression, "dtype")
    2071        if dtype:
    2072            collate = self.sql(expression, "collate")
    2073            collate = f" COLLATE {collate}" if collate else ""
    2074            using = self.sql(expression, "using")
    2075            using = f" USING {using}" if using else ""
    2076            return f"ALTER COLUMN {this} TYPE {dtype}{collate}{using}"
    2077
    2078        default = self.sql(expression, "default")
    2079        if default:
    2080            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    2081
    2082        if not expression.args.get("drop"):
    2083            self.unsupported("Unsupported ALTER COLUMN syntax")
    2084
    2085        return f"ALTER COLUMN {this} DROP DEFAULT"
    2086
    2087    def renametable_sql(self, expression: exp.RenameTable) -> str:
    2088        if not self.RENAME_TABLE_WITH_DB:
    2089            # Remove db from tables
    2090            expression = expression.transform(
    2091                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    2092            )
    2093        this = self.sql(expression, "this")
    2094        return f"RENAME TO {this}"
    2095
    2096    def altertable_sql(self, expression: exp.AlterTable) -> str:
    2097        actions = expression.args["actions"]
    2098
    2099        if isinstance(actions[0], exp.ColumnDef):
    2100            actions = self.expressions(expression, key="actions", prefix="ADD COLUMN ")
    2101        elif isinstance(actions[0], exp.Schema):
    2102            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    2103        elif isinstance(actions[0], exp.Delete):
    2104            actions = self.expressions(expression, key="actions", flat=True)
    2105        else:
    2106            actions = self.expressions(expression, key="actions")
    2107
    2108        exists = " IF EXISTS" if expression.args.get("exists") else ""
    2109        return f"ALTER TABLE{exists} {self.sql(expression, 'this')} {actions}"
    2110
    2111    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    2112        expressions = self.expressions(expression)
    2113        exists = " IF EXISTS " if expression.args.get("exists") else " "
    2114        return f"DROP{exists}{expressions}"
    2115
    2116    def addconstraint_sql(self, expression: exp.AddConstraint) -> str:
    2117        this = self.sql(expression, "this")
    2118        expression_ = self.sql(expression, "expression")
    2119        add_constraint = f"ADD CONSTRAINT {this}" if this else "ADD"
    2120
    2121        enforced = expression.args.get("enforced")
    2122        if enforced is not None:
    2123            return f"{add_constraint} CHECK ({expression_}){' ENFORCED' if enforced else ''}"
    2124
    2125        return f"{add_constraint} {expression_}"
    2126
    2127    def distinct_sql(self, expression: exp.Distinct) -> str:
    2128        this = self.expressions(expression, flat=True)
    2129        this = f" {this}" if this else ""
    2130
    2131        on = self.sql(expression, "on")
    2132        on = f" ON {on}" if on else ""
    2133        return f"DISTINCT{this}{on}"
    2134
    2135    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
    2136        return f"{self.sql(expression, 'this')} IGNORE NULLS"
    2137
    2138    def respectnulls_sql(self, expression: exp.RespectNulls) -> str:
    2139        return f"{self.sql(expression, 'this')} RESPECT NULLS"
    2140
    2141    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    2142        return self.sql(
    2143            exp.Cast(
    2144                this=exp.Div(this=expression.this, expression=expression.expression),
    2145                to=exp.DataType(this=exp.DataType.Type.INT),
    2146            )
    2147        )
    2148
    2149    def dpipe_sql(self, expression: exp.DPipe) -> str:
    2150        return self.binary(expression, "||")
    2151
    2152    def safedpipe_sql(self, expression: exp.SafeDPipe) -> str:
    2153        if self.STRICT_STRING_CONCAT:
    2154            return self.func("CONCAT", *(exp.cast(e, "text") for e in expression.flatten()))
    2155        return self.dpipe_sql(expression)
    2156
    2157    def div_sql(self, expression: exp.Div) -> str:
    2158        return self.binary(expression, "/")
    2159
    2160    def overlaps_sql(self, expression: exp.Overlaps) -> str:
    2161        return self.binary(expression, "OVERLAPS")
    2162
    2163    def distance_sql(self, expression: exp.Distance) -> str:
    2164        return self.binary(expression, "<->")
    2165
    2166    def dot_sql(self, expression: exp.Dot) -> str:
    2167        return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}"
    2168
    2169    def eq_sql(self, expression: exp.EQ) -> str:
    2170        return self.binary(expression, "=")
    2171
    2172    def escape_sql(self, expression: exp.Escape) -> str:
    2173        return self.binary(expression, "ESCAPE")
    2174
    2175    def glob_sql(self, expression: exp.Glob) -> str:
    2176        return self.binary(expression, "GLOB")
    2177
    2178    def gt_sql(self, expression: exp.GT) -> str:
    2179        return self.binary(expression, ">")
    2180
    2181    def gte_sql(self, expression: exp.GTE) -> str:
    2182        return self.binary(expression, ">=")
    2183
    2184    def ilike_sql(self, expression: exp.ILike) -> str:
    2185        return self.binary(expression, "ILIKE")
    2186
    2187    def ilikeany_sql(self, expression: exp.ILikeAny) -> str:
    2188        return self.binary(expression, "ILIKE ANY")
    2189
    2190    def is_sql(self, expression: exp.Is) -> str:
    2191        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    2192            return self.sql(
    2193                expression.this if expression.expression.this else exp.not_(expression.this)
    2194            )
    2195        return self.binary(expression, "IS")
    2196
    2197    def like_sql(self, expression: exp.Like) -> str:
    2198        return self.binary(expression, "LIKE")
    2199
    2200    def likeany_sql(self, expression: exp.LikeAny) -> str:
    2201        return self.binary(expression, "LIKE ANY")
    2202
    2203    def similarto_sql(self, expression: exp.SimilarTo) -> str:
    2204        return self.binary(expression, "SIMILAR TO")
    2205
    2206    def lt_sql(self, expression: exp.LT) -> str:
    2207        return self.binary(expression, "<")
    2208
    2209    def lte_sql(self, expression: exp.LTE) -> str:
    2210        return self.binary(expression, "<=")
    2211
    2212    def mod_sql(self, expression: exp.Mod) -> str:
    2213        return self.binary(expression, "%")
    2214
    2215    def mul_sql(self, expression: exp.Mul) -> str:
    2216        return self.binary(expression, "*")
    2217
    2218    def neq_sql(self, expression: exp.NEQ) -> str:
    2219        return self.binary(expression, "<>")
    2220
    2221    def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str:
    2222        return self.binary(expression, "IS NOT DISTINCT FROM")
    2223
    2224    def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str:
    2225        return self.binary(expression, "IS DISTINCT FROM")
    2226
    2227    def or_sql(self, expression: exp.Or) -> str:
    2228        return self.connector_sql(expression, "OR")
    2229
    2230    def slice_sql(self, expression: exp.Slice) -> str:
    2231        return self.binary(expression, ":")
    2232
    2233    def sub_sql(self, expression: exp.Sub) -> str:
    2234        return self.binary(expression, "-")
    2235
    2236    def trycast_sql(self, expression: exp.TryCast) -> str:
    2237        return self.cast_sql(expression, safe_prefix="TRY_")
    2238
    2239    def use_sql(self, expression: exp.Use) -> str:
    2240        kind = self.sql(expression, "kind")
    2241        kind = f" {kind}" if kind else ""
    2242        this = self.sql(expression, "this")
    2243        this = f" {this}" if this else ""
    2244        return f"USE{kind}{this}"
    2245
    2246    def binary(self, expression: exp.Binary, op: str) -> str:
    2247        op = self.maybe_comment(op, comments=expression.comments)
    2248        return f"{self.sql(expression, 'this')} {op} {self.sql(expression, 'expression')}"
    2249
    2250    def function_fallback_sql(self, expression: exp.Func) -> str:
    2251        args = []
    2252        for arg_value in expression.args.values():
    2253            if isinstance(arg_value, list):
    2254                for value in arg_value:
    2255                    args.append(value)
    2256            else:
    2257                args.append(arg_value)
    2258
    2259        return self.func(expression.sql_name(), *args)
    2260
    2261    def func(
    2262        self,
    2263        name: str,
    2264        *args: t.Optional[exp.Expression | str],
    2265        prefix: str = "(",
    2266        suffix: str = ")",
    2267    ) -> str:
    2268        return f"{self.normalize_func(name)}{prefix}{self.format_args(*args)}{suffix}"
    2269
    2270    def format_args(self, *args: t.Optional[str | exp.Expression]) -> str:
    2271        arg_sqls = tuple(self.sql(arg) for arg in args if arg is not None)
    2272        if self.pretty and self.text_width(arg_sqls) > self.max_text_width:
    2273            return self.indent("\n" + f",\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True)
    2274        return ", ".join(arg_sqls)
    2275
    2276    def text_width(self, args: t.Iterable) -> int:
    2277        return sum(len(arg) for arg in args)
    2278
    2279    def format_time(self, expression: exp.Expression) -> t.Optional[str]:
    2280        return format_time(
    2281            self.sql(expression, "format"), self.INVERSE_TIME_MAPPING, self.INVERSE_TIME_TRIE
    2282        )
    2283
    2284    def expressions(
    2285        self,
    2286        expression: t.Optional[exp.Expression] = None,
    2287        key: t.Optional[str] = None,
    2288        sqls: t.Optional[t.List[str]] = None,
    2289        flat: bool = False,
    2290        indent: bool = True,
    2291        sep: str = ", ",
    2292        prefix: str = "",
    2293    ) -> str:
    2294        expressions = expression.args.get(key or "expressions") if expression else sqls
    2295
    2296        if not expressions:
    2297            return ""
    2298
    2299        if flat:
    2300            return sep.join(self.sql(e) for e in expressions)
    2301
    2302        num_sqls = len(expressions)
    2303
    2304        # These are calculated once in case we have the leading_comma / pretty option set, correspondingly
    2305        pad = " " * self.pad
    2306        stripped_sep = sep.strip()
    2307
    2308        result_sqls = []
    2309        for i, e in enumerate(expressions):
    2310            sql = self.sql(e, comment=False)
    2311            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    2312
    2313            if self.pretty:
    2314                if self.leading_comma:
    2315                    result_sqls.append(f"{sep if i > 0 else pad}{prefix}{sql}{comments}")
    2316                else:
    2317                    result_sqls.append(
    2318                        f"{prefix}{sql}{stripped_sep if i + 1 < num_sqls else ''}{comments}"
    2319                    )
    2320            else:
    2321                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    2322
    2323        result_sql = "\n".join(result_sqls) if self.pretty else "".join(result_sqls)
    2324        return self.indent(result_sql, skip_first=False) if indent else result_sql
    2325
    2326    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    2327        flat = flat or isinstance(expression.parent, exp.Properties)
    2328        expressions_sql = self.expressions(expression, flat=flat)
    2329        if flat:
    2330            return f"{op} {expressions_sql}"
    2331        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"
    2332
    2333    def naked_property(self, expression: exp.Property) -> str:
    2334        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    2335        if not property_name:
    2336            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    2337        return f"{property_name} {self.sql(expression, 'this')}"
    2338
    2339    def set_operation(self, expression: exp.Expression, op: str) -> str:
    2340        this = self.sql(expression, "this")
    2341        op = self.seg(op)
    2342        return self.query_modifiers(
    2343            expression, f"{this}{op}{self.sep()}{self.sql(expression, 'expression')}"
    2344        )
    2345
    2346    def tag_sql(self, expression: exp.Tag) -> str:
    2347        return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}"
    2348
    2349    def token_sql(self, token_type: TokenType) -> str:
    2350        return self.TOKEN_MAPPING.get(token_type, token_type.name)
    2351
    2352    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    2353        this = self.sql(expression, "this")
    2354        expressions = self.no_identify(self.expressions, expression)
    2355        expressions = (
    2356            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    2357        )
    2358        return f"{this}{expressions}"
    2359
    2360    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    2361        this = self.sql(expression, "this")
    2362        expressions = self.expressions(expression, flat=True)
    2363        return f"{this}({expressions})"
    2364
    2365    def kwarg_sql(self, expression: exp.Kwarg) -> str:
    2366        return self.binary(expression, "=>")
    2367
    2368    def when_sql(self, expression: exp.When) -> str:
    2369        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    2370        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    2371        condition = self.sql(expression, "condition")
    2372        condition = f" AND {condition}" if condition else ""
    2373
    2374        then_expression = expression.args.get("then")
    2375        if isinstance(then_expression, exp.Insert):
    2376            then = f"INSERT {self.sql(then_expression, 'this')}"
    2377            if "expression" in then_expression.args:
    2378                then += f" VALUES {self.sql(then_expression, 'expression')}"
    2379        elif isinstance(then_expression, exp.Update):
    2380            if isinstance(then_expression.args.get("expressions"), exp.Star):
    2381                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    2382            else:
    2383                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    2384        else:
    2385            then = self.sql(then_expression)
    2386        return f"WHEN {matched}{source}{condition} THEN {then}"
    2387
    2388    def merge_sql(self, expression: exp.Merge) -> str:
    2389        this = self.sql(expression, "this")
    2390        using = f"USING {self.sql(expression, 'using')}"
    2391        on = f"ON {self.sql(expression, 'on')}"
    2392        return f"MERGE INTO {this} {using} {on} {self.expressions(expression, sep=' ')}"
    2393
    2394    def tochar_sql(self, expression: exp.ToChar) -> str:
    2395        if expression.args.get("format"):
    2396            self.unsupported("Format argument unsupported for TO_CHAR/TO_VARCHAR function")
    2397
    2398        return self.sql(exp.cast(expression.this, "text"))
    2399
    2400    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    2401        this = self.sql(expression, "this")
    2402        kind = self.sql(expression, "kind")
    2403        settings_sql = self.expressions(expression, key="settings", sep=" ")
    2404        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    2405        return f"{this}({kind}{args})"
    2406
    2407    def dictrange_sql(self, expression: exp.DictRange) -> str:
    2408        this = self.sql(expression, "this")
    2409        max = self.sql(expression, "max")
    2410        min = self.sql(expression, "min")
    2411        return f"{this}(MIN {min} MAX {max})"
    2412
    2413    def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str:
    2414        return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}"
    2415
    2416    def oncluster_sql(self, expression: exp.OnCluster) -> str:
    2417        return ""
    2418
    2419    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    2420        expressions = self.expressions(expression, key="expressions", flat=True)
    2421        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    2422        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    2423        buckets = self.sql(expression, "buckets")
    2424        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"
    2425
    2426
    2427def cached_generator(
    2428    cache: t.Optional[t.Dict[int, str]] = None
    2429) -> t.Callable[[exp.Expression], str]:
    2430    """Returns a cached generator."""
    2431    cache = {} if cache is None else cache
    2432    generator = Generator(normalize=True, identify="safe")
    2433    return lambda e: generator.generate(e, cache)

logger = <Logger sqlglot (WARNING)>
class Generator: View Source

      16class Generator:
      17    """
      18    Generator converts a given syntax tree to the corresponding SQL string.
      19
      20    Args:
      21        pretty: Whether or not to format the produced SQL string.
      22            Default: False.
      23        identify: Determines when an identifier should be quoted. Possible values are:
      24            False (default): Never quote, except in cases where it's mandatory by the dialect.
      25            True or 'always': Always quote.
      26            'safe': Only quote identifiers that are case insensitive.
      27        normalize: Whether or not to normalize identifiers to lowercase.
      28            Default: False.
      29        pad: Determines the pad size in a formatted string.
      30            Default: 2.
      31        indent: Determines the indentation size in a formatted string.
      32            Default: 2.
      33        normalize_functions: Whether or not to normalize all function names. Possible values are:
      34            "upper" or True (default): Convert names to uppercase.
      35            "lower": Convert names to lowercase.
      36            False: Disables function name normalization.
      37        unsupported_level: Determines the generator's behavior when it encounters unsupported expressions.
      38            Default ErrorLevel.WARN.
      39        max_unsupported: Maximum number of unsupported messages to include in a raised UnsupportedError.
      40            This is only relevant if unsupported_level is ErrorLevel.RAISE.
      41            Default: 3
      42        leading_comma: Determines whether or not the comma is leading or trailing in select expressions.
      43            This is only relevant when generating in pretty mode.
      44            Default: False
      45        max_text_width: The max number of characters in a segment before creating new lines in pretty mode.
      46            The default is on the smaller end because the length only represents a segment and not the true
      47            line length.
      48            Default: 80
      49        comments: Whether or not to preserve comments in the output SQL code.
      50            Default: True
      51    """
      52
      53    TRANSFORMS = {
      54        exp.DateAdd: lambda self, e: self.func(
      55            "DATE_ADD", e.this, e.expression, exp.Literal.string(e.text("unit"))
      56        ),
      57        exp.TsOrDsAdd: lambda self, e: self.func(
      58            "TS_OR_DS_ADD", e.this, e.expression, exp.Literal.string(e.text("unit"))
      59        ),
      60        exp.CaseSpecificColumnConstraint: lambda self, e: f"{'NOT ' if e.args.get('not_') else ''}CASESPECIFIC",
      61        exp.CharacterSetColumnConstraint: lambda self, e: f"CHARACTER SET {self.sql(e, 'this')}",
      62        exp.CharacterSetProperty: lambda self, e: f"{'DEFAULT ' if e.args.get('default') else ''}CHARACTER SET={self.sql(e, 'this')}",
      63        exp.CheckColumnConstraint: lambda self, e: f"CHECK ({self.sql(e, 'this')})",
      64        exp.CollateColumnConstraint: lambda self, e: f"COLLATE {self.sql(e, 'this')}",
      65        exp.CopyGrantsProperty: lambda self, e: "COPY GRANTS",
      66        exp.CommentColumnConstraint: lambda self, e: f"COMMENT {self.sql(e, 'this')}",
      67        exp.DateFormatColumnConstraint: lambda self, e: f"FORMAT {self.sql(e, 'this')}",
      68        exp.DefaultColumnConstraint: lambda self, e: f"DEFAULT {self.sql(e, 'this')}",
      69        exp.EncodeColumnConstraint: lambda self, e: f"ENCODE {self.sql(e, 'this')}",
      70        exp.ExecuteAsProperty: lambda self, e: self.naked_property(e),
      71        exp.ExternalProperty: lambda self, e: "EXTERNAL",
      72        exp.InlineLengthColumnConstraint: lambda self, e: f"INLINE LENGTH {self.sql(e, 'this')}",
      73        exp.LanguageProperty: lambda self, e: self.naked_property(e),
      74        exp.LocationProperty: lambda self, e: self.naked_property(e),
      75        exp.LogProperty: lambda self, e: f"{'NO ' if e.args.get('no') else ''}LOG",
      76        exp.MaterializedProperty: lambda self, e: "MATERIALIZED",
      77        exp.NoPrimaryIndexProperty: lambda self, e: "NO PRIMARY INDEX",
      78        exp.OnCommitProperty: lambda self, e: f"ON COMMIT {'DELETE' if e.args.get('delete') else 'PRESERVE'} ROWS",
      79        exp.OnUpdateColumnConstraint: lambda self, e: f"ON UPDATE {self.sql(e, 'this')}",
      80        exp.PathColumnConstraint: lambda self, e: f"PATH {self.sql(e, 'this')}",
      81        exp.ReturnsProperty: lambda self, e: self.naked_property(e),
      82        exp.SetProperty: lambda self, e: f"{'MULTI' if e.args.get('multi') else ''}SET",
      83        exp.SettingsProperty: lambda self, e: f"SETTINGS{self.seg('')}{(self.expressions(e))}",
      84        exp.SqlSecurityProperty: lambda self, e: f"SQL SECURITY {'DEFINER' if e.args.get('definer') else 'INVOKER'}",
      85        exp.StabilityProperty: lambda self, e: e.name,
      86        exp.TemporaryProperty: lambda self, e: f"TEMPORARY",
      87        exp.ToTableProperty: lambda self, e: f"TO {self.sql(e.this)}",
      88        exp.TransientProperty: lambda self, e: "TRANSIENT",
      89        exp.TitleColumnConstraint: lambda self, e: f"TITLE {self.sql(e, 'this')}",
      90        exp.UppercaseColumnConstraint: lambda self, e: f"UPPERCASE",
      91        exp.VarMap: lambda self, e: self.func("MAP", e.args["keys"], e.args["values"]),
      92        exp.VolatileProperty: lambda self, e: "VOLATILE",
      93        exp.WithJournalTableProperty: lambda self, e: f"WITH JOURNAL TABLE={self.sql(e, 'this')}",
      94    }
      95
      96    # Whether or not null ordering is supported in order by
      97    NULL_ORDERING_SUPPORTED = True
      98
      99    # Whether or not locking reads (i.e. SELECT ... FOR UPDATE/SHARE) are supported
     100    LOCKING_READS_SUPPORTED = False
     101
     102    # Always do union distinct or union all
     103    EXPLICIT_UNION = False
     104
     105    # Wrap derived values in parens, usually standard but spark doesn't support it
     106    WRAP_DERIVED_VALUES = True
     107
     108    # Whether or not create function uses an AS before the RETURN
     109    CREATE_FUNCTION_RETURN_AS = True
     110
     111    # Whether or not MERGE ... WHEN MATCHED BY SOURCE is allowed
     112    MATCHED_BY_SOURCE = True
     113
     114    # Whether or not the INTERVAL expression works only with values like '1 day'
     115    SINGLE_STRING_INTERVAL = False
     116
     117    # Whether or not the plural form of date parts like day (i.e. "days") is supported in INTERVALs
     118    INTERVAL_ALLOWS_PLURAL_FORM = True
     119
     120    # Whether or not the TABLESAMPLE clause supports a method name, like BERNOULLI
     121    TABLESAMPLE_WITH_METHOD = True
     122
     123    # Whether or not to treat the number in TABLESAMPLE (50) as a percentage
     124    TABLESAMPLE_SIZE_IS_PERCENT = False
     125
     126    # Whether or not limit and fetch are supported (possible values: "ALL", "LIMIT", "FETCH")
     127    LIMIT_FETCH = "ALL"
     128
     129    # Whether or not a table is allowed to be renamed with a db
     130    RENAME_TABLE_WITH_DB = True
     131
     132    # The separator for grouping sets and rollups
     133    GROUPINGS_SEP = ","
     134
     135    # The string used for creating an index on a table
     136    INDEX_ON = "ON"
     137
     138    # Whether or not join hints should be generated
     139    JOIN_HINTS = True
     140
     141    # Whether or not table hints should be generated
     142    TABLE_HINTS = True
     143
     144    # Whether or not comparing against booleans (e.g. x IS TRUE) is supported
     145    IS_BOOL_ALLOWED = True
     146
     147    # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax
     148    SELECT_KINDS: t.Tuple[str, ...] = ("STRUCT", "VALUE")
     149
     150    TYPE_MAPPING = {
     151        exp.DataType.Type.NCHAR: "CHAR",
     152        exp.DataType.Type.NVARCHAR: "VARCHAR",
     153        exp.DataType.Type.MEDIUMTEXT: "TEXT",
     154        exp.DataType.Type.LONGTEXT: "TEXT",
     155        exp.DataType.Type.MEDIUMBLOB: "BLOB",
     156        exp.DataType.Type.LONGBLOB: "BLOB",
     157        exp.DataType.Type.INET: "INET",
     158    }
     159
     160    STAR_MAPPING = {
     161        "except": "EXCEPT",
     162        "replace": "REPLACE",
     163    }
     164
     165    TIME_PART_SINGULARS = {
     166        "microseconds": "microsecond",
     167        "seconds": "second",
     168        "minutes": "minute",
     169        "hours": "hour",
     170        "days": "day",
     171        "weeks": "week",
     172        "months": "month",
     173        "quarters": "quarter",
     174        "years": "year",
     175    }
     176
     177    TOKEN_MAPPING: t.Dict[TokenType, str] = {}
     178
     179    STRUCT_DELIMITER = ("<", ">")
     180
     181    PARAMETER_TOKEN = "@"
     182
     183    PROPERTIES_LOCATION = {
     184        exp.AlgorithmProperty: exp.Properties.Location.POST_CREATE,
     185        exp.AutoIncrementProperty: exp.Properties.Location.POST_SCHEMA,
     186        exp.BlockCompressionProperty: exp.Properties.Location.POST_NAME,
     187        exp.CharacterSetProperty: exp.Properties.Location.POST_SCHEMA,
     188        exp.ChecksumProperty: exp.Properties.Location.POST_NAME,
     189        exp.CollateProperty: exp.Properties.Location.POST_SCHEMA,
     190        exp.CopyGrantsProperty: exp.Properties.Location.POST_SCHEMA,
     191        exp.Cluster: exp.Properties.Location.POST_SCHEMA,
     192        exp.ClusteredByProperty: exp.Properties.Location.POST_SCHEMA,
     193        exp.DataBlocksizeProperty: exp.Properties.Location.POST_NAME,
     194        exp.DefinerProperty: exp.Properties.Location.POST_CREATE,
     195        exp.DictRange: exp.Properties.Location.POST_SCHEMA,
     196        exp.DictProperty: exp.Properties.Location.POST_SCHEMA,
     197        exp.DistKeyProperty: exp.Properties.Location.POST_SCHEMA,
     198        exp.DistStyleProperty: exp.Properties.Location.POST_SCHEMA,
     199        exp.EngineProperty: exp.Properties.Location.POST_SCHEMA,
     200        exp.ExecuteAsProperty: exp.Properties.Location.POST_SCHEMA,
     201        exp.ExternalProperty: exp.Properties.Location.POST_CREATE,
     202        exp.FallbackProperty: exp.Properties.Location.POST_NAME,
     203        exp.FileFormatProperty: exp.Properties.Location.POST_WITH,
     204        exp.FreespaceProperty: exp.Properties.Location.POST_NAME,
     205        exp.IsolatedLoadingProperty: exp.Properties.Location.POST_NAME,
     206        exp.JournalProperty: exp.Properties.Location.POST_NAME,
     207        exp.LanguageProperty: exp.Properties.Location.POST_SCHEMA,
     208        exp.LikeProperty: exp.Properties.Location.POST_SCHEMA,
     209        exp.LocationProperty: exp.Properties.Location.POST_SCHEMA,
     210        exp.LockingProperty: exp.Properties.Location.POST_ALIAS,
     211        exp.LogProperty: exp.Properties.Location.POST_NAME,
     212        exp.MaterializedProperty: exp.Properties.Location.POST_CREATE,
     213        exp.MergeBlockRatioProperty: exp.Properties.Location.POST_NAME,
     214        exp.NoPrimaryIndexProperty: exp.Properties.Location.POST_EXPRESSION,
     215        exp.OnCommitProperty: exp.Properties.Location.POST_EXPRESSION,
     216        exp.Order: exp.Properties.Location.POST_SCHEMA,
     217        exp.PartitionedByProperty: exp.Properties.Location.POST_WITH,
     218        exp.PrimaryKey: exp.Properties.Location.POST_SCHEMA,
     219        exp.Property: exp.Properties.Location.POST_WITH,
     220        exp.ReturnsProperty: exp.Properties.Location.POST_SCHEMA,
     221        exp.RowFormatProperty: exp.Properties.Location.POST_SCHEMA,
     222        exp.RowFormatDelimitedProperty: exp.Properties.Location.POST_SCHEMA,
     223        exp.RowFormatSerdeProperty: exp.Properties.Location.POST_SCHEMA,
     224        exp.SchemaCommentProperty: exp.Properties.Location.POST_SCHEMA,
     225        exp.SerdeProperties: exp.Properties.Location.POST_SCHEMA,
     226        exp.Set: exp.Properties.Location.POST_SCHEMA,
     227        exp.SettingsProperty: exp.Properties.Location.POST_SCHEMA,
     228        exp.SetProperty: exp.Properties.Location.POST_CREATE,
     229        exp.SortKeyProperty: exp.Properties.Location.POST_SCHEMA,
     230        exp.SqlSecurityProperty: exp.Properties.Location.POST_CREATE,
     231        exp.StabilityProperty: exp.Properties.Location.POST_SCHEMA,
     232        exp.TemporaryProperty: exp.Properties.Location.POST_CREATE,
     233        exp.ToTableProperty: exp.Properties.Location.POST_SCHEMA,
     234        exp.TransientProperty: exp.Properties.Location.POST_CREATE,
     235        exp.MergeTreeTTL: exp.Properties.Location.POST_SCHEMA,
     236        exp.VolatileProperty: exp.Properties.Location.POST_CREATE,
     237        exp.WithDataProperty: exp.Properties.Location.POST_EXPRESSION,
     238        exp.WithJournalTableProperty: exp.Properties.Location.POST_NAME,
     239    }
     240
     241    # Keywords that can't be used as unquoted identifier names
     242    RESERVED_KEYWORDS: t.Set[str] = set()
     243
     244    # Expressions whose comments are separated from them for better formatting
     245    WITH_SEPARATED_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = (
     246        exp.Select,
     247        exp.From,
     248        exp.Where,
     249        exp.With,
     250    )
     251
     252    # Expressions that can remain unwrapped when appearing in the context of an INTERVAL
     253    UNWRAPPED_INTERVAL_VALUES: t.Tuple[t.Type[exp.Expression], ...] = (
     254        exp.Column,
     255        exp.Literal,
     256        exp.Neg,
     257        exp.Paren,
     258    )
     259
     260    SENTINEL_LINE_BREAK = "__SQLGLOT__LB__"
     261
     262    # Autofilled
     263    INVERSE_TIME_MAPPING: t.Dict[str, str] = {}
     264    INVERSE_TIME_TRIE: t.Dict = {}
     265    INDEX_OFFSET = 0
     266    UNNEST_COLUMN_ONLY = False
     267    ALIAS_POST_TABLESAMPLE = False
     268    IDENTIFIERS_CAN_START_WITH_DIGIT = False
     269    STRICT_STRING_CONCAT = False
     270    NORMALIZE_FUNCTIONS: bool | str = "upper"
     271    NULL_ORDERING = "nulls_are_small"
     272
     273    can_identify: t.Callable[[str, str | bool], bool]
     274
     275    # Delimiters for quotes, identifiers and the corresponding escape characters
     276    QUOTE_START = "'"
     277    QUOTE_END = "'"
     278    IDENTIFIER_START = '"'
     279    IDENTIFIER_END = '"'
     280    STRING_ESCAPE = "'"
     281    IDENTIFIER_ESCAPE = '"'
     282
     283    # Delimiters for bit, hex, byte and raw literals
     284    BIT_START: t.Optional[str] = None
     285    BIT_END: t.Optional[str] = None
     286    HEX_START: t.Optional[str] = None
     287    HEX_END: t.Optional[str] = None
     288    BYTE_START: t.Optional[str] = None
     289    BYTE_END: t.Optional[str] = None
     290    RAW_START: t.Optional[str] = None
     291    RAW_END: t.Optional[str] = None
     292
     293    __slots__ = (
     294        "pretty",
     295        "identify",
     296        "normalize",
     297        "pad",
     298        "_indent",
     299        "normalize_functions",
     300        "unsupported_level",
     301        "max_unsupported",
     302        "leading_comma",
     303        "max_text_width",
     304        "comments",
     305        "unsupported_messages",
     306        "_escaped_quote_end",
     307        "_escaped_identifier_end",
     308        "_cache",
     309    )
     310
     311    def __init__(
     312        self,
     313        pretty: t.Optional[bool] = None,
     314        identify: str | bool = False,
     315        normalize: bool = False,
     316        pad: int = 2,
     317        indent: int = 2,
     318        normalize_functions: t.Optional[str | bool] = None,
     319        unsupported_level: ErrorLevel = ErrorLevel.WARN,
     320        max_unsupported: int = 3,
     321        leading_comma: bool = False,
     322        max_text_width: int = 80,
     323        comments: bool = True,
     324    ):
     325        import sqlglot
     326
     327        self.pretty = pretty if pretty is not None else sqlglot.pretty
     328        self.identify = identify
     329        self.normalize = normalize
     330        self.pad = pad
     331        self._indent = indent
     332        self.unsupported_level = unsupported_level
     333        self.max_unsupported = max_unsupported
     334        self.leading_comma = leading_comma
     335        self.max_text_width = max_text_width
     336        self.comments = comments
     337
     338        # This is both a Dialect property and a Generator argument, so we prioritize the latter
     339        self.normalize_functions = (
     340            self.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions
     341        )
     342
     343        self.unsupported_messages: t.List[str] = []
     344        self._escaped_quote_end: str = self.STRING_ESCAPE + self.QUOTE_END
     345        self._escaped_identifier_end: str = self.IDENTIFIER_ESCAPE + self.IDENTIFIER_END
     346        self._cache: t.Optional[t.Dict[int, str]] = None
     347
     348    def generate(
     349        self,
     350        expression: t.Optional[exp.Expression],
     351        cache: t.Optional[t.Dict[int, str]] = None,
     352    ) -> str:
     353        """
     354        Generates the SQL string corresponding to the given syntax tree.
     355
     356        Args:
     357            expression: The syntax tree.
     358            cache: An optional sql string cache. This leverages the hash of an Expression
     359                which can be slow to compute, so only use it if you set _hash on each node.
     360
     361        Returns:
     362            The SQL string corresponding to `expression`.
     363        """
     364        if cache is not None:
     365            self._cache = cache
     366
     367        self.unsupported_messages = []
     368        sql = self.sql(expression).strip()
     369        self._cache = None
     370
     371        if self.unsupported_level == ErrorLevel.IGNORE:
     372            return sql
     373
     374        if self.unsupported_level == ErrorLevel.WARN:
     375            for msg in self.unsupported_messages:
     376                logger.warning(msg)
     377        elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages:
     378            raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported))
     379
     380        if self.pretty:
     381            sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n")
     382        return sql
     383
     384    def unsupported(self, message: str) -> None:
     385        if self.unsupported_level == ErrorLevel.IMMEDIATE:
     386            raise UnsupportedError(message)
     387        self.unsupported_messages.append(message)
     388
     389    def sep(self, sep: str = " ") -> str:
     390        return f"{sep.strip()}\n" if self.pretty else sep
     391
     392    def seg(self, sql: str, sep: str = " ") -> str:
     393        return f"{self.sep(sep)}{sql}"
     394
     395    def pad_comment(self, comment: str) -> str:
     396        comment = " " + comment if comment[0].strip() else comment
     397        comment = comment + " " if comment[-1].strip() else comment
     398        return comment
     399
     400    def maybe_comment(
     401        self,
     402        sql: str,
     403        expression: t.Optional[exp.Expression] = None,
     404        comments: t.Optional[t.List[str]] = None,
     405    ) -> str:
     406        comments = (
     407            ((expression and expression.comments) if comments is None else comments)  # type: ignore
     408            if self.comments
     409            else None
     410        )
     411
     412        if not comments or isinstance(expression, exp.Binary):
     413            return sql
     414
     415        sep = "\n" if self.pretty else " "
     416        comments_sql = sep.join(
     417            f"/*{self.pad_comment(comment)}*/" for comment in comments if comment
     418        )
     419
     420        if not comments_sql:
     421            return sql
     422
     423        if isinstance(expression, self.WITH_SEPARATED_COMMENTS):
     424            return (
     425                f"{self.sep()}{comments_sql}{sql}"
     426                if sql[0].isspace()
     427                else f"{comments_sql}{self.sep()}{sql}"
     428            )
     429
     430        return f"{sql} {comments_sql}"
     431
     432    def wrap(self, expression: exp.Expression | str) -> str:
     433        this_sql = self.indent(
     434            self.sql(expression)
     435            if isinstance(expression, (exp.Select, exp.Union))
     436            else self.sql(expression, "this"),
     437            level=1,
     438            pad=0,
     439        )
     440        return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"
     441
     442    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
     443        original = self.identify
     444        self.identify = False
     445        result = func(*args, **kwargs)
     446        self.identify = original
     447        return result
     448
     449    def normalize_func(self, name: str) -> str:
     450        if self.normalize_functions == "upper" or self.normalize_functions is True:
     451            return name.upper()
     452        if self.normalize_functions == "lower":
     453            return name.lower()
     454        return name
     455
     456    def indent(
     457        self,
     458        sql: str,
     459        level: int = 0,
     460        pad: t.Optional[int] = None,
     461        skip_first: bool = False,
     462        skip_last: bool = False,
     463    ) -> str:
     464        if not self.pretty:
     465            return sql
     466
     467        pad = self.pad if pad is None else pad
     468        lines = sql.split("\n")
     469
     470        return "\n".join(
     471            line
     472            if (skip_first and i == 0) or (skip_last and i == len(lines) - 1)
     473            else f"{' ' * (level * self._indent + pad)}{line}"
     474            for i, line in enumerate(lines)
     475        )
     476
     477    def sql(
     478        self,
     479        expression: t.Optional[str | exp.Expression],
     480        key: t.Optional[str] = None,
     481        comment: bool = True,
     482    ) -> str:
     483        if not expression:
     484            return ""
     485
     486        if isinstance(expression, str):
     487            return expression
     488
     489        if key:
     490            return self.sql(expression.args.get(key))
     491
     492        if self._cache is not None:
     493            expression_id = hash(expression)
     494
     495            if expression_id in self._cache:
     496                return self._cache[expression_id]
     497
     498        transform = self.TRANSFORMS.get(expression.__class__)
     499
     500        if callable(transform):
     501            sql = transform(self, expression)
     502        elif transform:
     503            sql = transform
     504        elif isinstance(expression, exp.Expression):
     505            exp_handler_name = f"{expression.key}_sql"
     506
     507            if hasattr(self, exp_handler_name):
     508                sql = getattr(self, exp_handler_name)(expression)
     509            elif isinstance(expression, exp.Func):
     510                sql = self.function_fallback_sql(expression)
     511            elif isinstance(expression, exp.Property):
     512                sql = self.property_sql(expression)
     513            else:
     514                raise ValueError(f"Unsupported expression type {expression.__class__.__name__}")
     515        else:
     516            raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}")
     517
     518        sql = self.maybe_comment(sql, expression) if self.comments and comment else sql
     519
     520        if self._cache is not None:
     521            self._cache[expression_id] = sql
     522        return sql
     523
     524    def uncache_sql(self, expression: exp.Uncache) -> str:
     525        table = self.sql(expression, "this")
     526        exists_sql = " IF EXISTS" if expression.args.get("exists") else ""
     527        return f"UNCACHE TABLE{exists_sql} {table}"
     528
     529    def cache_sql(self, expression: exp.Cache) -> str:
     530        lazy = " LAZY" if expression.args.get("lazy") else ""
     531        table = self.sql(expression, "this")
     532        options = expression.args.get("options")
     533        options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else ""
     534        sql = self.sql(expression, "expression")
     535        sql = f" AS{self.sep()}{sql}" if sql else ""
     536        sql = f"CACHE{lazy} TABLE {table}{options}{sql}"
     537        return self.prepend_ctes(expression, sql)
     538
     539    def characterset_sql(self, expression: exp.CharacterSet) -> str:
     540        if isinstance(expression.parent, exp.Cast):
     541            return f"CHAR CHARACTER SET {self.sql(expression, 'this')}"
     542        default = "DEFAULT " if expression.args.get("default") else ""
     543        return f"{default}CHARACTER SET={self.sql(expression, 'this')}"
     544
     545    def column_sql(self, expression: exp.Column) -> str:
     546        return ".".join(
     547            self.sql(part)
     548            for part in (
     549                expression.args.get("catalog"),
     550                expression.args.get("db"),
     551                expression.args.get("table"),
     552                expression.args.get("this"),
     553            )
     554            if part
     555        )
     556
     557    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
     558        this = self.sql(expression, "this")
     559        this = f" {this}" if this else ""
     560        position = self.sql(expression, "position")
     561        return f"{position}{this}"
     562
     563    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
     564        column = self.sql(expression, "this")
     565        kind = self.sql(expression, "kind")
     566        constraints = self.expressions(expression, key="constraints", sep=" ", flat=True)
     567        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
     568        kind = f"{sep}{kind}" if kind else ""
     569        constraints = f" {constraints}" if constraints else ""
     570        position = self.sql(expression, "position")
     571        position = f" {position}" if position else ""
     572
     573        return f"{exists}{column}{kind}{constraints}{position}"
     574
     575    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
     576        this = self.sql(expression, "this")
     577        kind_sql = self.sql(expression, "kind").strip()
     578        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql
     579
     580    def autoincrementcolumnconstraint_sql(self, _) -> str:
     581        return self.token_sql(TokenType.AUTO_INCREMENT)
     582
     583    def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str:
     584        if isinstance(expression.this, list):
     585            this = self.wrap(self.expressions(expression, key="this", flat=True))
     586        else:
     587            this = self.sql(expression, "this")
     588
     589        return f"COMPRESS {this}"
     590
     591    def generatedasidentitycolumnconstraint_sql(
     592        self, expression: exp.GeneratedAsIdentityColumnConstraint
     593    ) -> str:
     594        this = ""
     595        if expression.this is not None:
     596            on_null = "ON NULL " if expression.args.get("on_null") else ""
     597            this = " ALWAYS " if expression.this else f" BY DEFAULT {on_null}"
     598
     599        start = expression.args.get("start")
     600        start = f"START WITH {start}" if start else ""
     601        increment = expression.args.get("increment")
     602        increment = f" INCREMENT BY {increment}" if increment else ""
     603        minvalue = expression.args.get("minvalue")
     604        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
     605        maxvalue = expression.args.get("maxvalue")
     606        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
     607        cycle = expression.args.get("cycle")
     608        cycle_sql = ""
     609
     610        if cycle is not None:
     611            cycle_sql = f"{' NO' if not cycle else ''} CYCLE"
     612            cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql
     613
     614        sequence_opts = ""
     615        if start or increment or cycle_sql:
     616            sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}"
     617            sequence_opts = f" ({sequence_opts.strip()})"
     618
     619        expr = self.sql(expression, "expression")
     620        expr = f"({expr})" if expr else "IDENTITY"
     621
     622        return f"GENERATED{this}AS {expr}{sequence_opts}"
     623
     624    def notnullcolumnconstraint_sql(self, expression: exp.NotNullColumnConstraint) -> str:
     625        return f"{'' if expression.args.get('allow_null') else 'NOT '}NULL"
     626
     627    def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str:
     628        desc = expression.args.get("desc")
     629        if desc is not None:
     630            return f"PRIMARY KEY{' DESC' if desc else ' ASC'}"
     631        return f"PRIMARY KEY"
     632
     633    def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str:
     634        this = self.sql(expression, "this")
     635        this = f" {this}" if this else ""
     636        return f"UNIQUE{this}"
     637
     638    def createable_sql(
     639        self, expression: exp.Create, locations: dict[exp.Properties.Location, list[exp.Property]]
     640    ) -> str:
     641        return self.sql(expression, "this")
     642
     643    def create_sql(self, expression: exp.Create) -> str:
     644        kind = self.sql(expression, "kind").upper()
     645        properties = expression.args.get("properties")
     646        properties_locs = self.locate_properties(properties) if properties else {}
     647
     648        this = self.createable_sql(expression, properties_locs)
     649
     650        properties_sql = ""
     651        if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get(
     652            exp.Properties.Location.POST_WITH
     653        ):
     654            properties_sql = self.sql(
     655                exp.Properties(
     656                    expressions=[
     657                        *properties_locs[exp.Properties.Location.POST_SCHEMA],
     658                        *properties_locs[exp.Properties.Location.POST_WITH],
     659                    ]
     660                )
     661            )
     662
     663        begin = " BEGIN" if expression.args.get("begin") else ""
     664        expression_sql = self.sql(expression, "expression")
     665        if expression_sql:
     666            expression_sql = f"{begin}{self.sep()}{expression_sql}"
     667
     668            if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return):
     669                if properties_locs.get(exp.Properties.Location.POST_ALIAS):
     670                    postalias_props_sql = self.properties(
     671                        exp.Properties(
     672                            expressions=properties_locs[exp.Properties.Location.POST_ALIAS]
     673                        ),
     674                        wrapped=False,
     675                    )
     676                    expression_sql = f" AS {postalias_props_sql}{expression_sql}"
     677                else:
     678                    expression_sql = f" AS{expression_sql}"
     679
     680        postindex_props_sql = ""
     681        if properties_locs.get(exp.Properties.Location.POST_INDEX):
     682            postindex_props_sql = self.properties(
     683                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]),
     684                wrapped=False,
     685                prefix=" ",
     686            )
     687
     688        indexes = self.expressions(expression, key="indexes", indent=False, sep=" ")
     689        indexes = f" {indexes}" if indexes else ""
     690        index_sql = indexes + postindex_props_sql
     691
     692        replace = " OR REPLACE" if expression.args.get("replace") else ""
     693        unique = " UNIQUE" if expression.args.get("unique") else ""
     694
     695        postcreate_props_sql = ""
     696        if properties_locs.get(exp.Properties.Location.POST_CREATE):
     697            postcreate_props_sql = self.properties(
     698                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]),
     699                sep=" ",
     700                prefix=" ",
     701                wrapped=False,
     702            )
     703
     704        modifiers = "".join((replace, unique, postcreate_props_sql))
     705
     706        postexpression_props_sql = ""
     707        if properties_locs.get(exp.Properties.Location.POST_EXPRESSION):
     708            postexpression_props_sql = self.properties(
     709                exp.Properties(
     710                    expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION]
     711                ),
     712                sep=" ",
     713                prefix=" ",
     714                wrapped=False,
     715            )
     716
     717        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
     718        no_schema_binding = (
     719            " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else ""
     720        )
     721
     722        clone = self.sql(expression, "clone")
     723        clone = f" {clone}" if clone else ""
     724
     725        expression_sql = f"CREATE{modifiers} {kind}{exists_sql} {this}{properties_sql}{expression_sql}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}"
     726        return self.prepend_ctes(expression, expression_sql)
     727
     728    def clone_sql(self, expression: exp.Clone) -> str:
     729        this = self.sql(expression, "this")
     730        when = self.sql(expression, "when")
     731
     732        if when:
     733            kind = self.sql(expression, "kind")
     734            expr = self.sql(expression, "expression")
     735            return f"CLONE {this} {when} ({kind} => {expr})"
     736
     737        return f"CLONE {this}"
     738
     739    def describe_sql(self, expression: exp.Describe) -> str:
     740        return f"DESCRIBE {self.sql(expression, 'this')}"
     741
     742    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
     743        with_ = self.sql(expression, "with")
     744        if with_:
     745            sql = f"{with_}{self.sep()}{sql}"
     746        return sql
     747
     748    def with_sql(self, expression: exp.With) -> str:
     749        sql = self.expressions(expression, flat=True)
     750        recursive = "RECURSIVE " if expression.args.get("recursive") else ""
     751
     752        return f"WITH {recursive}{sql}"
     753
     754    def cte_sql(self, expression: exp.CTE) -> str:
     755        alias = self.sql(expression, "alias")
     756        return f"{alias} AS {self.wrap(expression)}"
     757
     758    def tablealias_sql(self, expression: exp.TableAlias) -> str:
     759        alias = self.sql(expression, "this")
     760        columns = self.expressions(expression, key="columns", flat=True)
     761        columns = f"({columns})" if columns else ""
     762        return f"{alias}{columns}"
     763
     764    def bitstring_sql(self, expression: exp.BitString) -> str:
     765        this = self.sql(expression, "this")
     766        if self.BIT_START:
     767            return f"{self.BIT_START}{this}{self.BIT_END}"
     768        return f"{int(this, 2)}"
     769
     770    def hexstring_sql(self, expression: exp.HexString) -> str:
     771        this = self.sql(expression, "this")
     772        if self.HEX_START:
     773            return f"{self.HEX_START}{this}{self.HEX_END}"
     774        return f"{int(this, 16)}"
     775
     776    def bytestring_sql(self, expression: exp.ByteString) -> str:
     777        this = self.sql(expression, "this")
     778        if self.BYTE_START:
     779            return f"{self.BYTE_START}{this}{self.BYTE_END}"
     780        return this
     781
     782    def rawstring_sql(self, expression: exp.RawString) -> str:
     783        string = expression.this
     784        if self.RAW_START:
     785            return f"{self.RAW_START}{self.escape_str(expression.this)}{self.RAW_END}"
     786        string = self.escape_str(string.replace("\\", "\\\\"))
     787        return f"{self.QUOTE_START}{string}{self.QUOTE_END}"
     788
     789    def datatypesize_sql(self, expression: exp.DataTypeSize) -> str:
     790        this = self.sql(expression, "this")
     791        specifier = self.sql(expression, "expression")
     792        specifier = f" {specifier}" if specifier else ""
     793        return f"{this}{specifier}"
     794
     795    def datatype_sql(self, expression: exp.DataType) -> str:
     796        type_value = expression.this
     797        type_sql = self.TYPE_MAPPING.get(type_value, type_value.value)
     798        nested = ""
     799        interior = self.expressions(expression, flat=True)
     800        values = ""
     801        if interior:
     802            if expression.args.get("nested"):
     803                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
     804                if expression.args.get("values") is not None:
     805                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
     806                    values = self.expressions(expression, key="values", flat=True)
     807                    values = f"{delimiters[0]}{values}{delimiters[1]}"
     808            else:
     809                nested = f"({interior})"
     810
     811        return f"{type_sql}{nested}{values}"
     812
     813    def directory_sql(self, expression: exp.Directory) -> str:
     814        local = "LOCAL " if expression.args.get("local") else ""
     815        row_format = self.sql(expression, "row_format")
     816        row_format = f" {row_format}" if row_format else ""
     817        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"
     818
     819    def delete_sql(self, expression: exp.Delete) -> str:
     820        this = self.sql(expression, "this")
     821        this = f" FROM {this}" if this else ""
     822        using_sql = (
     823            f" USING {self.expressions(expression, key='using', sep=', USING ')}"
     824            if expression.args.get("using")
     825            else ""
     826        )
     827        where_sql = self.sql(expression, "where")
     828        returning = self.sql(expression, "returning")
     829        limit = self.sql(expression, "limit")
     830        sql = f"DELETE{this}{using_sql}{where_sql}{returning}{limit}"
     831        return self.prepend_ctes(expression, sql)
     832
     833    def drop_sql(self, expression: exp.Drop) -> str:
     834        this = self.sql(expression, "this")
     835        kind = expression.args["kind"]
     836        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
     837        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
     838        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
     839        cascade = " CASCADE" if expression.args.get("cascade") else ""
     840        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
     841        purge = " PURGE" if expression.args.get("purge") else ""
     842        return (
     843            f"DROP{temporary}{materialized} {kind}{exists_sql}{this}{cascade}{constraints}{purge}"
     844        )
     845
     846    def except_sql(self, expression: exp.Except) -> str:
     847        return self.prepend_ctes(
     848            expression,
     849            self.set_operation(expression, self.except_op(expression)),
     850        )
     851
     852    def except_op(self, expression: exp.Except) -> str:
     853        return f"EXCEPT{'' if expression.args.get('distinct') else ' ALL'}"
     854
     855    def fetch_sql(self, expression: exp.Fetch) -> str:
     856        direction = expression.args.get("direction")
     857        direction = f" {direction.upper()}" if direction else ""
     858        count = expression.args.get("count")
     859        count = f" {count}" if count else ""
     860        if expression.args.get("percent"):
     861            count = f"{count} PERCENT"
     862        with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY"
     863        return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}"
     864
     865    def filter_sql(self, expression: exp.Filter) -> str:
     866        this = self.sql(expression, "this")
     867        where = self.sql(expression, "expression")[1:]  # where has a leading space
     868        return f"{this} FILTER({where})"
     869
     870    def hint_sql(self, expression: exp.Hint) -> str:
     871        if self.sql(expression, "this"):
     872            self.unsupported("Hints are not supported")
     873        return ""
     874
     875    def index_sql(self, expression: exp.Index) -> str:
     876        unique = "UNIQUE " if expression.args.get("unique") else ""
     877        primary = "PRIMARY " if expression.args.get("primary") else ""
     878        amp = "AMP " if expression.args.get("amp") else ""
     879        name = f"{expression.name} " if expression.name else ""
     880        table = self.sql(expression, "table")
     881        table = f"{self.INDEX_ON} {table} " if table else ""
     882        using = self.sql(expression, "using")
     883        using = f"USING {using} " if using else ""
     884        index = "INDEX " if not table else ""
     885        columns = self.expressions(expression, key="columns", flat=True)
     886        columns = f"({columns})" if columns else ""
     887        partition_by = self.expressions(expression, key="partition_by", flat=True)
     888        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
     889        return f"{unique}{primary}{amp}{index}{name}{table}{using}{columns}{partition_by}"
     890
     891    def identifier_sql(self, expression: exp.Identifier) -> str:
     892        text = expression.name
     893        lower = text.lower()
     894        text = lower if self.normalize and not expression.quoted else text
     895        text = text.replace(self.IDENTIFIER_END, self._escaped_identifier_end)
     896        if (
     897            expression.quoted
     898            or self.can_identify(text, self.identify)
     899            or lower in self.RESERVED_KEYWORDS
     900            or (not self.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
     901        ):
     902            text = f"{self.IDENTIFIER_START}{text}{self.IDENTIFIER_END}"
     903        return text
     904
     905    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
     906        input_format = self.sql(expression, "input_format")
     907        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
     908        output_format = self.sql(expression, "output_format")
     909        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
     910        return self.sep().join((input_format, output_format))
     911
     912    def national_sql(self, expression: exp.National, prefix: str = "N") -> str:
     913        string = self.sql(exp.Literal.string(expression.name))
     914        return f"{prefix}{string}"
     915
     916    def partition_sql(self, expression: exp.Partition) -> str:
     917        return f"PARTITION({self.expressions(expression, flat=True)})"
     918
     919    def properties_sql(self, expression: exp.Properties) -> str:
     920        root_properties = []
     921        with_properties = []
     922
     923        for p in expression.expressions:
     924            p_loc = self.PROPERTIES_LOCATION[p.__class__]
     925            if p_loc == exp.Properties.Location.POST_WITH:
     926                with_properties.append(p)
     927            elif p_loc == exp.Properties.Location.POST_SCHEMA:
     928                root_properties.append(p)
     929
     930        return self.root_properties(
     931            exp.Properties(expressions=root_properties)
     932        ) + self.with_properties(exp.Properties(expressions=with_properties))
     933
     934    def root_properties(self, properties: exp.Properties) -> str:
     935        if properties.expressions:
     936            return self.sep() + self.expressions(properties, indent=False, sep=" ")
     937        return ""
     938
     939    def properties(
     940        self,
     941        properties: exp.Properties,
     942        prefix: str = "",
     943        sep: str = ", ",
     944        suffix: str = "",
     945        wrapped: bool = True,
     946    ) -> str:
     947        if properties.expressions:
     948            expressions = self.expressions(properties, sep=sep, indent=False)
     949            expressions = self.wrap(expressions) if wrapped else expressions
     950            return f"{prefix}{' ' if prefix and prefix != ' ' else ''}{expressions}{suffix}"
     951        return ""
     952
     953    def with_properties(self, properties: exp.Properties) -> str:
     954        return self.properties(properties, prefix=self.seg("WITH"))
     955
     956    def locate_properties(
     957        self, properties: exp.Properties
     958    ) -> t.Dict[exp.Properties.Location, list[exp.Property]]:
     959        properties_locs: t.Dict[exp.Properties.Location, list[exp.Property]] = {
     960            key: [] for key in exp.Properties.Location
     961        }
     962
     963        for p in properties.expressions:
     964            p_loc = self.PROPERTIES_LOCATION[p.__class__]
     965            if p_loc == exp.Properties.Location.POST_NAME:
     966                properties_locs[exp.Properties.Location.POST_NAME].append(p)
     967            elif p_loc == exp.Properties.Location.POST_INDEX:
     968                properties_locs[exp.Properties.Location.POST_INDEX].append(p)
     969            elif p_loc == exp.Properties.Location.POST_SCHEMA:
     970                properties_locs[exp.Properties.Location.POST_SCHEMA].append(p)
     971            elif p_loc == exp.Properties.Location.POST_WITH:
     972                properties_locs[exp.Properties.Location.POST_WITH].append(p)
     973            elif p_loc == exp.Properties.Location.POST_CREATE:
     974                properties_locs[exp.Properties.Location.POST_CREATE].append(p)
     975            elif p_loc == exp.Properties.Location.POST_ALIAS:
     976                properties_locs[exp.Properties.Location.POST_ALIAS].append(p)
     977            elif p_loc == exp.Properties.Location.POST_EXPRESSION:
     978                properties_locs[exp.Properties.Location.POST_EXPRESSION].append(p)
     979            elif p_loc == exp.Properties.Location.UNSUPPORTED:
     980                self.unsupported(f"Unsupported property {p.key}")
     981
     982        return properties_locs
     983
     984    def property_sql(self, expression: exp.Property) -> str:
     985        property_cls = expression.__class__
     986        if property_cls == exp.Property:
     987            return f"{expression.name}={self.sql(expression, 'value')}"
     988
     989        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
     990        if not property_name:
     991            self.unsupported(f"Unsupported property {expression.key}")
     992
     993        return f"{property_name}={self.sql(expression, 'this')}"
     994
     995    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
     996        options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
     997        options = f" {options}" if options else ""
     998        return f"LIKE {self.sql(expression, 'this')}{options}"
     999
    1000    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1001        no = "NO " if expression.args.get("no") else ""
    1002        protection = " PROTECTION" if expression.args.get("protection") else ""
    1003        return f"{no}FALLBACK{protection}"
    1004
    1005    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1006        no = "NO " if expression.args.get("no") else ""
    1007        local = expression.args.get("local")
    1008        local = f"{local} " if local else ""
    1009        dual = "DUAL " if expression.args.get("dual") else ""
    1010        before = "BEFORE " if expression.args.get("before") else ""
    1011        after = "AFTER " if expression.args.get("after") else ""
    1012        return f"{no}{local}{dual}{before}{after}JOURNAL"
    1013
    1014    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1015        freespace = self.sql(expression, "this")
    1016        percent = " PERCENT" if expression.args.get("percent") else ""
    1017        return f"FREESPACE={freespace}{percent}"
    1018
    1019    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1020        if expression.args.get("default"):
    1021            property = "DEFAULT"
    1022        elif expression.args.get("on"):
    1023            property = "ON"
    1024        else:
    1025            property = "OFF"
    1026        return f"CHECKSUM={property}"
    1027
    1028    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1029        if expression.args.get("no"):
    1030            return "NO MERGEBLOCKRATIO"
    1031        if expression.args.get("default"):
    1032            return "DEFAULT MERGEBLOCKRATIO"
    1033
    1034        percent = " PERCENT" if expression.args.get("percent") else ""
    1035        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"
    1036
    1037    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1038        default = expression.args.get("default")
    1039        minimum = expression.args.get("minimum")
    1040        maximum = expression.args.get("maximum")
    1041        if default or minimum or maximum:
    1042            if default:
    1043                prop = "DEFAULT"
    1044            elif minimum:
    1045                prop = "MINIMUM"
    1046            else:
    1047                prop = "MAXIMUM"
    1048            return f"{prop} DATABLOCKSIZE"
    1049        units = expression.args.get("units")
    1050        units = f" {units}" if units else ""
    1051        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"
    1052
    1053    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1054        autotemp = expression.args.get("autotemp")
    1055        always = expression.args.get("always")
    1056        default = expression.args.get("default")
    1057        manual = expression.args.get("manual")
    1058        never = expression.args.get("never")
    1059
    1060        if autotemp is not None:
    1061            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1062        elif always:
    1063            prop = "ALWAYS"
    1064        elif default:
    1065            prop = "DEFAULT"
    1066        elif manual:
    1067            prop = "MANUAL"
    1068        elif never:
    1069            prop = "NEVER"
    1070        return f"BLOCKCOMPRESSION={prop}"
    1071
    1072    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1073        no = expression.args.get("no")
    1074        no = " NO" if no else ""
    1075        concurrent = expression.args.get("concurrent")
    1076        concurrent = " CONCURRENT" if concurrent else ""
    1077
    1078        for_ = ""
    1079        if expression.args.get("for_all"):
    1080            for_ = " FOR ALL"
    1081        elif expression.args.get("for_insert"):
    1082            for_ = " FOR INSERT"
    1083        elif expression.args.get("for_none"):
    1084            for_ = " FOR NONE"
    1085        return f"WITH{no}{concurrent} ISOLATED LOADING{for_}"
    1086
    1087    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1088        kind = expression.args.get("kind")
    1089        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1090        for_or_in = expression.args.get("for_or_in")
    1091        lock_type = expression.args.get("lock_type")
    1092        override = " OVERRIDE" if expression.args.get("override") else ""
    1093        return f"LOCKING {kind}{this} {for_or_in} {lock_type}{override}"
    1094
    1095    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1096        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1097        statistics = expression.args.get("statistics")
    1098        statistics_sql = ""
    1099        if statistics is not None:
    1100            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1101        return f"{data_sql}{statistics_sql}"
    1102
    1103    def insert_sql(self, expression: exp.Insert) -> str:
    1104        overwrite = expression.args.get("overwrite")
    1105
    1106        if isinstance(expression.this, exp.Directory):
    1107            this = " OVERWRITE" if overwrite else " INTO"
    1108        else:
    1109            this = " OVERWRITE TABLE" if overwrite else " INTO"
    1110
    1111        alternative = expression.args.get("alternative")
    1112        alternative = f" OR {alternative}" if alternative else ""
    1113        this = f"{this} {self.sql(expression, 'this')}"
    1114
    1115        exists = " IF EXISTS" if expression.args.get("exists") else ""
    1116        partition_sql = (
    1117            f" {self.sql(expression, 'partition')}" if expression.args.get("partition") else ""
    1118        )
    1119        where = self.sql(expression, "where")
    1120        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
    1121        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
    1122        conflict = self.sql(expression, "conflict")
    1123        returning = self.sql(expression, "returning")
    1124        sql = f"INSERT{alternative}{this}{exists}{partition_sql}{where}{expression_sql}{conflict}{returning}"
    1125        return self.prepend_ctes(expression, sql)
    1126
    1127    def intersect_sql(self, expression: exp.Intersect) -> str:
    1128        return self.prepend_ctes(
    1129            expression,
    1130            self.set_operation(expression, self.intersect_op(expression)),
    1131        )
    1132
    1133    def intersect_op(self, expression: exp.Intersect) -> str:
    1134        return f"INTERSECT{'' if expression.args.get('distinct') else ' ALL'}"
    1135
    1136    def introducer_sql(self, expression: exp.Introducer) -> str:
    1137        return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}"
    1138
    1139    def pseudotype_sql(self, expression: exp.PseudoType) -> str:
    1140        return expression.name.upper()
    1141
    1142    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1143        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1144        constraint = self.sql(expression, "constraint")
    1145        if constraint:
    1146            constraint = f"ON CONSTRAINT {constraint}"
    1147        key = self.expressions(expression, key="key", flat=True)
    1148        do = "" if expression.args.get("duplicate") else " DO "
    1149        nothing = "NOTHING" if expression.args.get("nothing") else ""
    1150        expressions = self.expressions(expression, flat=True)
    1151        if expressions:
    1152            expressions = f"UPDATE SET {expressions}"
    1153        return f"{self.seg(conflict)} {constraint}{key}{do}{nothing}{expressions}"
    1154
    1155    def returning_sql(self, expression: exp.Returning) -> str:
    1156        return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}"
    1157
    1158    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1159        fields = expression.args.get("fields")
    1160        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1161        escaped = expression.args.get("escaped")
    1162        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1163        items = expression.args.get("collection_items")
    1164        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1165        keys = expression.args.get("map_keys")
    1166        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1167        lines = expression.args.get("lines")
    1168        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1169        null = expression.args.get("null")
    1170        null = f" NULL DEFINED AS {null}" if null else ""
    1171        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"
    1172
    1173    def withtablehint_sql(self, expression: exp.WithTableHint) -> str:
    1174        return f"WITH ({self.expressions(expression, flat=True)})"
    1175
    1176    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1177        this = f"{self.sql(expression, 'this')} INDEX"
    1178        target = self.sql(expression, "target")
    1179        target = f" FOR {target}" if target else ""
    1180        return f"{this}{target} ({self.expressions(expression, flat=True)})"
    1181
    1182    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1183        table = ".".join(
    1184            part
    1185            for part in [
    1186                self.sql(expression, "catalog"),
    1187                self.sql(expression, "db"),
    1188                self.sql(expression, "this"),
    1189            ]
    1190            if part
    1191        )
    1192
    1193        alias = self.sql(expression, "alias")
    1194        alias = f"{sep}{alias}" if alias else ""
    1195        hints = self.expressions(expression, key="hints", sep=" ")
    1196        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
    1197        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    1198        pivots = f" {pivots}" if pivots else ""
    1199        joins = self.expressions(expression, key="joins", sep="")
    1200        laterals = self.expressions(expression, key="laterals", sep="")
    1201        system_time = expression.args.get("system_time")
    1202        system_time = f" {self.sql(expression, 'system_time')}" if system_time else ""
    1203
    1204        return f"{table}{system_time}{alias}{hints}{pivots}{joins}{laterals}"
    1205
    1206    def tablesample_sql(
    1207        self, expression: exp.TableSample, seed_prefix: str = "SEED", sep=" AS "
    1208    ) -> str:
    1209        if self.ALIAS_POST_TABLESAMPLE and expression.this.alias:
    1210            table = expression.this.copy()
    1211            table.set("alias", None)
    1212            this = self.sql(table)
    1213            alias = f"{sep}{self.sql(expression.this, 'alias')}"
    1214        else:
    1215            this = self.sql(expression, "this")
    1216            alias = ""
    1217        method = self.sql(expression, "method")
    1218        method = f"{method.upper()} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    1219        numerator = self.sql(expression, "bucket_numerator")
    1220        denominator = self.sql(expression, "bucket_denominator")
    1221        field = self.sql(expression, "bucket_field")
    1222        field = f" ON {field}" if field else ""
    1223        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    1224        percent = self.sql(expression, "percent")
    1225        percent = f"{percent} PERCENT" if percent else ""
    1226        rows = self.sql(expression, "rows")
    1227        rows = f"{rows} ROWS" if rows else ""
    1228        size = self.sql(expression, "size")
    1229        if size and self.TABLESAMPLE_SIZE_IS_PERCENT:
    1230            size = f"{size} PERCENT"
    1231        seed = self.sql(expression, "seed")
    1232        seed = f" {seed_prefix} ({seed})" if seed else ""
    1233        kind = expression.args.get("kind", "TABLESAMPLE")
    1234        return f"{this} {kind} {method}({bucket}{percent}{rows}{size}){seed}{alias}"
    1235
    1236    def pivot_sql(self, expression: exp.Pivot) -> str:
    1237        expressions = self.expressions(expression, flat=True)
    1238
    1239        if expression.this:
    1240            this = self.sql(expression, "this")
    1241            on = f"{self.seg('ON')} {expressions}"
    1242            using = self.expressions(expression, key="using", flat=True)
    1243            using = f"{self.seg('USING')} {using}" if using else ""
    1244            group = self.sql(expression, "group")
    1245            return f"PIVOT {this}{on}{using}{group}"
    1246
    1247        alias = self.sql(expression, "alias")
    1248        alias = f" AS {alias}" if alias else ""
    1249        unpivot = expression.args.get("unpivot")
    1250        direction = "UNPIVOT" if unpivot else "PIVOT"
    1251        field = self.sql(expression, "field")
    1252        return f"{direction}({expressions} FOR {field}){alias}"
    1253
    1254    def tuple_sql(self, expression: exp.Tuple) -> str:
    1255        return f"({self.expressions(expression, flat=True)})"
    1256
    1257    def update_sql(self, expression: exp.Update) -> str:
    1258        this = self.sql(expression, "this")
    1259        set_sql = self.expressions(expression, flat=True)
    1260        from_sql = self.sql(expression, "from")
    1261        where_sql = self.sql(expression, "where")
    1262        returning = self.sql(expression, "returning")
    1263        limit = self.sql(expression, "limit")
    1264        sql = f"UPDATE {this} SET {set_sql}{from_sql}{where_sql}{returning}{limit}"
    1265        return self.prepend_ctes(expression, sql)
    1266
    1267    def values_sql(self, expression: exp.Values) -> str:
    1268        args = self.expressions(expression)
    1269        alias = self.sql(expression, "alias")
    1270        values = f"VALUES{self.seg('')}{args}"
    1271        values = (
    1272            f"({values})"
    1273            if self.WRAP_DERIVED_VALUES and (alias or isinstance(expression.parent, exp.From))
    1274            else values
    1275        )
    1276        return f"{values} AS {alias}" if alias else values
    1277
    1278    def var_sql(self, expression: exp.Var) -> str:
    1279        return self.sql(expression, "this")
    1280
    1281    def into_sql(self, expression: exp.Into) -> str:
    1282        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    1283        unlogged = " UNLOGGED" if expression.args.get("unlogged") else ""
    1284        return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"
    1285
    1286    def from_sql(self, expression: exp.From) -> str:
    1287        return f"{self.seg('FROM')} {self.sql(expression, 'this')}"
    1288
    1289    def group_sql(self, expression: exp.Group) -> str:
    1290        group_by = self.op_expressions("GROUP BY", expression)
    1291        grouping_sets = self.expressions(expression, key="grouping_sets", indent=False)
    1292        grouping_sets = (
    1293            f"{self.seg('GROUPING SETS')} {self.wrap(grouping_sets)}" if grouping_sets else ""
    1294        )
    1295
    1296        cube = expression.args.get("cube", [])
    1297        if seq_get(cube, 0) is True:
    1298            return f"{group_by}{self.seg('WITH CUBE')}"
    1299        else:
    1300            cube_sql = self.expressions(expression, key="cube", indent=False)
    1301            cube_sql = f"{self.seg('CUBE')} {self.wrap(cube_sql)}" if cube_sql else ""
    1302
    1303        rollup = expression.args.get("rollup", [])
    1304        if seq_get(rollup, 0) is True:
    1305            return f"{group_by}{self.seg('WITH ROLLUP')}"
    1306        else:
    1307            rollup_sql = self.expressions(expression, key="rollup", indent=False)
    1308            rollup_sql = f"{self.seg('ROLLUP')} {self.wrap(rollup_sql)}" if rollup_sql else ""
    1309
    1310        groupings = csv(
    1311            grouping_sets,
    1312            cube_sql,
    1313            rollup_sql,
    1314            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    1315            sep=self.GROUPINGS_SEP,
    1316        )
    1317
    1318        if expression.args.get("expressions") and groupings:
    1319            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    1320
    1321        return f"{group_by}{groupings}"
    1322
    1323    def having_sql(self, expression: exp.Having) -> str:
    1324        this = self.indent(self.sql(expression, "this"))
    1325        return f"{self.seg('HAVING')}{self.sep()}{this}"
    1326
    1327    def join_sql(self, expression: exp.Join) -> str:
    1328        op_sql = " ".join(
    1329            op
    1330            for op in (
    1331                expression.method,
    1332                "GLOBAL" if expression.args.get("global") else None,
    1333                expression.side,
    1334                expression.kind,
    1335                expression.hint if self.JOIN_HINTS else None,
    1336            )
    1337            if op
    1338        )
    1339        on_sql = self.sql(expression, "on")
    1340        using = expression.args.get("using")
    1341
    1342        if not on_sql and using:
    1343            on_sql = csv(*(self.sql(column) for column in using))
    1344
    1345        this_sql = self.sql(expression, "this")
    1346
    1347        if on_sql:
    1348            on_sql = self.indent(on_sql, skip_first=True)
    1349            space = self.seg(" " * self.pad) if self.pretty else " "
    1350            if using:
    1351                on_sql = f"{space}USING ({on_sql})"
    1352            else:
    1353                on_sql = f"{space}ON {on_sql}"
    1354        elif not op_sql:
    1355            return f", {this_sql}"
    1356
    1357        op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    1358        return f"{self.seg(op_sql)} {this_sql}{on_sql}"
    1359
    1360    def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->") -> str:
    1361        args = self.expressions(expression, flat=True)
    1362        args = f"({args})" if len(args.split(",")) > 1 else args
    1363        return f"{args} {arrow_sep} {self.sql(expression, 'this')}"
    1364
    1365    def lateral_sql(self, expression: exp.Lateral) -> str:
    1366        this = self.sql(expression, "this")
    1367
    1368        if isinstance(expression.this, exp.Subquery):
    1369            return f"LATERAL {this}"
    1370
    1371        if expression.args.get("view"):
    1372            alias = expression.args["alias"]
    1373            columns = self.expressions(alias, key="columns", flat=True)
    1374            table = f" {alias.name}" if alias.name else ""
    1375            columns = f" AS {columns}" if columns else ""
    1376            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    1377            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    1378
    1379        alias = self.sql(expression, "alias")
    1380        alias = f" AS {alias}" if alias else ""
    1381        return f"LATERAL {this}{alias}"
    1382
    1383    def limit_sql(self, expression: exp.Limit) -> str:
    1384        this = self.sql(expression, "this")
    1385        args = ", ".join(
    1386            sql
    1387            for sql in (
    1388                self.sql(expression, "offset"),
    1389                self.sql(expression, "expression"),
    1390            )
    1391            if sql
    1392        )
    1393        return f"{this}{self.seg('LIMIT')} {args}"
    1394
    1395    def offset_sql(self, expression: exp.Offset) -> str:
    1396        this = self.sql(expression, "this")
    1397        return f"{this}{self.seg('OFFSET')} {self.sql(expression, 'expression')}"
    1398
    1399    def setitem_sql(self, expression: exp.SetItem) -> str:
    1400        kind = self.sql(expression, "kind")
    1401        kind = f"{kind} " if kind else ""
    1402        this = self.sql(expression, "this")
    1403        expressions = self.expressions(expression)
    1404        collate = self.sql(expression, "collate")
    1405        collate = f" COLLATE {collate}" if collate else ""
    1406        global_ = "GLOBAL " if expression.args.get("global") else ""
    1407        return f"{global_}{kind}{this}{expressions}{collate}"
    1408
    1409    def set_sql(self, expression: exp.Set) -> str:
    1410        expressions = (
    1411            f" {self.expressions(expression, flat=True)}" if expression.expressions else ""
    1412        )
    1413        tag = " TAG" if expression.args.get("tag") else ""
    1414        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"
    1415
    1416    def pragma_sql(self, expression: exp.Pragma) -> str:
    1417        return f"PRAGMA {self.sql(expression, 'this')}"
    1418
    1419    def lock_sql(self, expression: exp.Lock) -> str:
    1420        if not self.LOCKING_READS_SUPPORTED:
    1421            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    1422            return ""
    1423
    1424        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    1425        expressions = self.expressions(expression, flat=True)
    1426        expressions = f" OF {expressions}" if expressions else ""
    1427        wait = expression.args.get("wait")
    1428
    1429        if wait is not None:
    1430            if isinstance(wait, exp.Literal):
    1431                wait = f" WAIT {self.sql(wait)}"
    1432            else:
    1433                wait = " NOWAIT" if wait else " SKIP LOCKED"
    1434
    1435        return f"{lock_type}{expressions}{wait or ''}"
    1436
    1437    def literal_sql(self, expression: exp.Literal) -> str:
    1438        text = expression.this or ""
    1439        if expression.is_string:
    1440            text = f"{self.QUOTE_START}{self.escape_str(text)}{self.QUOTE_END}"
    1441        return text
    1442
    1443    def escape_str(self, text: str) -> str:
    1444        text = text.replace(self.QUOTE_END, self._escaped_quote_end)
    1445        if self.pretty:
    1446            text = text.replace("\n", self.SENTINEL_LINE_BREAK)
    1447        return text
    1448
    1449    def loaddata_sql(self, expression: exp.LoadData) -> str:
    1450        local = " LOCAL" if expression.args.get("local") else ""
    1451        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    1452        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    1453        this = f" INTO TABLE {self.sql(expression, 'this')}"
    1454        partition = self.sql(expression, "partition")
    1455        partition = f" {partition}" if partition else ""
    1456        input_format = self.sql(expression, "input_format")
    1457        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    1458        serde = self.sql(expression, "serde")
    1459        serde = f" SERDE {serde}" if serde else ""
    1460        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"
    1461
    1462    def null_sql(self, *_) -> str:
    1463        return "NULL"
    1464
    1465    def boolean_sql(self, expression: exp.Boolean) -> str:
    1466        return "TRUE" if expression.this else "FALSE"
    1467
    1468    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    1469        this = self.sql(expression, "this")
    1470        this = f"{this} " if this else this
    1471        return self.op_expressions(f"{this}ORDER BY", expression, flat=this or flat)  # type: ignore
    1472
    1473    def cluster_sql(self, expression: exp.Cluster) -> str:
    1474        return self.op_expressions("CLUSTER BY", expression)
    1475
    1476    def distribute_sql(self, expression: exp.Distribute) -> str:
    1477        return self.op_expressions("DISTRIBUTE BY", expression)
    1478
    1479    def sort_sql(self, expression: exp.Sort) -> str:
    1480        return self.op_expressions("SORT BY", expression)
    1481
    1482    def ordered_sql(self, expression: exp.Ordered) -> str:
    1483        desc = expression.args.get("desc")
    1484        asc = not desc
    1485
    1486        nulls_first = expression.args.get("nulls_first")
    1487        nulls_last = not nulls_first
    1488        nulls_are_large = self.NULL_ORDERING == "nulls_are_large"
    1489        nulls_are_small = self.NULL_ORDERING == "nulls_are_small"
    1490        nulls_are_last = self.NULL_ORDERING == "nulls_are_last"
    1491
    1492        sort_order = " DESC" if desc else ""
    1493        nulls_sort_change = ""
    1494        if nulls_first and (
    1495            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
    1496        ):
    1497            nulls_sort_change = " NULLS FIRST"
    1498        elif (
    1499            nulls_last
    1500            and ((asc and nulls_are_small) or (desc and nulls_are_large))
    1501            and not nulls_are_last
    1502        ):
    1503            nulls_sort_change = " NULLS LAST"
    1504
    1505        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
    1506            self.unsupported(
    1507                "Sorting in an ORDER BY on NULLS FIRST/NULLS LAST is not supported by this dialect"
    1508            )
    1509            nulls_sort_change = ""
    1510
    1511        return f"{self.sql(expression, 'this')}{sort_order}{nulls_sort_change}"
    1512
    1513    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    1514        partition = self.partition_by_sql(expression)
    1515        order = self.sql(expression, "order")
    1516        measures = self.expressions(expression, key="measures")
    1517        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    1518        rows = self.sql(expression, "rows")
    1519        rows = self.seg(rows) if rows else ""
    1520        after = self.sql(expression, "after")
    1521        after = self.seg(after) if after else ""
    1522        pattern = self.sql(expression, "pattern")
    1523        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    1524        definition_sqls = [
    1525            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    1526            for definition in expression.args.get("define", [])
    1527        ]
    1528        definitions = self.expressions(sqls=definition_sqls)
    1529        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    1530        body = "".join(
    1531            (
    1532                partition,
    1533                order,
    1534                measures,
    1535                rows,
    1536                after,
    1537                pattern,
    1538                define,
    1539            )
    1540        )
    1541        alias = self.sql(expression, "alias")
    1542        alias = f" {alias}" if alias else ""
    1543        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"
    1544
    1545    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    1546        limit: t.Optional[exp.Fetch | exp.Limit] = expression.args.get("limit")
    1547
    1548        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    1549            limit = exp.Limit(expression=limit.args.get("count"))
    1550        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    1551            limit = exp.Fetch(direction="FIRST", count=limit.expression)
    1552
    1553        fetch = isinstance(limit, exp.Fetch)
    1554
    1555        return csv(
    1556            *sqls,
    1557            *[self.sql(join) for join in expression.args.get("joins") or []],
    1558            self.sql(expression, "match"),
    1559            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    1560            self.sql(expression, "where"),
    1561            self.sql(expression, "group"),
    1562            self.sql(expression, "having"),
    1563            *self.after_having_modifiers(expression),
    1564            self.sql(expression, "order"),
    1565            *self.offset_limit_modifiers(expression, fetch, limit),
    1566            *self.after_limit_modifiers(expression),
    1567            sep="",
    1568        )
    1569
    1570    def offset_limit_modifiers(
    1571        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    1572    ) -> t.List[str]:
    1573        return [
    1574            self.sql(expression, "offset") if fetch else self.sql(limit),
    1575            self.sql(limit) if fetch else self.sql(expression, "offset"),
    1576        ]
    1577
    1578    def after_having_modifiers(self, expression: exp.Expression) -> t.List[str]:
    1579        return [
    1580            self.sql(expression, "qualify"),
    1581            self.seg("WINDOW ") + self.expressions(expression, key="windows", flat=True)
    1582            if expression.args.get("windows")
    1583            else "",
    1584        ]
    1585
    1586    def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]:
    1587        locks = self.expressions(expression, key="locks", sep=" ")
    1588        locks = f" {locks}" if locks else ""
    1589        return [locks, self.sql(expression, "sample")]
    1590
    1591    def select_sql(self, expression: exp.Select) -> str:
    1592        hint = self.sql(expression, "hint")
    1593        distinct = self.sql(expression, "distinct")
    1594        distinct = f" {distinct}" if distinct else ""
    1595        kind = self.sql(expression, "kind").upper()
    1596        expressions = self.expressions(expression)
    1597
    1598        if kind:
    1599            if kind in self.SELECT_KINDS:
    1600                kind = f" AS {kind}"
    1601            else:
    1602                if kind == "STRUCT":
    1603                    expressions = self.expressions(
    1604                        sqls=[
    1605                            self.sql(
    1606                                exp.Struct(
    1607                                    expressions=[
    1608                                        exp.column(e.output_name).eq(
    1609                                            e.this if isinstance(e, exp.Alias) else e
    1610                                        )
    1611                                        for e in expression.expressions
    1612                                    ]
    1613                                )
    1614                            )
    1615                        ]
    1616                    )
    1617                kind = ""
    1618
    1619        expressions = f"{self.sep()}{expressions}" if expressions else expressions
    1620        sql = self.query_modifiers(
    1621            expression,
    1622            f"SELECT{hint}{distinct}{kind}{expressions}",
    1623            self.sql(expression, "into", comment=False),
    1624            self.sql(expression, "from", comment=False),
    1625        )
    1626        return self.prepend_ctes(expression, sql)
    1627
    1628    def schema_sql(self, expression: exp.Schema) -> str:
    1629        this = self.sql(expression, "this")
    1630        this = f"{this} " if this else ""
    1631        sql = self.schema_columns_sql(expression)
    1632        return f"{this}{sql}"
    1633
    1634    def schema_columns_sql(self, expression: exp.Schema) -> str:
    1635        return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
    1636
    1637    def star_sql(self, expression: exp.Star) -> str:
    1638        except_ = self.expressions(expression, key="except", flat=True)
    1639        except_ = f"{self.seg(self.STAR_MAPPING['except'])} ({except_})" if except_ else ""
    1640        replace = self.expressions(expression, key="replace", flat=True)
    1641        replace = f"{self.seg(self.STAR_MAPPING['replace'])} ({replace})" if replace else ""
    1642        return f"*{except_}{replace}"
    1643
    1644    def parameter_sql(self, expression: exp.Parameter) -> str:
    1645        this = self.sql(expression, "this")
    1646        this = f"{{{this}}}" if expression.args.get("wrapped") else f"{this}"
    1647        return f"{self.PARAMETER_TOKEN}{this}"
    1648
    1649    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    1650        this = self.sql(expression, "this")
    1651        kind = expression.text("kind")
    1652        if kind:
    1653            kind = f"{kind}."
    1654        return f"@@{kind}{this}"
    1655
    1656    def placeholder_sql(self, expression: exp.Placeholder) -> str:
    1657        return f":{expression.name}" if expression.name else "?"
    1658
    1659    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    1660        alias = self.sql(expression, "alias")
    1661        alias = f"{sep}{alias}" if alias else ""
    1662
    1663        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    1664        pivots = f" {pivots}" if pivots else ""
    1665
    1666        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    1667        return self.prepend_ctes(expression, sql)
    1668
    1669    def qualify_sql(self, expression: exp.Qualify) -> str:
    1670        this = self.indent(self.sql(expression, "this"))
    1671        return f"{self.seg('QUALIFY')}{self.sep()}{this}"
    1672
    1673    def union_sql(self, expression: exp.Union) -> str:
    1674        return self.prepend_ctes(
    1675            expression,
    1676            self.set_operation(expression, self.union_op(expression)),
    1677        )
    1678
    1679    def union_op(self, expression: exp.Union) -> str:
    1680        kind = " DISTINCT" if self.EXPLICIT_UNION else ""
    1681        kind = kind if expression.args.get("distinct") else " ALL"
    1682        return f"UNION{kind}"
    1683
    1684    def unnest_sql(self, expression: exp.Unnest) -> str:
    1685        args = self.expressions(expression, flat=True)
    1686        alias = expression.args.get("alias")
    1687        if alias and self.UNNEST_COLUMN_ONLY:
    1688            columns = alias.columns
    1689            alias = self.sql(columns[0]) if columns else ""
    1690        else:
    1691            alias = self.sql(expression, "alias")
    1692        alias = f" AS {alias}" if alias else alias
    1693        ordinality = " WITH ORDINALITY" if expression.args.get("ordinality") else ""
    1694        offset = expression.args.get("offset")
    1695        offset = f" WITH OFFSET AS {self.sql(offset)}" if offset else ""
    1696        return f"UNNEST({args}){ordinality}{alias}{offset}"
    1697
    1698    def where_sql(self, expression: exp.Where) -> str:
    1699        this = self.indent(self.sql(expression, "this"))
    1700        return f"{self.seg('WHERE')}{self.sep()}{this}"
    1701
    1702    def window_sql(self, expression: exp.Window) -> str:
    1703        this = self.sql(expression, "this")
    1704        partition = self.partition_by_sql(expression)
    1705        order = expression.args.get("order")
    1706        order = self.order_sql(order, flat=True) if order else ""
    1707        spec = self.sql(expression, "spec")
    1708        alias = self.sql(expression, "alias")
    1709        over = self.sql(expression, "over") or "OVER"
    1710
    1711        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    1712
    1713        first = expression.args.get("first")
    1714        if first is None:
    1715            first = ""
    1716        else:
    1717            first = "FIRST" if first else "LAST"
    1718
    1719        if not partition and not order and not spec and alias:
    1720            return f"{this} {alias}"
    1721
    1722        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
    1723        return f"{this} ({args})"
    1724
    1725    def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str:
    1726        partition = self.expressions(expression, key="partition_by", flat=True)
    1727        return f"PARTITION BY {partition}" if partition else ""
    1728
    1729    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    1730        kind = self.sql(expression, "kind")
    1731        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    1732        end = (
    1733            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    1734            or "CURRENT ROW"
    1735        )
    1736        return f"{kind} BETWEEN {start} AND {end}"
    1737
    1738    def withingroup_sql(self, expression: exp.WithinGroup) -> str:
    1739        this = self.sql(expression, "this")
    1740        expression_sql = self.sql(expression, "expression")[1:]  # order has a leading space
    1741        return f"{this} WITHIN GROUP ({expression_sql})"
    1742
    1743    def between_sql(self, expression: exp.Between) -> str:
    1744        this = self.sql(expression, "this")
    1745        low = self.sql(expression, "low")
    1746        high = self.sql(expression, "high")
    1747        return f"{this} BETWEEN {low} AND {high}"
    1748
    1749    def bracket_sql(self, expression: exp.Bracket) -> str:
    1750        expressions = apply_index_offset(expression.this, expression.expressions, self.INDEX_OFFSET)
    1751        expressions_sql = ", ".join(self.sql(e) for e in expressions)
    1752
    1753        return f"{self.sql(expression, 'this')}[{expressions_sql}]"
    1754
    1755    def safebracket_sql(self, expression: exp.SafeBracket) -> str:
    1756        return self.bracket_sql(expression)
    1757
    1758    def all_sql(self, expression: exp.All) -> str:
    1759        return f"ALL {self.wrap(expression)}"
    1760
    1761    def any_sql(self, expression: exp.Any) -> str:
    1762        this = self.sql(expression, "this")
    1763        if isinstance(expression.this, exp.Subqueryable):
    1764            this = self.wrap(this)
    1765        return f"ANY {this}"
    1766
    1767    def exists_sql(self, expression: exp.Exists) -> str:
    1768        return f"EXISTS{self.wrap(expression)}"
    1769
    1770    def case_sql(self, expression: exp.Case) -> str:
    1771        this = self.sql(expression, "this")
    1772        statements = [f"CASE {this}" if this else "CASE"]
    1773
    1774        for e in expression.args["ifs"]:
    1775            statements.append(f"WHEN {self.sql(e, 'this')}")
    1776            statements.append(f"THEN {self.sql(e, 'true')}")
    1777
    1778        default = self.sql(expression, "default")
    1779
    1780        if default:
    1781            statements.append(f"ELSE {default}")
    1782
    1783        statements.append("END")
    1784
    1785        if self.pretty and self.text_width(statements) > self.max_text_width:
    1786            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    1787
    1788        return " ".join(statements)
    1789
    1790    def constraint_sql(self, expression: exp.Constraint) -> str:
    1791        this = self.sql(expression, "this")
    1792        expressions = self.expressions(expression, flat=True)
    1793        return f"CONSTRAINT {this} {expressions}"
    1794
    1795    def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str:
    1796        order = expression.args.get("order")
    1797        order = f" OVER ({self.order_sql(order, flat=True)})" if order else ""
    1798        return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}"
    1799
    1800    def extract_sql(self, expression: exp.Extract) -> str:
    1801        this = self.sql(expression, "this")
    1802        expression_sql = self.sql(expression, "expression")
    1803        return f"EXTRACT({this} FROM {expression_sql})"
    1804
    1805    def trim_sql(self, expression: exp.Trim) -> str:
    1806        trim_type = self.sql(expression, "position")
    1807
    1808        if trim_type == "LEADING":
    1809            return self.func("LTRIM", expression.this)
    1810        elif trim_type == "TRAILING":
    1811            return self.func("RTRIM", expression.this)
    1812        else:
    1813            return self.func("TRIM", expression.this, expression.expression)
    1814
    1815    def safeconcat_sql(self, expression: exp.SafeConcat) -> str:
    1816        expressions = expression.expressions
    1817        if self.STRICT_STRING_CONCAT:
    1818            expressions = (exp.cast(e, "text") for e in expressions)
    1819        return self.func("CONCAT", *expressions)
    1820
    1821    def check_sql(self, expression: exp.Check) -> str:
    1822        this = self.sql(expression, key="this")
    1823        return f"CHECK ({this})"
    1824
    1825    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    1826        expressions = self.expressions(expression, flat=True)
    1827        reference = self.sql(expression, "reference")
    1828        reference = f" {reference}" if reference else ""
    1829        delete = self.sql(expression, "delete")
    1830        delete = f" ON DELETE {delete}" if delete else ""
    1831        update = self.sql(expression, "update")
    1832        update = f" ON UPDATE {update}" if update else ""
    1833        return f"FOREIGN KEY ({expressions}){reference}{delete}{update}"
    1834
    1835    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    1836        expressions = self.expressions(expression, flat=True)
    1837        options = self.expressions(expression, key="options", flat=True, sep=" ")
    1838        options = f" {options}" if options else ""
    1839        return f"PRIMARY KEY ({expressions}){options}"
    1840
    1841    def if_sql(self, expression: exp.If) -> str:
    1842        return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false")))
    1843
    1844    def matchagainst_sql(self, expression: exp.MatchAgainst) -> str:
    1845        modifier = expression.args.get("modifier")
    1846        modifier = f" {modifier}" if modifier else ""
    1847        return f"{self.func('MATCH', *expression.expressions)} AGAINST({self.sql(expression, 'this')}{modifier})"
    1848
    1849    def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str:
    1850        return f"{self.sql(expression, 'this')}: {self.sql(expression, 'expression')}"
    1851
    1852    def jsonobject_sql(self, expression: exp.JSONObject) -> str:
    1853        null_handling = expression.args.get("null_handling")
    1854        null_handling = f" {null_handling}" if null_handling else ""
    1855        unique_keys = expression.args.get("unique_keys")
    1856        if unique_keys is not None:
    1857            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    1858        else:
    1859            unique_keys = ""
    1860        return_type = self.sql(expression, "return_type")
    1861        return_type = f" RETURNING {return_type}" if return_type else ""
    1862        format_json = " FORMAT JSON" if expression.args.get("format_json") else ""
    1863        encoding = self.sql(expression, "encoding")
    1864        encoding = f" ENCODING {encoding}" if encoding else ""
    1865        return self.func(
    1866            "JSON_OBJECT",
    1867            *expression.expressions,
    1868            suffix=f"{null_handling}{unique_keys}{return_type}{format_json}{encoding})",
    1869        )
    1870
    1871    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    1872        this = self.sql(expression, "this")
    1873        kind = self.sql(expression, "kind")
    1874        path = self.sql(expression, "path")
    1875        path = f" {path}" if path else ""
    1876        as_json = " AS JSON" if expression.args.get("as_json") else ""
    1877        return f"{this} {kind}{path}{as_json}"
    1878
    1879    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    1880        this = self.sql(expression, "this")
    1881        path = self.sql(expression, "path")
    1882        path = f", {path}" if path else ""
    1883        expressions = self.expressions(expression)
    1884        with_ = (
    1885            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    1886            if expressions
    1887            else ""
    1888        )
    1889        return f"OPENJSON({this}{path}){with_}"
    1890
    1891    def in_sql(self, expression: exp.In) -> str:
    1892        query = expression.args.get("query")
    1893        unnest = expression.args.get("unnest")
    1894        field = expression.args.get("field")
    1895        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    1896
    1897        if query:
    1898            in_sql = self.wrap(query)
    1899        elif unnest:
    1900            in_sql = self.in_unnest_op(unnest)
    1901        elif field:
    1902            in_sql = self.sql(field)
    1903        else:
    1904            in_sql = f"({self.expressions(expression, flat=True)})"
    1905
    1906        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"
    1907
    1908    def in_unnest_op(self, unnest: exp.Unnest) -> str:
    1909        return f"(SELECT {self.sql(unnest)})"
    1910
    1911    def interval_sql(self, expression: exp.Interval) -> str:
    1912        unit = self.sql(expression, "unit")
    1913        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    1914            unit = self.TIME_PART_SINGULARS.get(unit.lower(), unit)
    1915        unit = f" {unit}" if unit else ""
    1916
    1917        if self.SINGLE_STRING_INTERVAL:
    1918            this = expression.this.name if expression.this else ""
    1919            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    1920
    1921        this = self.sql(expression, "this")
    1922        if this:
    1923            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    1924            this = f" {this}" if unwrapped else f" ({this})"
    1925
    1926        return f"INTERVAL{this}{unit}"
    1927
    1928    def return_sql(self, expression: exp.Return) -> str:
    1929        return f"RETURN {self.sql(expression, 'this')}"
    1930
    1931    def reference_sql(self, expression: exp.Reference) -> str:
    1932        this = self.sql(expression, "this")
    1933        expressions = self.expressions(expression, flat=True)
    1934        expressions = f"({expressions})" if expressions else ""
    1935        options = self.expressions(expression, key="options", flat=True, sep=" ")
    1936        options = f" {options}" if options else ""
    1937        return f"REFERENCES {this}{expressions}{options}"
    1938
    1939    def anonymous_sql(self, expression: exp.Anonymous) -> str:
    1940        return self.func(expression.name, *expression.expressions)
    1941
    1942    def paren_sql(self, expression: exp.Paren) -> str:
    1943        if isinstance(expression.unnest(), exp.Select):
    1944            sql = self.wrap(expression)
    1945        else:
    1946            sql = self.seg(self.indent(self.sql(expression, "this")), sep="")
    1947            sql = f"({sql}{self.seg(')', sep='')}"
    1948
    1949        return self.prepend_ctes(expression, sql)
    1950
    1951    def neg_sql(self, expression: exp.Neg) -> str:
    1952        # This makes sure we don't convert "- - 5" to "--5", which is a comment
    1953        this_sql = self.sql(expression, "this")
    1954        sep = " " if this_sql[0] == "-" else ""
    1955        return f"-{sep}{this_sql}"
    1956
    1957    def not_sql(self, expression: exp.Not) -> str:
    1958        return f"NOT {self.sql(expression, 'this')}"
    1959
    1960    def alias_sql(self, expression: exp.Alias) -> str:
    1961        alias = self.sql(expression, "alias")
    1962        alias = f" AS {alias}" if alias else ""
    1963        return f"{self.sql(expression, 'this')}{alias}"
    1964
    1965    def aliases_sql(self, expression: exp.Aliases) -> str:
    1966        return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})"
    1967
    1968    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    1969        this = self.sql(expression, "this")
    1970        zone = self.sql(expression, "zone")
    1971        return f"{this} AT TIME ZONE {zone}"
    1972
    1973    def add_sql(self, expression: exp.Add) -> str:
    1974        return self.binary(expression, "+")
    1975
    1976    def and_sql(self, expression: exp.And) -> str:
    1977        return self.connector_sql(expression, "AND")
    1978
    1979    def connector_sql(self, expression: exp.Connector, op: str) -> str:
    1980        if not self.pretty:
    1981            return self.binary(expression, op)
    1982
    1983        sqls = tuple(
    1984            self.maybe_comment(self.sql(e), e, e.parent.comments or []) if i != 1 else self.sql(e)
    1985            for i, e in enumerate(expression.flatten(unnest=False))
    1986        )
    1987
    1988        sep = "\n" if self.text_width(sqls) > self.max_text_width else " "
    1989        return f"{sep}{op} ".join(sqls)
    1990
    1991    def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str:
    1992        return self.binary(expression, "&")
    1993
    1994    def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str:
    1995        return self.binary(expression, "<<")
    1996
    1997    def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str:
    1998        return f"~{self.sql(expression, 'this')}"
    1999
    2000    def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str:
    2001        return self.binary(expression, "|")
    2002
    2003    def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str:
    2004        return self.binary(expression, ">>")
    2005
    2006    def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str:
    2007        return self.binary(expression, "^")
    2008
    2009    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    2010        format_sql = self.sql(expression, "format")
    2011        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    2012        return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS {self.sql(expression, 'to')}{format_sql})"
    2013
    2014    def currentdate_sql(self, expression: exp.CurrentDate) -> str:
    2015        zone = self.sql(expression, "this")
    2016        return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE"
    2017
    2018    def collate_sql(self, expression: exp.Collate) -> str:
    2019        return self.binary(expression, "COLLATE")
    2020
    2021    def command_sql(self, expression: exp.Command) -> str:
    2022        return f"{self.sql(expression, 'this').upper()} {expression.text('expression').strip()}"
    2023
    2024    def comment_sql(self, expression: exp.Comment) -> str:
    2025        this = self.sql(expression, "this")
    2026        kind = expression.args["kind"]
    2027        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    2028        expression_sql = self.sql(expression, "expression")
    2029        return f"COMMENT{exists_sql}ON {kind} {this} IS {expression_sql}"
    2030
    2031    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    2032        this = self.sql(expression, "this")
    2033        delete = " DELETE" if expression.args.get("delete") else ""
    2034        recompress = self.sql(expression, "recompress")
    2035        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    2036        to_disk = self.sql(expression, "to_disk")
    2037        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    2038        to_volume = self.sql(expression, "to_volume")
    2039        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    2040        return f"{this}{delete}{recompress}{to_disk}{to_volume}"
    2041
    2042    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    2043        where = self.sql(expression, "where")
    2044        group = self.sql(expression, "group")
    2045        aggregates = self.expressions(expression, key="aggregates")
    2046        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    2047
    2048        if not (where or group or aggregates) and len(expression.expressions) == 1:
    2049            return f"TTL {self.expressions(expression, flat=True)}"
    2050
    2051        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"
    2052
    2053    def transaction_sql(self, expression: exp.Transaction) -> str:
    2054        return "BEGIN"
    2055
    2056    def commit_sql(self, expression: exp.Commit) -> str:
    2057        chain = expression.args.get("chain")
    2058        if chain is not None:
    2059            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    2060
    2061        return f"COMMIT{chain or ''}"
    2062
    2063    def rollback_sql(self, expression: exp.Rollback) -> str:
    2064        savepoint = expression.args.get("savepoint")
    2065        savepoint = f" TO {savepoint}" if savepoint else ""
    2066        return f"ROLLBACK{savepoint}"
    2067
    2068    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    2069        this = self.sql(expression, "this")
    2070
    2071        dtype = self.sql(expression, "dtype")
    2072        if dtype:
    2073            collate = self.sql(expression, "collate")
    2074            collate = f" COLLATE {collate}" if collate else ""
    2075            using = self.sql(expression, "using")
    2076            using = f" USING {using}" if using else ""
    2077            return f"ALTER COLUMN {this} TYPE {dtype}{collate}{using}"
    2078
    2079        default = self.sql(expression, "default")
    2080        if default:
    2081            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    2082
    2083        if not expression.args.get("drop"):
    2084            self.unsupported("Unsupported ALTER COLUMN syntax")
    2085
    2086        return f"ALTER COLUMN {this} DROP DEFAULT"
    2087
    2088    def renametable_sql(self, expression: exp.RenameTable) -> str:
    2089        if not self.RENAME_TABLE_WITH_DB:
    2090            # Remove db from tables
    2091            expression = expression.transform(
    2092                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    2093            )
    2094        this = self.sql(expression, "this")
    2095        return f"RENAME TO {this}"
    2096
    2097    def altertable_sql(self, expression: exp.AlterTable) -> str:
    2098        actions = expression.args["actions"]
    2099
    2100        if isinstance(actions[0], exp.ColumnDef):
    2101            actions = self.expressions(expression, key="actions", prefix="ADD COLUMN ")
    2102        elif isinstance(actions[0], exp.Schema):
    2103            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    2104        elif isinstance(actions[0], exp.Delete):
    2105            actions = self.expressions(expression, key="actions", flat=True)
    2106        else:
    2107            actions = self.expressions(expression, key="actions")
    2108
    2109        exists = " IF EXISTS" if expression.args.get("exists") else ""
    2110        return f"ALTER TABLE{exists} {self.sql(expression, 'this')} {actions}"
    2111
    2112    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    2113        expressions = self.expressions(expression)
    2114        exists = " IF EXISTS " if expression.args.get("exists") else " "
    2115        return f"DROP{exists}{expressions}"
    2116
    2117    def addconstraint_sql(self, expression: exp.AddConstraint) -> str:
    2118        this = self.sql(expression, "this")
    2119        expression_ = self.sql(expression, "expression")
    2120        add_constraint = f"ADD CONSTRAINT {this}" if this else "ADD"
    2121
    2122        enforced = expression.args.get("enforced")
    2123        if enforced is not None:
    2124            return f"{add_constraint} CHECK ({expression_}){' ENFORCED' if enforced else ''}"
    2125
    2126        return f"{add_constraint} {expression_}"
    2127
    2128    def distinct_sql(self, expression: exp.Distinct) -> str:
    2129        this = self.expressions(expression, flat=True)
    2130        this = f" {this}" if this else ""
    2131
    2132        on = self.sql(expression, "on")
    2133        on = f" ON {on}" if on else ""
    2134        return f"DISTINCT{this}{on}"
    2135
    2136    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
    2137        return f"{self.sql(expression, 'this')} IGNORE NULLS"
    2138
    2139    def respectnulls_sql(self, expression: exp.RespectNulls) -> str:
    2140        return f"{self.sql(expression, 'this')} RESPECT NULLS"
    2141
    2142    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    2143        return self.sql(
    2144            exp.Cast(
    2145                this=exp.Div(this=expression.this, expression=expression.expression),
    2146                to=exp.DataType(this=exp.DataType.Type.INT),
    2147            )
    2148        )
    2149
    2150    def dpipe_sql(self, expression: exp.DPipe) -> str:
    2151        return self.binary(expression, "||")
    2152
    2153    def safedpipe_sql(self, expression: exp.SafeDPipe) -> str:
    2154        if self.STRICT_STRING_CONCAT:
    2155            return self.func("CONCAT", *(exp.cast(e, "text") for e in expression.flatten()))
    2156        return self.dpipe_sql(expression)
    2157
    2158    def div_sql(self, expression: exp.Div) -> str:
    2159        return self.binary(expression, "/")
    2160
    2161    def overlaps_sql(self, expression: exp.Overlaps) -> str:
    2162        return self.binary(expression, "OVERLAPS")
    2163
    2164    def distance_sql(self, expression: exp.Distance) -> str:
    2165        return self.binary(expression, "<->")
    2166
    2167    def dot_sql(self, expression: exp.Dot) -> str:
    2168        return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}"
    2169
    2170    def eq_sql(self, expression: exp.EQ) -> str:
    2171        return self.binary(expression, "=")
    2172
    2173    def escape_sql(self, expression: exp.Escape) -> str:
    2174        return self.binary(expression, "ESCAPE")
    2175
    2176    def glob_sql(self, expression: exp.Glob) -> str:
    2177        return self.binary(expression, "GLOB")
    2178
    2179    def gt_sql(self, expression: exp.GT) -> str:
    2180        return self.binary(expression, ">")
    2181
    2182    def gte_sql(self, expression: exp.GTE) -> str:
    2183        return self.binary(expression, ">=")
    2184
    2185    def ilike_sql(self, expression: exp.ILike) -> str:
    2186        return self.binary(expression, "ILIKE")
    2187
    2188    def ilikeany_sql(self, expression: exp.ILikeAny) -> str:
    2189        return self.binary(expression, "ILIKE ANY")
    2190
    2191    def is_sql(self, expression: exp.Is) -> str:
    2192        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    2193            return self.sql(
    2194                expression.this if expression.expression.this else exp.not_(expression.this)
    2195            )
    2196        return self.binary(expression, "IS")
    2197
    2198    def like_sql(self, expression: exp.Like) -> str:
    2199        return self.binary(expression, "LIKE")
    2200
    2201    def likeany_sql(self, expression: exp.LikeAny) -> str:
    2202        return self.binary(expression, "LIKE ANY")
    2203
    2204    def similarto_sql(self, expression: exp.SimilarTo) -> str:
    2205        return self.binary(expression, "SIMILAR TO")
    2206
    2207    def lt_sql(self, expression: exp.LT) -> str:
    2208        return self.binary(expression, "<")
    2209
    2210    def lte_sql(self, expression: exp.LTE) -> str:
    2211        return self.binary(expression, "<=")
    2212
    2213    def mod_sql(self, expression: exp.Mod) -> str:
    2214        return self.binary(expression, "%")
    2215
    2216    def mul_sql(self, expression: exp.Mul) -> str:
    2217        return self.binary(expression, "*")
    2218
    2219    def neq_sql(self, expression: exp.NEQ) -> str:
    2220        return self.binary(expression, "<>")
    2221
    2222    def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str:
    2223        return self.binary(expression, "IS NOT DISTINCT FROM")
    2224
    2225    def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str:
    2226        return self.binary(expression, "IS DISTINCT FROM")
    2227
    2228    def or_sql(self, expression: exp.Or) -> str:
    2229        return self.connector_sql(expression, "OR")
    2230
    2231    def slice_sql(self, expression: exp.Slice) -> str:
    2232        return self.binary(expression, ":")
    2233
    2234    def sub_sql(self, expression: exp.Sub) -> str:
    2235        return self.binary(expression, "-")
    2236
    2237    def trycast_sql(self, expression: exp.TryCast) -> str:
    2238        return self.cast_sql(expression, safe_prefix="TRY_")
    2239
    2240    def use_sql(self, expression: exp.Use) -> str:
    2241        kind = self.sql(expression, "kind")
    2242        kind = f" {kind}" if kind else ""
    2243        this = self.sql(expression, "this")
    2244        this = f" {this}" if this else ""
    2245        return f"USE{kind}{this}"
    2246
    2247    def binary(self, expression: exp.Binary, op: str) -> str:
    2248        op = self.maybe_comment(op, comments=expression.comments)
    2249        return f"{self.sql(expression, 'this')} {op} {self.sql(expression, 'expression')}"
    2250
    2251    def function_fallback_sql(self, expression: exp.Func) -> str:
    2252        args = []
    2253        for arg_value in expression.args.values():
    2254            if isinstance(arg_value, list):
    2255                for value in arg_value:
    2256                    args.append(value)
    2257            else:
    2258                args.append(arg_value)
    2259
    2260        return self.func(expression.sql_name(), *args)
    2261
    2262    def func(
    2263        self,
    2264        name: str,
    2265        *args: t.Optional[exp.Expression | str],
    2266        prefix: str = "(",
    2267        suffix: str = ")",
    2268    ) -> str:
    2269        return f"{self.normalize_func(name)}{prefix}{self.format_args(*args)}{suffix}"
    2270
    2271    def format_args(self, *args: t.Optional[str | exp.Expression]) -> str:
    2272        arg_sqls = tuple(self.sql(arg) for arg in args if arg is not None)
    2273        if self.pretty and self.text_width(arg_sqls) > self.max_text_width:
    2274            return self.indent("\n" + f",\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True)
    2275        return ", ".join(arg_sqls)
    2276
    2277    def text_width(self, args: t.Iterable) -> int:
    2278        return sum(len(arg) for arg in args)
    2279
    2280    def format_time(self, expression: exp.Expression) -> t.Optional[str]:
    2281        return format_time(
    2282            self.sql(expression, "format"), self.INVERSE_TIME_MAPPING, self.INVERSE_TIME_TRIE
    2283        )
    2284
    2285    def expressions(
    2286        self,
    2287        expression: t.Optional[exp.Expression] = None,
    2288        key: t.Optional[str] = None,
    2289        sqls: t.Optional[t.List[str]] = None,
    2290        flat: bool = False,
    2291        indent: bool = True,
    2292        sep: str = ", ",
    2293        prefix: str = "",
    2294    ) -> str:
    2295        expressions = expression.args.get(key or "expressions") if expression else sqls
    2296
    2297        if not expressions:
    2298            return ""
    2299
    2300        if flat:
    2301            return sep.join(self.sql(e) for e in expressions)
    2302
    2303        num_sqls = len(expressions)
    2304
    2305        # These are calculated once in case we have the leading_comma / pretty option set, correspondingly
    2306        pad = " " * self.pad
    2307        stripped_sep = sep.strip()
    2308
    2309        result_sqls = []
    2310        for i, e in enumerate(expressions):
    2311            sql = self.sql(e, comment=False)
    2312            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    2313
    2314            if self.pretty:
    2315                if self.leading_comma:
    2316                    result_sqls.append(f"{sep if i > 0 else pad}{prefix}{sql}{comments}")
    2317                else:
    2318                    result_sqls.append(
    2319                        f"{prefix}{sql}{stripped_sep if i + 1 < num_sqls else ''}{comments}"
    2320                    )
    2321            else:
    2322                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    2323
    2324        result_sql = "\n".join(result_sqls) if self.pretty else "".join(result_sqls)
    2325        return self.indent(result_sql, skip_first=False) if indent else result_sql
    2326
    2327    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    2328        flat = flat or isinstance(expression.parent, exp.Properties)
    2329        expressions_sql = self.expressions(expression, flat=flat)
    2330        if flat:
    2331            return f"{op} {expressions_sql}"
    2332        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"
    2333
    2334    def naked_property(self, expression: exp.Property) -> str:
    2335        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    2336        if not property_name:
    2337            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    2338        return f"{property_name} {self.sql(expression, 'this')}"
    2339
    2340    def set_operation(self, expression: exp.Expression, op: str) -> str:
    2341        this = self.sql(expression, "this")
    2342        op = self.seg(op)
    2343        return self.query_modifiers(
    2344            expression, f"{this}{op}{self.sep()}{self.sql(expression, 'expression')}"
    2345        )
    2346
    2347    def tag_sql(self, expression: exp.Tag) -> str:
    2348        return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}"
    2349
    2350    def token_sql(self, token_type: TokenType) -> str:
    2351        return self.TOKEN_MAPPING.get(token_type, token_type.name)
    2352
    2353    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    2354        this = self.sql(expression, "this")
    2355        expressions = self.no_identify(self.expressions, expression)
    2356        expressions = (
    2357            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    2358        )
    2359        return f"{this}{expressions}"
    2360
    2361    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    2362        this = self.sql(expression, "this")
    2363        expressions = self.expressions(expression, flat=True)
    2364        return f"{this}({expressions})"
    2365
    2366    def kwarg_sql(self, expression: exp.Kwarg) -> str:
    2367        return self.binary(expression, "=>")
    2368
    2369    def when_sql(self, expression: exp.When) -> str:
    2370        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    2371        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    2372        condition = self.sql(expression, "condition")
    2373        condition = f" AND {condition}" if condition else ""
    2374
    2375        then_expression = expression.args.get("then")
    2376        if isinstance(then_expression, exp.Insert):
    2377            then = f"INSERT {self.sql(then_expression, 'this')}"
    2378            if "expression" in then_expression.args:
    2379                then += f" VALUES {self.sql(then_expression, 'expression')}"
    2380        elif isinstance(then_expression, exp.Update):
    2381            if isinstance(then_expression.args.get("expressions"), exp.Star):
    2382                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    2383            else:
    2384                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    2385        else:
    2386            then = self.sql(then_expression)
    2387        return f"WHEN {matched}{source}{condition} THEN {then}"
    2388
    2389    def merge_sql(self, expression: exp.Merge) -> str:
    2390        this = self.sql(expression, "this")
    2391        using = f"USING {self.sql(expression, 'using')}"
    2392        on = f"ON {self.sql(expression, 'on')}"
    2393        return f"MERGE INTO {this} {using} {on} {self.expressions(expression, sep=' ')}"
    2394
    2395    def tochar_sql(self, expression: exp.ToChar) -> str:
    2396        if expression.args.get("format"):
    2397            self.unsupported("Format argument unsupported for TO_CHAR/TO_VARCHAR function")
    2398
    2399        return self.sql(exp.cast(expression.this, "text"))
    2400
    2401    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    2402        this = self.sql(expression, "this")
    2403        kind = self.sql(expression, "kind")
    2404        settings_sql = self.expressions(expression, key="settings", sep=" ")
    2405        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    2406        return f"{this}({kind}{args})"
    2407
    2408    def dictrange_sql(self, expression: exp.DictRange) -> str:
    2409        this = self.sql(expression, "this")
    2410        max = self.sql(expression, "max")
    2411        min = self.sql(expression, "min")
    2412        return f"{this}(MIN {min} MAX {max})"
    2413
    2414    def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str:
    2415        return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}"
    2416
    2417    def oncluster_sql(self, expression: exp.OnCluster) -> str:
    2418        return ""
    2419
    2420    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    2421        expressions = self.expressions(expression, key="expressions", flat=True)
    2422        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    2423        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    2424        buckets = self.sql(expression, "buckets")
    2425        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"

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

###### Arguments:

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

Generator( pretty: Optional[bool] = None, identify: str | bool = False, normalize: bool = False, pad: int = 2, indent: int = 2, normalize_functions: Union[str, bool, NoneType] = None, unsupported_level: sqlglot.errors.ErrorLevel = <ErrorLevel.WARN: 'WARN'>, max_unsupported: int = 3, leading_comma: bool = False, max_text_width: int = 80, comments: bool = True) View Source

    311    def __init__(
    312        self,
    313        pretty: t.Optional[bool] = None,
    314        identify: str | bool = False,
    315        normalize: bool = False,
    316        pad: int = 2,
    317        indent: int = 2,
    318        normalize_functions: t.Optional[str | bool] = None,
    319        unsupported_level: ErrorLevel = ErrorLevel.WARN,
    320        max_unsupported: int = 3,
    321        leading_comma: bool = False,
    322        max_text_width: int = 80,
    323        comments: bool = True,
    324    ):
    325        import sqlglot
    326
    327        self.pretty = pretty if pretty is not None else sqlglot.pretty
    328        self.identify = identify
    329        self.normalize = normalize
    330        self.pad = pad
    331        self._indent = indent
    332        self.unsupported_level = unsupported_level
    333        self.max_unsupported = max_unsupported
    334        self.leading_comma = leading_comma
    335        self.max_text_width = max_text_width
    336        self.comments = comments
    337
    338        # This is both a Dialect property and a Generator argument, so we prioritize the latter
    339        self.normalize_functions = (
    340            self.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions
    341        )
    342
    343        self.unsupported_messages: t.List[str] = []
    344        self._escaped_quote_end: str = self.STRING_ESCAPE + self.QUOTE_END
    345        self._escaped_identifier_end: str = self.IDENTIFIER_ESCAPE + self.IDENTIFIER_END
    346        self._cache: t.Optional[t.Dict[int, str]] = None

TRANSFORMS = {<class 'sqlglot.expressions.DateAdd'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TsOrDsAdd'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CaseSpecificColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CheckColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CommentColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DateFormatColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DefaultColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EncodeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExternalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InlineLengthColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LanguageProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LocationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.MaterializedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnCommitProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnUpdateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ReturnsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StabilityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TemporaryProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VarMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <function Generator.<lambda>>}
NULL_ORDERING_SUPPORTED = True
LOCKING_READS_SUPPORTED = False
EXPLICIT_UNION = False
WRAP_DERIVED_VALUES = True
CREATE_FUNCTION_RETURN_AS = True
MATCHED_BY_SOURCE = True
SINGLE_STRING_INTERVAL = False
INTERVAL_ALLOWS_PLURAL_FORM = True
TABLESAMPLE_WITH_METHOD = True
TABLESAMPLE_SIZE_IS_PERCENT = False
LIMIT_FETCH = 'ALL'
RENAME_TABLE_WITH_DB = True
GROUPINGS_SEP = ','
INDEX_ON = 'ON'
JOIN_HINTS = True
TABLE_HINTS = True
IS_BOOL_ALLOWED = True
SELECT_KINDS: Tuple[str, ...] = ('STRUCT', 'VALUE')
TYPE_MAPPING = {<Type.NCHAR: 'NCHAR'>: 'CHAR', <Type.NVARCHAR: 'NVARCHAR'>: 'VARCHAR', <Type.MEDIUMTEXT: 'MEDIUMTEXT'>: 'TEXT', <Type.LONGTEXT: 'LONGTEXT'>: 'TEXT', <Type.MEDIUMBLOB: 'MEDIUMBLOB'>: 'BLOB', <Type.LONGBLOB: 'LONGBLOB'>: 'BLOB', <Type.INET: 'INET'>: 'INET'}
STAR_MAPPING = {'except': 'EXCEPT', 'replace': 'REPLACE'}
TIME_PART_SINGULARS = {'microseconds': 'microsecond', 'seconds': 'second', 'minutes': 'minute', 'hours': 'hour', 'days': 'day', 'weeks': 'week', 'months': 'month', 'quarters': 'quarter', 'years': 'year'}
TOKEN_MAPPING: Dict[sqlglot.tokens.TokenType, str] = {}
STRUCT_DELIMITER = ('<', '>')
PARAMETER_TOKEN = '@'
PROPERTIES_LOCATION = {<class 'sqlglot.expressions.AlgorithmProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.AutoIncrementProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.BlockCompressionProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CharacterSetProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ChecksumProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CollateProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Cluster'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ClusteredByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DataBlocksizeProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.DefinerProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.DictRange'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DictProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistStyleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EngineProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExternalProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.FallbackProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.FileFormatProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.FreespaceProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.IsolatedLoadingProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.JournalProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.LanguageProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LikeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LocationProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LockingProperty'>: <Location.POST_ALIAS: 'POST_ALIAS'>, <class 'sqlglot.expressions.LogProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.MaterializedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.MergeBlockRatioProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.OnCommitProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.Order'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PartitionedByProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.PrimaryKey'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Property'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.ReturnsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatDelimitedProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatSerdeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SchemaCommentProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SerdeProperties'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Set'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SettingsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SetProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.SortKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StabilityProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TemporaryProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.ToTableProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TransientProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.MergeTreeTTL'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.VolatileProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.WithDataProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <Location.POST_NAME: 'POST_NAME'>}
RESERVED_KEYWORDS: Set[str] = set()
WITH_SEPARATED_COMMENTS: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Select'>, <class 'sqlglot.expressions.From'>, <class 'sqlglot.expressions.Where'>, <class 'sqlglot.expressions.With'>)
UNWRAPPED_INTERVAL_VALUES: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Column'>, <class 'sqlglot.expressions.Literal'>, <class 'sqlglot.expressions.Neg'>, <class 'sqlglot.expressions.Paren'>)
SENTINEL_LINE_BREAK = '__SQLGLOT__LB__'
INVERSE_TIME_MAPPING: Dict[str, str] = {}
INVERSE_TIME_TRIE: Dict = {}
INDEX_OFFSET = 0
UNNEST_COLUMN_ONLY = False
ALIAS_POST_TABLESAMPLE = False
IDENTIFIERS_CAN_START_WITH_DIGIT = False
STRICT_STRING_CONCAT = False
NORMALIZE_FUNCTIONS: bool | str = 'upper'
NULL_ORDERING = 'nulls_are_small'
@classmethod
def can_identify(text: str, identify: str | bool = 'safe') -> bool: View Source

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

Checks if text can be identified given an identify option.

###### Arguments:

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

###### Returns:

> Whether or not the given text can be identified.

QUOTE_START = "'"
QUOTE_END = "'"
IDENTIFIER_START = '"'
IDENTIFIER_END = '"'
STRING_ESCAPE = "'"
IDENTIFIER_ESCAPE = '"'
BIT_START: Optional[str] = None
BIT_END: Optional[str] = None
HEX_START: Optional[str] = None
HEX_END: Optional[str] = None
BYTE_START: Optional[str] = None
BYTE_END: Optional[str] = None
RAW_START: Optional[str] = None
RAW_END: Optional[str] = None
pretty
identify
normalize
pad
unsupported_level
max_unsupported
leading_comma
max_text_width
comments
normalize_functions
unsupported_messages: List[str]
def generate( self, expression: Optional[sqlglot.expressions.Expression], cache: Optional[Dict[int, str]] = None) -> str: View Source

    348    def generate(
    349        self,
    350        expression: t.Optional[exp.Expression],
    351        cache: t.Optional[t.Dict[int, str]] = None,
    352    ) -> str:
    353        """
    354        Generates the SQL string corresponding to the given syntax tree.
    355
    356        Args:
    357            expression: The syntax tree.
    358            cache: An optional sql string cache. This leverages the hash of an Expression
    359                which can be slow to compute, so only use it if you set _hash on each node.
    360
    361        Returns:
    362            The SQL string corresponding to `expression`.
    363        """
    364        if cache is not None:
    365            self._cache = cache
    366
    367        self.unsupported_messages = []
    368        sql = self.sql(expression).strip()
    369        self._cache = None
    370
    371        if self.unsupported_level == ErrorLevel.IGNORE:
    372            return sql
    373
    374        if self.unsupported_level == ErrorLevel.WARN:
    375            for msg in self.unsupported_messages:
    376                logger.warning(msg)
    377        elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages:
    378            raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported))
    379
    380        if self.pretty:
    381            sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n")
    382        return sql

Generates the SQL string corresponding to the given syntax tree.

###### Arguments:

- expression: The syntax tree.
- cache: An optional sql string cache. This leverages the hash of an Expression which can be slow to compute, so only use it if you set _hash on each node.

###### Returns:

> The SQL string corresponding to `expression`.

def unsupported(self, message: str) -> None: View Source

    384    def unsupported(self, message: str) -> None:
    385        if self.unsupported_level == ErrorLevel.IMMEDIATE:
    386            raise UnsupportedError(message)
    387        self.unsupported_messages.append(message)

def sep(self, sep: str = ' ') -> str: View Source

    389    def sep(self, sep: str = " ") -> str:
    390        return f"{sep.strip()}\n" if self.pretty else sep

def seg(self, sql: str, sep: str = ' ') -> str: View Source

    392    def seg(self, sql: str, sep: str = " ") -> str:
    393        return f"{self.sep(sep)}{sql}"

def pad_comment(self, comment: str) -> str: View Source

    395    def pad_comment(self, comment: str) -> str:
    396        comment = " " + comment if comment[0].strip() else comment
    397        comment = comment + " " if comment[-1].strip() else comment
    398        return comment

def maybe_comment( self, sql: str, expression: Optional[sqlglot.expressions.Expression] = None, comments: Optional[List[str]] = None) -> str: View Source

    400    def maybe_comment(
    401        self,
    402        sql: str,
    403        expression: t.Optional[exp.Expression] = None,
    404        comments: t.Optional[t.List[str]] = None,
    405    ) -> str:
    406        comments = (
    407            ((expression and expression.comments) if comments is None else comments)  # type: ignore
    408            if self.comments
    409            else None
    410        )
    411
    412        if not comments or isinstance(expression, exp.Binary):
    413            return sql
    414
    415        sep = "\n" if self.pretty else " "
    416        comments_sql = sep.join(
    417            f"/*{self.pad_comment(comment)}*/" for comment in comments if comment
    418        )
    419
    420        if not comments_sql:
    421            return sql
    422
    423        if isinstance(expression, self.WITH_SEPARATED_COMMENTS):
    424            return (
    425                f"{self.sep()}{comments_sql}{sql}"
    426                if sql[0].isspace()
    427                else f"{comments_sql}{self.sep()}{sql}"
    428            )
    429
    430        return f"{sql} {comments_sql}"

def wrap(self, expression: sqlglot.expressions.Expression | str) -> str: View Source

    432    def wrap(self, expression: exp.Expression | str) -> str:
    433        this_sql = self.indent(
    434            self.sql(expression)
    435            if isinstance(expression, (exp.Select, exp.Union))
    436            else self.sql(expression, "this"),
    437            level=1,
    438            pad=0,
    439        )
    440        return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"

def no_identify(self, func: Callable[..., str], *args, **kwargs) -> str: View Source

    442    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
    443        original = self.identify
    444        self.identify = False
    445        result = func(*args, **kwargs)
    446        self.identify = original
    447        return result

def normalize_func(self, name: str) -> str: View Source

    449    def normalize_func(self, name: str) -> str:
    450        if self.normalize_functions == "upper" or self.normalize_functions is True:
    451            return name.upper()
    452        if self.normalize_functions == "lower":
    453            return name.lower()
    454        return name

def indent( self, sql: str, level: int = 0, pad: Optional[int] = None, skip_first: bool = False, skip_last: bool = False) -> str: View Source

    456    def indent(
    457        self,
    458        sql: str,
    459        level: int = 0,
    460        pad: t.Optional[int] = None,
    461        skip_first: bool = False,
    462        skip_last: bool = False,
    463    ) -> str:
    464        if not self.pretty:
    465            return sql
    466
    467        pad = self.pad if pad is None else pad
    468        lines = sql.split("\n")
    469
    470        return "\n".join(
    471            line
    472            if (skip_first and i == 0) or (skip_last and i == len(lines) - 1)
    473            else f"{' ' * (level * self._indent + pad)}{line}"
    474            for i, line in enumerate(lines)
    475        )

def sql( self, expression: Union[str, sqlglot.expressions.Expression, NoneType], key: Optional[str] = None, comment: bool = True) -> str: View Source

    477    def sql(
    478        self,
    479        expression: t.Optional[str | exp.Expression],
    480        key: t.Optional[str] = None,
    481        comment: bool = True,
    482    ) -> str:
    483        if not expression:
    484            return ""
    485
    486        if isinstance(expression, str):
    487            return expression
    488
    489        if key:
    490            return self.sql(expression.args.get(key))
    491
    492        if self._cache is not None:
    493            expression_id = hash(expression)
    494
    495            if expression_id in self._cache:
    496                return self._cache[expression_id]
    497
    498        transform = self.TRANSFORMS.get(expression.__class__)
    499
    500        if callable(transform):
    501            sql = transform(self, expression)
    502        elif transform:
    503            sql = transform
    504        elif isinstance(expression, exp.Expression):
    505            exp_handler_name = f"{expression.key}_sql"
    506
    507            if hasattr(self, exp_handler_name):
    508                sql = getattr(self, exp_handler_name)(expression)
    509            elif isinstance(expression, exp.Func):
    510                sql = self.function_fallback_sql(expression)
    511            elif isinstance(expression, exp.Property):
    512                sql = self.property_sql(expression)
    513            else:
    514                raise ValueError(f"Unsupported expression type {expression.__class__.__name__}")
    515        else:
    516            raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}")
    517
    518        sql = self.maybe_comment(sql, expression) if self.comments and comment else sql
    519
    520        if self._cache is not None:
    521            self._cache[expression_id] = sql
    522        return sql

def uncache_sql(self, expression: sqlglot.expressions.Uncache) -> str: View Source

    524    def uncache_sql(self, expression: exp.Uncache) -> str:
    525        table = self.sql(expression, "this")
    526        exists_sql = " IF EXISTS" if expression.args.get("exists") else ""
    527        return f"UNCACHE TABLE{exists_sql} {table}"

def cache_sql(self, expression: sqlglot.expressions.Cache) -> str: View Source

    529    def cache_sql(self, expression: exp.Cache) -> str:
    530        lazy = " LAZY" if expression.args.get("lazy") else ""
    531        table = self.sql(expression, "this")
    532        options = expression.args.get("options")
    533        options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else ""
    534        sql = self.sql(expression, "expression")
    535        sql = f" AS{self.sep()}{sql}" if sql else ""
    536        sql = f"CACHE{lazy} TABLE {table}{options}{sql}"
    537        return self.prepend_ctes(expression, sql)

def characterset_sql(self, expression: sqlglot.expressions.CharacterSet) -> str: View Source

    539    def characterset_sql(self, expression: exp.CharacterSet) -> str:
    540        if isinstance(expression.parent, exp.Cast):
    541            return f"CHAR CHARACTER SET {self.sql(expression, 'this')}"
    542        default = "DEFAULT " if expression.args.get("default") else ""
    543        return f"{default}CHARACTER SET={self.sql(expression, 'this')}"

def column_sql(self, expression: sqlglot.expressions.Column) -> str: View Source

    545    def column_sql(self, expression: exp.Column) -> str:
    546        return ".".join(
    547            self.sql(part)
    548            for part in (
    549                expression.args.get("catalog"),
    550                expression.args.get("db"),
    551                expression.args.get("table"),
    552                expression.args.get("this"),
    553            )
    554            if part
    555        )

def columnposition_sql(self, expression: sqlglot.expressions.ColumnPosition) -> str: View Source

    557    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
    558        this = self.sql(expression, "this")
    559        this = f" {this}" if this else ""
    560        position = self.sql(expression, "position")
    561        return f"{position}{this}"

def columndef_sql(self, expression: sqlglot.expressions.ColumnDef, sep: str = ' ') -> str: View Source

    563    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
    564        column = self.sql(expression, "this")
    565        kind = self.sql(expression, "kind")
    566        constraints = self.expressions(expression, key="constraints", sep=" ", flat=True)
    567        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
    568        kind = f"{sep}{kind}" if kind else ""
    569        constraints = f" {constraints}" if constraints else ""
    570        position = self.sql(expression, "position")
    571        position = f" {position}" if position else ""
    572
    573        return f"{exists}{column}{kind}{constraints}{position}"

def columnconstraint_sql(self, expression: sqlglot.expressions.ColumnConstraint) -> str: View Source

    575    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
    576        this = self.sql(expression, "this")
    577        kind_sql = self.sql(expression, "kind").strip()
    578        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql

def autoincrementcolumnconstraint_sql(self, _) -> str: View Source

    580    def autoincrementcolumnconstraint_sql(self, _) -> str:
    581        return self.token_sql(TokenType.AUTO_INCREMENT)

def compresscolumnconstraint_sql(self, expression: sqlglot.expressions.CompressColumnConstraint) -> str: View Source

    583    def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str:
    584        if isinstance(expression.this, list):
    585            this = self.wrap(self.expressions(expression, key="this", flat=True))
    586        else:
    587            this = self.sql(expression, "this")
    588
    589        return f"COMPRESS {this}"

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

    591    def generatedasidentitycolumnconstraint_sql(
    592        self, expression: exp.GeneratedAsIdentityColumnConstraint
    593    ) -> str:
    594        this = ""
    595        if expression.this is not None:
    596            on_null = "ON NULL " if expression.args.get("on_null") else ""
    597            this = " ALWAYS " if expression.this else f" BY DEFAULT {on_null}"
    598
    599        start = expression.args.get("start")
    600        start = f"START WITH {start}" if start else ""
    601        increment = expression.args.get("increment")
    602        increment = f" INCREMENT BY {increment}" if increment else ""
    603        minvalue = expression.args.get("minvalue")
    604        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    605        maxvalue = expression.args.get("maxvalue")
    606        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    607        cycle = expression.args.get("cycle")
    608        cycle_sql = ""
    609
    610        if cycle is not None:
    611            cycle_sql = f"{' NO' if not cycle else ''} CYCLE"
    612            cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql
    613
    614        sequence_opts = ""
    615        if start or increment or cycle_sql:
    616            sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}"
    617            sequence_opts = f" ({sequence_opts.strip()})"
    618
    619        expr = self.sql(expression, "expression")
    620        expr = f"({expr})" if expr else "IDENTITY"
    621
    622        return f"GENERATED{this}AS {expr}{sequence_opts}"

def notnullcolumnconstraint_sql(self, expression: sqlglot.expressions.NotNullColumnConstraint) -> str: View Source

    624    def notnullcolumnconstraint_sql(self, expression: exp.NotNullColumnConstraint) -> str:
    625        return f"{'' if expression.args.get('allow_null') else 'NOT '}NULL"

def primarykeycolumnconstraint_sql(self, expression: sqlglot.expressions.PrimaryKeyColumnConstraint) -> str: View Source

    627    def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str:
    628        desc = expression.args.get("desc")
    629        if desc is not None:
    630            return f"PRIMARY KEY{' DESC' if desc else ' ASC'}"
    631        return f"PRIMARY KEY"

def uniquecolumnconstraint_sql(self, expression: sqlglot.expressions.UniqueColumnConstraint) -> str: View Source

    633    def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str:
    634        this = self.sql(expression, "this")
    635        this = f" {this}" if this else ""
    636        return f"UNIQUE{this}"

def createable_sql( self, expression: sqlglot.expressions.Create, locations: dict[sqlglot.expressions.Properties.Location, list[sqlglot.expressions.Property]]) -> str: View Source

    638    def createable_sql(
    639        self, expression: exp.Create, locations: dict[exp.Properties.Location, list[exp.Property]]
    640    ) -> str:
    641        return self.sql(expression, "this")

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

    643    def create_sql(self, expression: exp.Create) -> str:
    644        kind = self.sql(expression, "kind").upper()
    645        properties = expression.args.get("properties")
    646        properties_locs = self.locate_properties(properties) if properties else {}
    647
    648        this = self.createable_sql(expression, properties_locs)
    649
    650        properties_sql = ""
    651        if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get(
    652            exp.Properties.Location.POST_WITH
    653        ):
    654            properties_sql = self.sql(
    655                exp.Properties(
    656                    expressions=[
    657                        *properties_locs[exp.Properties.Location.POST_SCHEMA],
    658                        *properties_locs[exp.Properties.Location.POST_WITH],
    659                    ]
    660                )
    661            )
    662
    663        begin = " BEGIN" if expression.args.get("begin") else ""
    664        expression_sql = self.sql(expression, "expression")
    665        if expression_sql:
    666            expression_sql = f"{begin}{self.sep()}{expression_sql}"
    667
    668            if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return):
    669                if properties_locs.get(exp.Properties.Location.POST_ALIAS):
    670                    postalias_props_sql = self.properties(
    671                        exp.Properties(
    672                            expressions=properties_locs[exp.Properties.Location.POST_ALIAS]
    673                        ),
    674                        wrapped=False,
    675                    )
    676                    expression_sql = f" AS {postalias_props_sql}{expression_sql}"
    677                else:
    678                    expression_sql = f" AS{expression_sql}"
    679
    680        postindex_props_sql = ""
    681        if properties_locs.get(exp.Properties.Location.POST_INDEX):
    682            postindex_props_sql = self.properties(
    683                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]),
    684                wrapped=False,
    685                prefix=" ",
    686            )
    687
    688        indexes = self.expressions(expression, key="indexes", indent=False, sep=" ")
    689        indexes = f" {indexes}" if indexes else ""
    690        index_sql = indexes + postindex_props_sql
    691
    692        replace = " OR REPLACE" if expression.args.get("replace") else ""
    693        unique = " UNIQUE" if expression.args.get("unique") else ""
    694
    695        postcreate_props_sql = ""
    696        if properties_locs.get(exp.Properties.Location.POST_CREATE):
    697            postcreate_props_sql = self.properties(
    698                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]),
    699                sep=" ",
    700                prefix=" ",
    701                wrapped=False,
    702            )
    703
    704        modifiers = "".join((replace, unique, postcreate_props_sql))
    705
    706        postexpression_props_sql = ""
    707        if properties_locs.get(exp.Properties.Location.POST_EXPRESSION):
    708            postexpression_props_sql = self.properties(
    709                exp.Properties(
    710                    expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION]
    711                ),
    712                sep=" ",
    713                prefix=" ",
    714                wrapped=False,
    715            )
    716
    717        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
    718        no_schema_binding = (
    719            " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else ""
    720        )
    721
    722        clone = self.sql(expression, "clone")
    723        clone = f" {clone}" if clone else ""
    724
    725        expression_sql = f"CREATE{modifiers} {kind}{exists_sql} {this}{properties_sql}{expression_sql}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}"
    726        return self.prepend_ctes(expression, expression_sql)

def clone_sql(self, expression: sqlglot.expressions.Clone) -> str: View Source

    728    def clone_sql(self, expression: exp.Clone) -> str:
    729        this = self.sql(expression, "this")
    730        when = self.sql(expression, "when")
    731
    732        if when:
    733            kind = self.sql(expression, "kind")
    734            expr = self.sql(expression, "expression")
    735            return f"CLONE {this} {when} ({kind} => {expr})"
    736
    737        return f"CLONE {this}"

def describe_sql(self, expression: sqlglot.expressions.Describe) -> str: View Source

    739    def describe_sql(self, expression: exp.Describe) -> str:
    740        return f"DESCRIBE {self.sql(expression, 'this')}"

def prepend_ctes(self, expression: sqlglot.expressions.Expression, sql: str) -> str: View Source

    742    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
    743        with_ = self.sql(expression, "with")
    744        if with_:
    745            sql = f"{with_}{self.sep()}{sql}"
    746        return sql

def with_sql(self, expression: sqlglot.expressions.With) -> str: View Source

    748    def with_sql(self, expression: exp.With) -> str:
    749        sql = self.expressions(expression, flat=True)
    750        recursive = "RECURSIVE " if expression.args.get("recursive") else ""
    751
    752        return f"WITH {recursive}{sql}"

def cte_sql(self, expression: sqlglot.expressions.CTE) -> str: View Source

    754    def cte_sql(self, expression: exp.CTE) -> str:
    755        alias = self.sql(expression, "alias")
    756        return f"{alias} AS {self.wrap(expression)}"

def tablealias_sql(self, expression: sqlglot.expressions.TableAlias) -> str: View Source

    758    def tablealias_sql(self, expression: exp.TableAlias) -> str:
    759        alias = self.sql(expression, "this")
    760        columns = self.expressions(expression, key="columns", flat=True)
    761        columns = f"({columns})" if columns else ""
    762        return f"{alias}{columns}"

def bitstring_sql(self, expression: sqlglot.expressions.BitString) -> str: View Source

    764    def bitstring_sql(self, expression: exp.BitString) -> str:
    765        this = self.sql(expression, "this")
    766        if self.BIT_START:
    767            return f"{self.BIT_START}{this}{self.BIT_END}"
    768        return f"{int(this, 2)}"

def hexstring_sql(self, expression: sqlglot.expressions.HexString) -> str: View Source

    770    def hexstring_sql(self, expression: exp.HexString) -> str:
    771        this = self.sql(expression, "this")
    772        if self.HEX_START:
    773            return f"{self.HEX_START}{this}{self.HEX_END}"
    774        return f"{int(this, 16)}"

def bytestring_sql(self, expression: sqlglot.expressions.ByteString) -> str: View Source

    776    def bytestring_sql(self, expression: exp.ByteString) -> str:
    777        this = self.sql(expression, "this")
    778        if self.BYTE_START:
    779            return f"{self.BYTE_START}{this}{self.BYTE_END}"
    780        return this

def rawstring_sql(self, expression: sqlglot.expressions.RawString) -> str: View Source

    782    def rawstring_sql(self, expression: exp.RawString) -> str:
    783        string = expression.this
    784        if self.RAW_START:
    785            return f"{self.RAW_START}{self.escape_str(expression.this)}{self.RAW_END}"
    786        string = self.escape_str(string.replace("\\", "\\\\"))
    787        return f"{self.QUOTE_START}{string}{self.QUOTE_END}"

def datatypesize_sql(self, expression: sqlglot.expressions.DataTypeSize) -> str: View Source

    789    def datatypesize_sql(self, expression: exp.DataTypeSize) -> str:
    790        this = self.sql(expression, "this")
    791        specifier = self.sql(expression, "expression")
    792        specifier = f" {specifier}" if specifier else ""
    793        return f"{this}{specifier}"

def datatype_sql(self, expression: sqlglot.expressions.DataType) -> str: View Source

    795    def datatype_sql(self, expression: exp.DataType) -> str:
    796        type_value = expression.this
    797        type_sql = self.TYPE_MAPPING.get(type_value, type_value.value)
    798        nested = ""
    799        interior = self.expressions(expression, flat=True)
    800        values = ""
    801        if interior:
    802            if expression.args.get("nested"):
    803                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
    804                if expression.args.get("values") is not None:
    805                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
    806                    values = self.expressions(expression, key="values", flat=True)
    807                    values = f"{delimiters[0]}{values}{delimiters[1]}"
    808            else:
    809                nested = f"({interior})"
    810
    811        return f"{type_sql}{nested}{values}"

def directory_sql(self, expression: sqlglot.expressions.Directory) -> str: View Source

    813    def directory_sql(self, expression: exp.Directory) -> str:
    814        local = "LOCAL " if expression.args.get("local") else ""
    815        row_format = self.sql(expression, "row_format")
    816        row_format = f" {row_format}" if row_format else ""
    817        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"

def delete_sql(self, expression: sqlglot.expressions.Delete) -> str: View Source

    819    def delete_sql(self, expression: exp.Delete) -> str:
    820        this = self.sql(expression, "this")
    821        this = f" FROM {this}" if this else ""
    822        using_sql = (
    823            f" USING {self.expressions(expression, key='using', sep=', USING ')}"
    824            if expression.args.get("using")
    825            else ""
    826        )
    827        where_sql = self.sql(expression, "where")
    828        returning = self.sql(expression, "returning")
    829        limit = self.sql(expression, "limit")
    830        sql = f"DELETE{this}{using_sql}{where_sql}{returning}{limit}"
    831        return self.prepend_ctes(expression, sql)

def drop_sql(self, expression: sqlglot.expressions.Drop) -> str: View Source

    833    def drop_sql(self, expression: exp.Drop) -> str:
    834        this = self.sql(expression, "this")
    835        kind = expression.args["kind"]
    836        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    837        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    838        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    839        cascade = " CASCADE" if expression.args.get("cascade") else ""
    840        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
    841        purge = " PURGE" if expression.args.get("purge") else ""
    842        return (
    843            f"DROP{temporary}{materialized} {kind}{exists_sql}{this}{cascade}{constraints}{purge}"
    844        )

def except_sql(self, expression: sqlglot.expressions.Except) -> str: View Source

    846    def except_sql(self, expression: exp.Except) -> str:
    847        return self.prepend_ctes(
    848            expression,
    849            self.set_operation(expression, self.except_op(expression)),
    850        )

def except_op(self, expression: sqlglot.expressions.Except) -> str: View Source

    852    def except_op(self, expression: exp.Except) -> str:
    853        return f"EXCEPT{'' if expression.args.get('distinct') else ' ALL'}"

def fetch_sql(self, expression: sqlglot.expressions.Fetch) -> str: View Source

    855    def fetch_sql(self, expression: exp.Fetch) -> str:
    856        direction = expression.args.get("direction")
    857        direction = f" {direction.upper()}" if direction else ""
    858        count = expression.args.get("count")
    859        count = f" {count}" if count else ""
    860        if expression.args.get("percent"):
    861            count = f"{count} PERCENT"
    862        with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY"
    863        return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}"

def filter_sql(self, expression: sqlglot.expressions.Filter) -> str: View Source

    865    def filter_sql(self, expression: exp.Filter) -> str:
    866        this = self.sql(expression, "this")
    867        where = self.sql(expression, "expression")[1:]  # where has a leading space
    868        return f"{this} FILTER({where})"

def hint_sql(self, expression: sqlglot.expressions.Hint) -> str: View Source

    870    def hint_sql(self, expression: exp.Hint) -> str:
    871        if self.sql(expression, "this"):
    872            self.unsupported("Hints are not supported")
    873        return ""

def index_sql(self, expression: sqlglot.expressions.Index) -> str: View Source

    875    def index_sql(self, expression: exp.Index) -> str:
    876        unique = "UNIQUE " if expression.args.get("unique") else ""
    877        primary = "PRIMARY " if expression.args.get("primary") else ""
    878        amp = "AMP " if expression.args.get("amp") else ""
    879        name = f"{expression.name} " if expression.name else ""
    880        table = self.sql(expression, "table")
    881        table = f"{self.INDEX_ON} {table} " if table else ""
    882        using = self.sql(expression, "using")
    883        using = f"USING {using} " if using else ""
    884        index = "INDEX " if not table else ""
    885        columns = self.expressions(expression, key="columns", flat=True)
    886        columns = f"({columns})" if columns else ""
    887        partition_by = self.expressions(expression, key="partition_by", flat=True)
    888        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
    889        return f"{unique}{primary}{amp}{index}{name}{table}{using}{columns}{partition_by}"

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

    891    def identifier_sql(self, expression: exp.Identifier) -> str:
    892        text = expression.name
    893        lower = text.lower()
    894        text = lower if self.normalize and not expression.quoted else text
    895        text = text.replace(self.IDENTIFIER_END, self._escaped_identifier_end)
    896        if (
    897            expression.quoted
    898            or self.can_identify(text, self.identify)
    899            or lower in self.RESERVED_KEYWORDS
    900            or (not self.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
    901        ):
    902            text = f"{self.IDENTIFIER_START}{text}{self.IDENTIFIER_END}"
    903        return text

def inputoutputformat_sql(self, expression: sqlglot.expressions.InputOutputFormat) -> str: View Source

    905    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    906        input_format = self.sql(expression, "input_format")
    907        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    908        output_format = self.sql(expression, "output_format")
    909        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    910        return self.sep().join((input_format, output_format))

def national_sql(self, expression: sqlglot.expressions.National, prefix: str = 'N') -> str: View Source

    912    def national_sql(self, expression: exp.National, prefix: str = "N") -> str:
    913        string = self.sql(exp.Literal.string(expression.name))
    914        return f"{prefix}{string}"

def partition_sql(self, expression: sqlglot.expressions.Partition) -> str: View Source

    916    def partition_sql(self, expression: exp.Partition) -> str:
    917        return f"PARTITION({self.expressions(expression, flat=True)})"

def properties_sql(self, expression: sqlglot.expressions.Properties) -> str: View Source

    919    def properties_sql(self, expression: exp.Properties) -> str:
    920        root_properties = []
    921        with_properties = []
    922
    923        for p in expression.expressions:
    924            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    925            if p_loc == exp.Properties.Location.POST_WITH:
    926                with_properties.append(p)
    927            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    928                root_properties.append(p)
    929
    930        return self.root_properties(
    931            exp.Properties(expressions=root_properties)
    932        ) + self.with_properties(exp.Properties(expressions=with_properties))

def root_properties(self, properties: sqlglot.expressions.Properties) -> str: View Source

    934    def root_properties(self, properties: exp.Properties) -> str:
    935        if properties.expressions:
    936            return self.sep() + self.expressions(properties, indent=False, sep=" ")
    937        return ""

def properties( self, properties: sqlglot.expressions.Properties, prefix: str = '', sep: str = ', ', suffix: str = '', wrapped: bool = True) -> str: View Source

    939    def properties(
    940        self,
    941        properties: exp.Properties,
    942        prefix: str = "",
    943        sep: str = ", ",
    944        suffix: str = "",
    945        wrapped: bool = True,
    946    ) -> str:
    947        if properties.expressions:
    948            expressions = self.expressions(properties, sep=sep, indent=False)
    949            expressions = self.wrap(expressions) if wrapped else expressions
    950            return f"{prefix}{' ' if prefix and prefix != ' ' else ''}{expressions}{suffix}"
    951        return ""

def with_properties(self, properties: sqlglot.expressions.Properties) -> str: View Source

    953    def with_properties(self, properties: exp.Properties) -> str:
    954        return self.properties(properties, prefix=self.seg("WITH"))

def locate_properties( self, properties: sqlglot.expressions.Properties) -> Dict[sqlglot.expressions.Properties.Location, list[sqlglot.expressions.Property]]: View Source

    956    def locate_properties(
    957        self, properties: exp.Properties
    958    ) -> t.Dict[exp.Properties.Location, list[exp.Property]]:
    959        properties_locs: t.Dict[exp.Properties.Location, list[exp.Property]] = {
    960            key: [] for key in exp.Properties.Location
    961        }
    962
    963        for p in properties.expressions:
    964            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    965            if p_loc == exp.Properties.Location.POST_NAME:
    966                properties_locs[exp.Properties.Location.POST_NAME].append(p)
    967            elif p_loc == exp.Properties.Location.POST_INDEX:
    968                properties_locs[exp.Properties.Location.POST_INDEX].append(p)
    969            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    970                properties_locs[exp.Properties.Location.POST_SCHEMA].append(p)
    971            elif p_loc == exp.Properties.Location.POST_WITH:
    972                properties_locs[exp.Properties.Location.POST_WITH].append(p)
    973            elif p_loc == exp.Properties.Location.POST_CREATE:
    974                properties_locs[exp.Properties.Location.POST_CREATE].append(p)
    975            elif p_loc == exp.Properties.Location.POST_ALIAS:
    976                properties_locs[exp.Properties.Location.POST_ALIAS].append(p)
    977            elif p_loc == exp.Properties.Location.POST_EXPRESSION:
    978                properties_locs[exp.Properties.Location.POST_EXPRESSION].append(p)
    979            elif p_loc == exp.Properties.Location.UNSUPPORTED:
    980                self.unsupported(f"Unsupported property {p.key}")
    981
    982        return properties_locs

def property_sql(self, expression: sqlglot.expressions.Property) -> str: View Source

    984    def property_sql(self, expression: exp.Property) -> str:
    985        property_cls = expression.__class__
    986        if property_cls == exp.Property:
    987            return f"{expression.name}={self.sql(expression, 'value')}"
    988
    989        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    990        if not property_name:
    991            self.unsupported(f"Unsupported property {expression.key}")
    992
    993        return f"{property_name}={self.sql(expression, 'this')}"

def likeproperty_sql(self, expression: sqlglot.expressions.LikeProperty) -> str: View Source

    995    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
    996        options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
    997        options = f" {options}" if options else ""
    998        return f"LIKE {self.sql(expression, 'this')}{options}"

def fallbackproperty_sql(self, expression: sqlglot.expressions.FallbackProperty) -> str: View Source

    1000    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1001        no = "NO " if expression.args.get("no") else ""
    1002        protection = " PROTECTION" if expression.args.get("protection") else ""
    1003        return f"{no}FALLBACK{protection}"

def journalproperty_sql(self, expression: sqlglot.expressions.JournalProperty) -> str: View Source

    1005    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1006        no = "NO " if expression.args.get("no") else ""
    1007        local = expression.args.get("local")
    1008        local = f"{local} " if local else ""
    1009        dual = "DUAL " if expression.args.get("dual") else ""
    1010        before = "BEFORE " if expression.args.get("before") else ""
    1011        after = "AFTER " if expression.args.get("after") else ""
    1012        return f"{no}{local}{dual}{before}{after}JOURNAL"

def freespaceproperty_sql(self, expression: sqlglot.expressions.FreespaceProperty) -> str: View Source

    1014    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1015        freespace = self.sql(expression, "this")
    1016        percent = " PERCENT" if expression.args.get("percent") else ""
    1017        return f"FREESPACE={freespace}{percent}"

def checksumproperty_sql(self, expression: sqlglot.expressions.ChecksumProperty) -> str: View Source

    1019    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1020        if expression.args.get("default"):
    1021            property = "DEFAULT"
    1022        elif expression.args.get("on"):
    1023            property = "ON"
    1024        else:
    1025            property = "OFF"
    1026        return f"CHECKSUM={property}"

def mergeblockratioproperty_sql(self, expression: sqlglot.expressions.MergeBlockRatioProperty) -> str: View Source

    1028    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1029        if expression.args.get("no"):
    1030            return "NO MERGEBLOCKRATIO"
    1031        if expression.args.get("default"):
    1032            return "DEFAULT MERGEBLOCKRATIO"
    1033
    1034        percent = " PERCENT" if expression.args.get("percent") else ""
    1035        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"

def datablocksizeproperty_sql(self, expression: sqlglot.expressions.DataBlocksizeProperty) -> str: View Source

    1037    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1038        default = expression.args.get("default")
    1039        minimum = expression.args.get("minimum")
    1040        maximum = expression.args.get("maximum")
    1041        if default or minimum or maximum:
    1042            if default:
    1043                prop = "DEFAULT"
    1044            elif minimum:
    1045                prop = "MINIMUM"
    1046            else:
    1047                prop = "MAXIMUM"
    1048            return f"{prop} DATABLOCKSIZE"
    1049        units = expression.args.get("units")
    1050        units = f" {units}" if units else ""
    1051        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"

def blockcompressionproperty_sql(self, expression: sqlglot.expressions.BlockCompressionProperty) -> str: View Source

    1053    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1054        autotemp = expression.args.get("autotemp")
    1055        always = expression.args.get("always")
    1056        default = expression.args.get("default")
    1057        manual = expression.args.get("manual")
    1058        never = expression.args.get("never")
    1059
    1060        if autotemp is not None:
    1061            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1062        elif always:
    1063            prop = "ALWAYS"
    1064        elif default:
    1065            prop = "DEFAULT"
    1066        elif manual:
    1067            prop = "MANUAL"
    1068        elif never:
    1069            prop = "NEVER"
    1070        return f"BLOCKCOMPRESSION={prop}"

def isolatedloadingproperty_sql(self, expression: sqlglot.expressions.IsolatedLoadingProperty) -> str: View Source

    1072    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1073        no = expression.args.get("no")
    1074        no = " NO" if no else ""
    1075        concurrent = expression.args.get("concurrent")
    1076        concurrent = " CONCURRENT" if concurrent else ""
    1077
    1078        for_ = ""
    1079        if expression.args.get("for_all"):
    1080            for_ = " FOR ALL"
    1081        elif expression.args.get("for_insert"):
    1082            for_ = " FOR INSERT"
    1083        elif expression.args.get("for_none"):
    1084            for_ = " FOR NONE"
    1085        return f"WITH{no}{concurrent} ISOLATED LOADING{for_}"

def lockingproperty_sql(self, expression: sqlglot.expressions.LockingProperty) -> str: View Source

    1087    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1088        kind = expression.args.get("kind")
    1089        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1090        for_or_in = expression.args.get("for_or_in")
    1091        lock_type = expression.args.get("lock_type")
    1092        override = " OVERRIDE" if expression.args.get("override") else ""
    1093        return f"LOCKING {kind}{this} {for_or_in} {lock_type}{override}"

def withdataproperty_sql(self, expression: sqlglot.expressions.WithDataProperty) -> str: View Source

    1095    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1096        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1097        statistics = expression.args.get("statistics")
    1098        statistics_sql = ""
    1099        if statistics is not None:
    1100            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1101        return f"{data_sql}{statistics_sql}"

def insert_sql(self, expression: sqlglot.expressions.Insert) -> str: View Source

    1103    def insert_sql(self, expression: exp.Insert) -> str:
    1104        overwrite = expression.args.get("overwrite")
    1105
    1106        if isinstance(expression.this, exp.Directory):
    1107            this = " OVERWRITE" if overwrite else " INTO"
    1108        else:
    1109            this = " OVERWRITE TABLE" if overwrite else " INTO"
    1110
    1111        alternative = expression.args.get("alternative")
    1112        alternative = f" OR {alternative}" if alternative else ""
    1113        this = f"{this} {self.sql(expression, 'this')}"
    1114
    1115        exists = " IF EXISTS" if expression.args.get("exists") else ""
    1116        partition_sql = (
    1117            f" {self.sql(expression, 'partition')}" if expression.args.get("partition") else ""
    1118        )
    1119        where = self.sql(expression, "where")
    1120        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
    1121        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
    1122        conflict = self.sql(expression, "conflict")
    1123        returning = self.sql(expression, "returning")
    1124        sql = f"INSERT{alternative}{this}{exists}{partition_sql}{where}{expression_sql}{conflict}{returning}"
    1125        return self.prepend_ctes(expression, sql)

def intersect_sql(self, expression: sqlglot.expressions.Intersect) -> str: View Source

    1127    def intersect_sql(self, expression: exp.Intersect) -> str:
    1128        return self.prepend_ctes(
    1129            expression,
    1130            self.set_operation(expression, self.intersect_op(expression)),
    1131        )

def intersect_op(self, expression: sqlglot.expressions.Intersect) -> str: View Source

    1133    def intersect_op(self, expression: exp.Intersect) -> str:
    1134        return f"INTERSECT{'' if expression.args.get('distinct') else ' ALL'}"

def introducer_sql(self, expression: sqlglot.expressions.Introducer) -> str: View Source

    1136    def introducer_sql(self, expression: exp.Introducer) -> str:
    1137        return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}"

def pseudotype_sql(self, expression: sqlglot.expressions.PseudoType) -> str: View Source

    1139    def pseudotype_sql(self, expression: exp.PseudoType) -> str:
    1140        return expression.name.upper()

def onconflict_sql(self, expression: sqlglot.expressions.OnConflict) -> str: View Source

    1142    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1143        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1144        constraint = self.sql(expression, "constraint")
    1145        if constraint:
    1146            constraint = f"ON CONSTRAINT {constraint}"
    1147        key = self.expressions(expression, key="key", flat=True)
    1148        do = "" if expression.args.get("duplicate") else " DO "
    1149        nothing = "NOTHING" if expression.args.get("nothing") else ""
    1150        expressions = self.expressions(expression, flat=True)
    1151        if expressions:
    1152            expressions = f"UPDATE SET {expressions}"
    1153        return f"{self.seg(conflict)} {constraint}{key}{do}{nothing}{expressions}"

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

    1155    def returning_sql(self, expression: exp.Returning) -> str:
    1156        return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}"

def rowformatdelimitedproperty_sql(self, expression: sqlglot.expressions.RowFormatDelimitedProperty) -> str: View Source

    1158    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1159        fields = expression.args.get("fields")
    1160        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1161        escaped = expression.args.get("escaped")
    1162        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1163        items = expression.args.get("collection_items")
    1164        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1165        keys = expression.args.get("map_keys")
    1166        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1167        lines = expression.args.get("lines")
    1168        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1169        null = expression.args.get("null")
    1170        null = f" NULL DEFINED AS {null}" if null else ""
    1171        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"

def withtablehint_sql(self, expression: sqlglot.expressions.WithTableHint) -> str: View Source

    1173    def withtablehint_sql(self, expression: exp.WithTableHint) -> str:
    1174        return f"WITH ({self.expressions(expression, flat=True)})"

def indextablehint_sql(self, expression: sqlglot.expressions.IndexTableHint) -> str: View Source

    1176    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1177        this = f"{self.sql(expression, 'this')} INDEX"
    1178        target = self.sql(expression, "target")
    1179        target = f" FOR {target}" if target else ""
    1180        return f"{this}{target} ({self.expressions(expression, flat=True)})"

def table_sql(self, expression: sqlglot.expressions.Table, sep: str = ' AS ') -> str: View Source

    1182    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1183        table = ".".join(
    1184            part
    1185            for part in [
    1186                self.sql(expression, "catalog"),
    1187                self.sql(expression, "db"),
    1188                self.sql(expression, "this"),
    1189            ]
    1190            if part
    1191        )
    1192
    1193        alias = self.sql(expression, "alias")
    1194        alias = f"{sep}{alias}" if alias else ""
    1195        hints = self.expressions(expression, key="hints", sep=" ")
    1196        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
    1197        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    1198        pivots = f" {pivots}" if pivots else ""
    1199        joins = self.expressions(expression, key="joins", sep="")
    1200        laterals = self.expressions(expression, key="laterals", sep="")
    1201        system_time = expression.args.get("system_time")
    1202        system_time = f" {self.sql(expression, 'system_time')}" if system_time else ""
    1203
    1204        return f"{table}{system_time}{alias}{hints}{pivots}{joins}{laterals}"

def tablesample_sql( self, expression: sqlglot.expressions.TableSample, seed_prefix: str = 'SEED', sep=' AS ') -> str: View Source

    1206    def tablesample_sql(
    1207        self, expression: exp.TableSample, seed_prefix: str = "SEED", sep=" AS "
    1208    ) -> str:
    1209        if self.ALIAS_POST_TABLESAMPLE and expression.this.alias:
    1210            table = expression.this.copy()
    1211            table.set("alias", None)
    1212            this = self.sql(table)
    1213            alias = f"{sep}{self.sql(expression.this, 'alias')}"
    1214        else:
    1215            this = self.sql(expression, "this")
    1216            alias = ""
    1217        method = self.sql(expression, "method")
    1218        method = f"{method.upper()} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    1219        numerator = self.sql(expression, "bucket_numerator")
    1220        denominator = self.sql(expression, "bucket_denominator")
    1221        field = self.sql(expression, "bucket_field")
    1222        field = f" ON {field}" if field else ""
    1223        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    1224        percent = self.sql(expression, "percent")
    1225        percent = f"{percent} PERCENT" if percent else ""
    1226        rows = self.sql(expression, "rows")
    1227        rows = f"{rows} ROWS" if rows else ""
    1228        size = self.sql(expression, "size")
    1229        if size and self.TABLESAMPLE_SIZE_IS_PERCENT:
    1230            size = f"{size} PERCENT"
    1231        seed = self.sql(expression, "seed")
    1232        seed = f" {seed_prefix} ({seed})" if seed else ""
    1233        kind = expression.args.get("kind", "TABLESAMPLE")
    1234        return f"{this} {kind} {method}({bucket}{percent}{rows}{size}){seed}{alias}"

def pivot_sql(self, expression: sqlglot.expressions.Pivot) -> str: View Source

    1236    def pivot_sql(self, expression: exp.Pivot) -> str:
    1237        expressions = self.expressions(expression, flat=True)
    1238
    1239        if expression.this:
    1240            this = self.sql(expression, "this")
    1241            on = f"{self.seg('ON')} {expressions}"
    1242            using = self.expressions(expression, key="using", flat=True)
    1243            using = f"{self.seg('USING')} {using}" if using else ""
    1244            group = self.sql(expression, "group")
    1245            return f"PIVOT {this}{on}{using}{group}"
    1246
    1247        alias = self.sql(expression, "alias")
    1248        alias = f" AS {alias}" if alias else ""
    1249        unpivot = expression.args.get("unpivot")
    1250        direction = "UNPIVOT" if unpivot else "PIVOT"
    1251        field = self.sql(expression, "field")
    1252        return f"{direction}({expressions} FOR {field}){alias}"

def tuple_sql(self, expression: sqlglot.expressions.Tuple) -> str: View Source

    1254    def tuple_sql(self, expression: exp.Tuple) -> str:
    1255        return f"({self.expressions(expression, flat=True)})"

def update_sql(self, expression: sqlglot.expressions.Update) -> str: View Source

    1257    def update_sql(self, expression: exp.Update) -> str:
    1258        this = self.sql(expression, "this")
    1259        set_sql = self.expressions(expression, flat=True)
    1260        from_sql = self.sql(expression, "from")
    1261        where_sql = self.sql(expression, "where")
    1262        returning = self.sql(expression, "returning")
    1263        limit = self.sql(expression, "limit")
    1264        sql = f"UPDATE {this} SET {set_sql}{from_sql}{where_sql}{returning}{limit}"
    1265        return self.prepend_ctes(expression, sql)

def values_sql(self, expression: sqlglot.expressions.Values) -> str: View Source

    1267    def values_sql(self, expression: exp.Values) -> str:
    1268        args = self.expressions(expression)
    1269        alias = self.sql(expression, "alias")
    1270        values = f"VALUES{self.seg('')}{args}"
    1271        values = (
    1272            f"({values})"
    1273            if self.WRAP_DERIVED_VALUES and (alias or isinstance(expression.parent, exp.From))
    1274            else values
    1275        )
    1276        return f"{values} AS {alias}" if alias else values

def var_sql(self, expression: sqlglot.expressions.Var) -> str: View Source

    1278    def var_sql(self, expression: exp.Var) -> str:
    1279        return self.sql(expression, "this")

def into_sql(self, expression: sqlglot.expressions.Into) -> str: View Source

    1281    def into_sql(self, expression: exp.Into) -> str:
    1282        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    1283        unlogged = " UNLOGGED" if expression.args.get("unlogged") else ""
    1284        return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"

def from_sql(self, expression: sqlglot.expressions.From) -> str: View Source

    1286    def from_sql(self, expression: exp.From) -> str:
    1287        return f"{self.seg('FROM')} {self.sql(expression, 'this')}"

def group_sql(self, expression: sqlglot.expressions.Group) -> str: View Source

    1289    def group_sql(self, expression: exp.Group) -> str:
    1290        group_by = self.op_expressions("GROUP BY", expression)
    1291        grouping_sets = self.expressions(expression, key="grouping_sets", indent=False)
    1292        grouping_sets = (
    1293            f"{self.seg('GROUPING SETS')} {self.wrap(grouping_sets)}" if grouping_sets else ""
    1294        )
    1295
    1296        cube = expression.args.get("cube", [])
    1297        if seq_get(cube, 0) is True:
    1298            return f"{group_by}{self.seg('WITH CUBE')}"
    1299        else:
    1300            cube_sql = self.expressions(expression, key="cube", indent=False)
    1301            cube_sql = f"{self.seg('CUBE')} {self.wrap(cube_sql)}" if cube_sql else ""
    1302
    1303        rollup = expression.args.get("rollup", [])
    1304        if seq_get(rollup, 0) is True:
    1305            return f"{group_by}{self.seg('WITH ROLLUP')}"
    1306        else:
    1307            rollup_sql = self.expressions(expression, key="rollup", indent=False)
    1308            rollup_sql = f"{self.seg('ROLLUP')} {self.wrap(rollup_sql)}" if rollup_sql else ""
    1309
    1310        groupings = csv(
    1311            grouping_sets,
    1312            cube_sql,
    1313            rollup_sql,
    1314            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    1315            sep=self.GROUPINGS_SEP,
    1316        )
    1317
    1318        if expression.args.get("expressions") and groupings:
    1319            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    1320
    1321        return f"{group_by}{groupings}"

def having_sql(self, expression: sqlglot.expressions.Having) -> str: View Source

    1323    def having_sql(self, expression: exp.Having) -> str:
    1324        this = self.indent(self.sql(expression, "this"))
    1325        return f"{self.seg('HAVING')}{self.sep()}{this}"

def join_sql(self, expression: sqlglot.expressions.Join) -> str: View Source

    1327    def join_sql(self, expression: exp.Join) -> str:
    1328        op_sql = " ".join(
    1329            op
    1330            for op in (
    1331                expression.method,
    1332                "GLOBAL" if expression.args.get("global") else None,
    1333                expression.side,
    1334                expression.kind,
    1335                expression.hint if self.JOIN_HINTS else None,
    1336            )
    1337            if op
    1338        )
    1339        on_sql = self.sql(expression, "on")
    1340        using = expression.args.get("using")
    1341
    1342        if not on_sql and using:
    1343            on_sql = csv(*(self.sql(column) for column in using))
    1344
    1345        this_sql = self.sql(expression, "this")
    1346
    1347        if on_sql:
    1348            on_sql = self.indent(on_sql, skip_first=True)
    1349            space = self.seg(" " * self.pad) if self.pretty else " "
    1350            if using:
    1351                on_sql = f"{space}USING ({on_sql})"
    1352            else:
    1353                on_sql = f"{space}ON {on_sql}"
    1354        elif not op_sql:
    1355            return f", {this_sql}"
    1356
    1357        op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    1358        return f"{self.seg(op_sql)} {this_sql}{on_sql}"

def lambda_sql( self, expression: sqlglot.expressions.Lambda, arrow_sep: str = '->') -> str: View Source

    1360    def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->") -> str:
    1361        args = self.expressions(expression, flat=True)
    1362        args = f"({args})" if len(args.split(",")) > 1 else args
    1363        return f"{args} {arrow_sep} {self.sql(expression, 'this')}"

def lateral_sql(self, expression: sqlglot.expressions.Lateral) -> str: View Source

    1365    def lateral_sql(self, expression: exp.Lateral) -> str:
    1366        this = self.sql(expression, "this")
    1367
    1368        if isinstance(expression.this, exp.Subquery):
    1369            return f"LATERAL {this}"
    1370
    1371        if expression.args.get("view"):
    1372            alias = expression.args["alias"]
    1373            columns = self.expressions(alias, key="columns", flat=True)
    1374            table = f" {alias.name}" if alias.name else ""
    1375            columns = f" AS {columns}" if columns else ""
    1376            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    1377            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    1378
    1379        alias = self.sql(expression, "alias")
    1380        alias = f" AS {alias}" if alias else ""
    1381        return f"LATERAL {this}{alias}"

def limit_sql(self, expression: sqlglot.expressions.Limit) -> str: View Source

    1383    def limit_sql(self, expression: exp.Limit) -> str:
    1384        this = self.sql(expression, "this")
    1385        args = ", ".join(
    1386            sql
    1387            for sql in (
    1388                self.sql(expression, "offset"),
    1389                self.sql(expression, "expression"),
    1390            )
    1391            if sql
    1392        )
    1393        return f"{this}{self.seg('LIMIT')} {args}"

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

    1395    def offset_sql(self, expression: exp.Offset) -> str:
    1396        this = self.sql(expression, "this")
    1397        return f"{this}{self.seg('OFFSET')} {self.sql(expression, 'expression')}"

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

    1399    def setitem_sql(self, expression: exp.SetItem) -> str:
    1400        kind = self.sql(expression, "kind")
    1401        kind = f"{kind} " if kind else ""
    1402        this = self.sql(expression, "this")
    1403        expressions = self.expressions(expression)
    1404        collate = self.sql(expression, "collate")
    1405        collate = f" COLLATE {collate}" if collate else ""
    1406        global_ = "GLOBAL " if expression.args.get("global") else ""
    1407        return f"{global_}{kind}{this}{expressions}{collate}"

def set_sql(self, expression: sqlglot.expressions.Set) -> str: View Source

    1409    def set_sql(self, expression: exp.Set) -> str:
    1410        expressions = (
    1411            f" {self.expressions(expression, flat=True)}" if expression.expressions else ""
    1412        )
    1413        tag = " TAG" if expression.args.get("tag") else ""
    1414        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"

def pragma_sql(self, expression: sqlglot.expressions.Pragma) -> str: View Source

    1416    def pragma_sql(self, expression: exp.Pragma) -> str:
    1417        return f"PRAGMA {self.sql(expression, 'this')}"

def lock_sql(self, expression: sqlglot.expressions.Lock) -> str: View Source

    1419    def lock_sql(self, expression: exp.Lock) -> str:
    1420        if not self.LOCKING_READS_SUPPORTED:
    1421            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    1422            return ""
    1423
    1424        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    1425        expressions = self.expressions(expression, flat=True)
    1426        expressions = f" OF {expressions}" if expressions else ""
    1427        wait = expression.args.get("wait")
    1428
    1429        if wait is not None:
    1430            if isinstance(wait, exp.Literal):
    1431                wait = f" WAIT {self.sql(wait)}"
    1432            else:
    1433                wait = " NOWAIT" if wait else " SKIP LOCKED"
    1434
    1435        return f"{lock_type}{expressions}{wait or ''}"

def literal_sql(self, expression: sqlglot.expressions.Literal) -> str: View Source

    1437    def literal_sql(self, expression: exp.Literal) -> str:
    1438        text = expression.this or ""
    1439        if expression.is_string:
    1440            text = f"{self.QUOTE_START}{self.escape_str(text)}{self.QUOTE_END}"
    1441        return text

def escape_str(self, text: str) -> str: View Source

    1443    def escape_str(self, text: str) -> str:
    1444        text = text.replace(self.QUOTE_END, self._escaped_quote_end)
    1445        if self.pretty:
    1446            text = text.replace("\n", self.SENTINEL_LINE_BREAK)
    1447        return text

def loaddata_sql(self, expression: sqlglot.expressions.LoadData) -> str: View Source

    1449    def loaddata_sql(self, expression: exp.LoadData) -> str:
    1450        local = " LOCAL" if expression.args.get("local") else ""
    1451        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    1452        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    1453        this = f" INTO TABLE {self.sql(expression, 'this')}"
    1454        partition = self.sql(expression, "partition")
    1455        partition = f" {partition}" if partition else ""
    1456        input_format = self.sql(expression, "input_format")
    1457        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    1458        serde = self.sql(expression, "serde")
    1459        serde = f" SERDE {serde}" if serde else ""
    1460        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"

def null_sql(self, *_) -> str: View Source

    1462    def null_sql(self, *_) -> str:
    1463        return "NULL"

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

    1465    def boolean_sql(self, expression: exp.Boolean) -> str:
    1466        return "TRUE" if expression.this else "FALSE"

def order_sql(self, expression: sqlglot.expressions.Order, flat: bool = False) -> str: View Source

    1468    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    1469        this = self.sql(expression, "this")
    1470        this = f"{this} " if this else this
    1471        return self.op_expressions(f"{this}ORDER BY", expression, flat=this or flat)  # type: ignore

def cluster_sql(self, expression: sqlglot.expressions.Cluster) -> str: View Source

    1473    def cluster_sql(self, expression: exp.Cluster) -> str:
    1474        return self.op_expressions("CLUSTER BY", expression)

def distribute_sql(self, expression: sqlglot.expressions.Distribute) -> str: View Source

    1476    def distribute_sql(self, expression: exp.Distribute) -> str:
    1477        return self.op_expressions("DISTRIBUTE BY", expression)

def sort_sql(self, expression: sqlglot.expressions.Sort) -> str: View Source

    1479    def sort_sql(self, expression: exp.Sort) -> str:
    1480        return self.op_expressions("SORT BY", expression)

def ordered_sql(self, expression: sqlglot.expressions.Ordered) -> str: View Source

    1482    def ordered_sql(self, expression: exp.Ordered) -> str:
    1483        desc = expression.args.get("desc")
    1484        asc = not desc
    1485
    1486        nulls_first = expression.args.get("nulls_first")
    1487        nulls_last = not nulls_first
    1488        nulls_are_large = self.NULL_ORDERING == "nulls_are_large"
    1489        nulls_are_small = self.NULL_ORDERING == "nulls_are_small"
    1490        nulls_are_last = self.NULL_ORDERING == "nulls_are_last"
    1491
    1492        sort_order = " DESC" if desc else ""
    1493        nulls_sort_change = ""
    1494        if nulls_first and (
    1495            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
    1496        ):
    1497            nulls_sort_change = " NULLS FIRST"
    1498        elif (
    1499            nulls_last
    1500            and ((asc and nulls_are_small) or (desc and nulls_are_large))
    1501            and not nulls_are_last
    1502        ):
    1503            nulls_sort_change = " NULLS LAST"
    1504
    1505        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
    1506            self.unsupported(
    1507                "Sorting in an ORDER BY on NULLS FIRST/NULLS LAST is not supported by this dialect"
    1508            )
    1509            nulls_sort_change = ""
    1510
    1511        return f"{self.sql(expression, 'this')}{sort_order}{nulls_sort_change}"

def matchrecognize_sql(self, expression: sqlglot.expressions.MatchRecognize) -> str: View Source

    1513    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    1514        partition = self.partition_by_sql(expression)
    1515        order = self.sql(expression, "order")
    1516        measures = self.expressions(expression, key="measures")
    1517        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    1518        rows = self.sql(expression, "rows")
    1519        rows = self.seg(rows) if rows else ""
    1520        after = self.sql(expression, "after")
    1521        after = self.seg(after) if after else ""
    1522        pattern = self.sql(expression, "pattern")
    1523        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    1524        definition_sqls = [
    1525            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    1526            for definition in expression.args.get("define", [])
    1527        ]
    1528        definitions = self.expressions(sqls=definition_sqls)
    1529        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    1530        body = "".join(
    1531            (
    1532                partition,
    1533                order,
    1534                measures,
    1535                rows,
    1536                after,
    1537                pattern,
    1538                define,
    1539            )
    1540        )
    1541        alias = self.sql(expression, "alias")
    1542        alias = f" {alias}" if alias else ""
    1543        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"

def query_modifiers(self, expression: sqlglot.expressions.Expression, *sqls: str) -> str: View Source

    1545    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    1546        limit: t.Optional[exp.Fetch | exp.Limit] = expression.args.get("limit")
    1547
    1548        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    1549            limit = exp.Limit(expression=limit.args.get("count"))
    1550        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    1551            limit = exp.Fetch(direction="FIRST", count=limit.expression)
    1552
    1553        fetch = isinstance(limit, exp.Fetch)
    1554
    1555        return csv(
    1556            *sqls,
    1557            *[self.sql(join) for join in expression.args.get("joins") or []],
    1558            self.sql(expression, "match"),
    1559            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    1560            self.sql(expression, "where"),
    1561            self.sql(expression, "group"),
    1562            self.sql(expression, "having"),
    1563            *self.after_having_modifiers(expression),
    1564            self.sql(expression, "order"),
    1565            *self.offset_limit_modifiers(expression, fetch, limit),
    1566            *self.after_limit_modifiers(expression),
    1567            sep="",
    1568        )

def offset_limit_modifiers( self, expression: sqlglot.expressions.Expression, fetch: bool, limit: Union[sqlglot.expressions.Fetch, sqlglot.expressions.Limit, NoneType]) -> List[str]: View Source

    1570    def offset_limit_modifiers(
    1571        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    1572    ) -> t.List[str]:
    1573        return [
    1574            self.sql(expression, "offset") if fetch else self.sql(limit),
    1575            self.sql(limit) if fetch else self.sql(expression, "offset"),
    1576        ]

def after_having_modifiers(self, expression: sqlglot.expressions.Expression) -> List[str]: View Source

    1578    def after_having_modifiers(self, expression: exp.Expression) -> t.List[str]:
    1579        return [
    1580            self.sql(expression, "qualify"),
    1581            self.seg("WINDOW ") + self.expressions(expression, key="windows", flat=True)
    1582            if expression.args.get("windows")
    1583            else "",
    1584        ]

def after_limit_modifiers(self, expression: sqlglot.expressions.Expression) -> List[str]: View Source

    1586    def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]:
    1587        locks = self.expressions(expression, key="locks", sep=" ")
    1588        locks = f" {locks}" if locks else ""
    1589        return [locks, self.sql(expression, "sample")]

def select_sql(self, expression: sqlglot.expressions.Select) -> str: View Source

    1591    def select_sql(self, expression: exp.Select) -> str:
    1592        hint = self.sql(expression, "hint")
    1593        distinct = self.sql(expression, "distinct")
    1594        distinct = f" {distinct}" if distinct else ""
    1595        kind = self.sql(expression, "kind").upper()
    1596        expressions = self.expressions(expression)
    1597
    1598        if kind:
    1599            if kind in self.SELECT_KINDS:
    1600                kind = f" AS {kind}"
    1601            else:
    1602                if kind == "STRUCT":
    1603                    expressions = self.expressions(
    1604                        sqls=[
    1605                            self.sql(
    1606                                exp.Struct(
    1607                                    expressions=[
    1608                                        exp.column(e.output_name).eq(
    1609                                            e.this if isinstance(e, exp.Alias) else e
    1610                                        )
    1611                                        for e in expression.expressions
    1612                                    ]
    1613                                )
    1614                            )
    1615                        ]
    1616                    )
    1617                kind = ""
    1618
    1619        expressions = f"{self.sep()}{expressions}" if expressions else expressions
    1620        sql = self.query_modifiers(
    1621            expression,
    1622            f"SELECT{hint}{distinct}{kind}{expressions}",
    1623            self.sql(expression, "into", comment=False),
    1624            self.sql(expression, "from", comment=False),
    1625        )
    1626        return self.prepend_ctes(expression, sql)

def schema_sql(self, expression: sqlglot.expressions.Schema) -> str: View Source

    1628    def schema_sql(self, expression: exp.Schema) -> str:
    1629        this = self.sql(expression, "this")
    1630        this = f"{this} " if this else ""
    1631        sql = self.schema_columns_sql(expression)
    1632        return f"{this}{sql}"

def schema_columns_sql(self, expression: sqlglot.expressions.Schema) -> str: View Source

    1634    def schema_columns_sql(self, expression: exp.Schema) -> str:
    1635        return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"

def star_sql(self, expression: sqlglot.expressions.Star) -> str: View Source

    1637    def star_sql(self, expression: exp.Star) -> str:
    1638        except_ = self.expressions(expression, key="except", flat=True)
    1639        except_ = f"{self.seg(self.STAR_MAPPING['except'])} ({except_})" if except_ else ""
    1640        replace = self.expressions(expression, key="replace", flat=True)
    1641        replace = f"{self.seg(self.STAR_MAPPING['replace'])} ({replace})" if replace else ""
    1642        return f"*{except_}{replace}"

def parameter_sql(self, expression: sqlglot.expressions.Parameter) -> str: View Source

    1644    def parameter_sql(self, expression: exp.Parameter) -> str:
    1645        this = self.sql(expression, "this")
    1646        this = f"{{{this}}}" if expression.args.get("wrapped") else f"{this}"
    1647        return f"{self.PARAMETER_TOKEN}{this}"

def sessionparameter_sql(self, expression: sqlglot.expressions.SessionParameter) -> str: View Source

    1649    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    1650        this = self.sql(expression, "this")
    1651        kind = expression.text("kind")
    1652        if kind:
    1653            kind = f"{kind}."
    1654        return f"@@{kind}{this}"

def placeholder_sql(self, expression: sqlglot.expressions.Placeholder) -> str: View Source

    1656    def placeholder_sql(self, expression: exp.Placeholder) -> str:
    1657        return f":{expression.name}" if expression.name else "?"

def subquery_sql(self, expression: sqlglot.expressions.Subquery, sep: str = ' AS ') -> str: View Source

    1659    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    1660        alias = self.sql(expression, "alias")
    1661        alias = f"{sep}{alias}" if alias else ""
    1662
    1663        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    1664        pivots = f" {pivots}" if pivots else ""
    1665
    1666        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    1667        return self.prepend_ctes(expression, sql)

def qualify_sql(self, expression: sqlglot.expressions.Qualify) -> str: View Source

    1669    def qualify_sql(self, expression: exp.Qualify) -> str:
    1670        this = self.indent(self.sql(expression, "this"))
    1671        return f"{self.seg('QUALIFY')}{self.sep()}{this}"

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

    1673    def union_sql(self, expression: exp.Union) -> str:
    1674        return self.prepend_ctes(
    1675            expression,
    1676            self.set_operation(expression, self.union_op(expression)),
    1677        )

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

    1679    def union_op(self, expression: exp.Union) -> str:
    1680        kind = " DISTINCT" if self.EXPLICIT_UNION else ""
    1681        kind = kind if expression.args.get("distinct") else " ALL"
    1682        return f"UNION{kind}"

def unnest_sql(self, expression: sqlglot.expressions.Unnest) -> str: View Source

    1684    def unnest_sql(self, expression: exp.Unnest) -> str:
    1685        args = self.expressions(expression, flat=True)
    1686        alias = expression.args.get("alias")
    1687        if alias and self.UNNEST_COLUMN_ONLY:
    1688            columns = alias.columns
    1689            alias = self.sql(columns[0]) if columns else ""
    1690        else:
    1691            alias = self.sql(expression, "alias")
    1692        alias = f" AS {alias}" if alias else alias
    1693        ordinality = " WITH ORDINALITY" if expression.args.get("ordinality") else ""
    1694        offset = expression.args.get("offset")
    1695        offset = f" WITH OFFSET AS {self.sql(offset)}" if offset else ""
    1696        return f"UNNEST({args}){ordinality}{alias}{offset}"

def where_sql(self, expression: sqlglot.expressions.Where) -> str: View Source

    1698    def where_sql(self, expression: exp.Where) -> str:
    1699        this = self.indent(self.sql(expression, "this"))
    1700        return f"{self.seg('WHERE')}{self.sep()}{this}"

def window_sql(self, expression: sqlglot.expressions.Window) -> str: View Source

    1702    def window_sql(self, expression: exp.Window) -> str:
    1703        this = self.sql(expression, "this")
    1704        partition = self.partition_by_sql(expression)
    1705        order = expression.args.get("order")
    1706        order = self.order_sql(order, flat=True) if order else ""
    1707        spec = self.sql(expression, "spec")
    1708        alias = self.sql(expression, "alias")
    1709        over = self.sql(expression, "over") or "OVER"
    1710
    1711        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    1712
    1713        first = expression.args.get("first")
    1714        if first is None:
    1715            first = ""
    1716        else:
    1717            first = "FIRST" if first else "LAST"
    1718
    1719        if not partition and not order and not spec and alias:
    1720            return f"{this} {alias}"
    1721
    1722        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
    1723        return f"{this} ({args})"

def partition_by_sql( self, expression: sqlglot.expressions.Window | sqlglot.expressions.MatchRecognize) -> str: View Source

    1725    def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str:
    1726        partition = self.expressions(expression, key="partition_by", flat=True)
    1727        return f"PARTITION BY {partition}" if partition else ""

def windowspec_sql(self, expression: sqlglot.expressions.WindowSpec) -> str: View Source

    1729    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    1730        kind = self.sql(expression, "kind")
    1731        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    1732        end = (
    1733            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    1734            or "CURRENT ROW"
    1735        )
    1736        return f"{kind} BETWEEN {start} AND {end}"

def withingroup_sql(self, expression: sqlglot.expressions.WithinGroup) -> str: View Source

    1738    def withingroup_sql(self, expression: exp.WithinGroup) -> str:
    1739        this = self.sql(expression, "this")
    1740        expression_sql = self.sql(expression, "expression")[1:]  # order has a leading space
    1741        return f"{this} WITHIN GROUP ({expression_sql})"

def between_sql(self, expression: sqlglot.expressions.Between) -> str: View Source

    1743    def between_sql(self, expression: exp.Between) -> str:
    1744        this = self.sql(expression, "this")
    1745        low = self.sql(expression, "low")
    1746        high = self.sql(expression, "high")
    1747        return f"{this} BETWEEN {low} AND {high}"

def bracket_sql(self, expression: sqlglot.expressions.Bracket) -> str: View Source

    1749    def bracket_sql(self, expression: exp.Bracket) -> str:
    1750        expressions = apply_index_offset(expression.this, expression.expressions, self.INDEX_OFFSET)
    1751        expressions_sql = ", ".join(self.sql(e) for e in expressions)
    1752
    1753        return f"{self.sql(expression, 'this')}[{expressions_sql}]"

def safebracket_sql(self, expression: sqlglot.expressions.SafeBracket) -> str: View Source

    1755    def safebracket_sql(self, expression: exp.SafeBracket) -> str:
    1756        return self.bracket_sql(expression)

def all_sql(self, expression: sqlglot.expressions.All) -> str: View Source

    1758    def all_sql(self, expression: exp.All) -> str:
    1759        return f"ALL {self.wrap(expression)}"

def any_sql(self, expression: sqlglot.expressions.Any) -> str: View Source

    1761    def any_sql(self, expression: exp.Any) -> str:
    1762        this = self.sql(expression, "this")
    1763        if isinstance(expression.this, exp.Subqueryable):
    1764            this = self.wrap(this)
    1765        return f"ANY {this}"

def exists_sql(self, expression: sqlglot.expressions.Exists) -> str: View Source

    1767    def exists_sql(self, expression: exp.Exists) -> str:
    1768        return f"EXISTS{self.wrap(expression)}"

def case_sql(self, expression: sqlglot.expressions.Case) -> str: View Source

    1770    def case_sql(self, expression: exp.Case) -> str:
    1771        this = self.sql(expression, "this")
    1772        statements = [f"CASE {this}" if this else "CASE"]
    1773
    1774        for e in expression.args["ifs"]:
    1775            statements.append(f"WHEN {self.sql(e, 'this')}")
    1776            statements.append(f"THEN {self.sql(e, 'true')}")
    1777
    1778        default = self.sql(expression, "default")
    1779
    1780        if default:
    1781            statements.append(f"ELSE {default}")
    1782
    1783        statements.append("END")
    1784
    1785        if self.pretty and self.text_width(statements) > self.max_text_width:
    1786            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    1787
    1788        return " ".join(statements)

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

    1790    def constraint_sql(self, expression: exp.Constraint) -> str:
    1791        this = self.sql(expression, "this")
    1792        expressions = self.expressions(expression, flat=True)
    1793        return f"CONSTRAINT {this} {expressions}"

def nextvaluefor_sql(self, expression: sqlglot.expressions.NextValueFor) -> str: View Source

    1795    def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str:
    1796        order = expression.args.get("order")
    1797        order = f" OVER ({self.order_sql(order, flat=True)})" if order else ""
    1798        return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}"

def extract_sql(self, expression: sqlglot.expressions.Extract) -> str: View Source

    1800    def extract_sql(self, expression: exp.Extract) -> str:
    1801        this = self.sql(expression, "this")
    1802        expression_sql = self.sql(expression, "expression")
    1803        return f"EXTRACT({this} FROM {expression_sql})"

def trim_sql(self, expression: sqlglot.expressions.Trim) -> str: View Source

    1805    def trim_sql(self, expression: exp.Trim) -> str:
    1806        trim_type = self.sql(expression, "position")
    1807
    1808        if trim_type == "LEADING":
    1809            return self.func("LTRIM", expression.this)
    1810        elif trim_type == "TRAILING":
    1811            return self.func("RTRIM", expression.this)
    1812        else:
    1813            return self.func("TRIM", expression.this, expression.expression)

def safeconcat_sql(self, expression: sqlglot.expressions.SafeConcat) -> str: View Source

    1815    def safeconcat_sql(self, expression: exp.SafeConcat) -> str:
    1816        expressions = expression.expressions
    1817        if self.STRICT_STRING_CONCAT:
    1818            expressions = (exp.cast(e, "text") for e in expressions)
    1819        return self.func("CONCAT", *expressions)

def check_sql(self, expression: sqlglot.expressions.Check) -> str: View Source

    1821    def check_sql(self, expression: exp.Check) -> str:
    1822        this = self.sql(expression, key="this")
    1823        return f"CHECK ({this})"

def foreignkey_sql(self, expression: sqlglot.expressions.ForeignKey) -> str: View Source

    1825    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    1826        expressions = self.expressions(expression, flat=True)
    1827        reference = self.sql(expression, "reference")
    1828        reference = f" {reference}" if reference else ""
    1829        delete = self.sql(expression, "delete")
    1830        delete = f" ON DELETE {delete}" if delete else ""
    1831        update = self.sql(expression, "update")
    1832        update = f" ON UPDATE {update}" if update else ""
    1833        return f"FOREIGN KEY ({expressions}){reference}{delete}{update}"

def primarykey_sql(self, expression: sqlglot.expressions.ForeignKey) -> str: View Source

    1835    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    1836        expressions = self.expressions(expression, flat=True)
    1837        options = self.expressions(expression, key="options", flat=True, sep=" ")
    1838        options = f" {options}" if options else ""
    1839        return f"PRIMARY KEY ({expressions}){options}"

def if_sql(self, expression: sqlglot.expressions.If) -> str: View Source

    1841    def if_sql(self, expression: exp.If) -> str:
    1842        return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false")))

def matchagainst_sql(self, expression: sqlglot.expressions.MatchAgainst) -> str: View Source

    1844    def matchagainst_sql(self, expression: exp.MatchAgainst) -> str:
    1845        modifier = expression.args.get("modifier")
    1846        modifier = f" {modifier}" if modifier else ""
    1847        return f"{self.func('MATCH', *expression.expressions)} AGAINST({self.sql(expression, 'this')}{modifier})"

def jsonkeyvalue_sql(self, expression: sqlglot.expressions.JSONKeyValue) -> str: View Source

    1849    def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str:
    1850        return f"{self.sql(expression, 'this')}: {self.sql(expression, 'expression')}"

def jsonobject_sql(self, expression: sqlglot.expressions.JSONObject) -> str: View Source

    1852    def jsonobject_sql(self, expression: exp.JSONObject) -> str:
    1853        null_handling = expression.args.get("null_handling")
    1854        null_handling = f" {null_handling}" if null_handling else ""
    1855        unique_keys = expression.args.get("unique_keys")
    1856        if unique_keys is not None:
    1857            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    1858        else:
    1859            unique_keys = ""
    1860        return_type = self.sql(expression, "return_type")
    1861        return_type = f" RETURNING {return_type}" if return_type else ""
    1862        format_json = " FORMAT JSON" if expression.args.get("format_json") else ""
    1863        encoding = self.sql(expression, "encoding")
    1864        encoding = f" ENCODING {encoding}" if encoding else ""
    1865        return self.func(
    1866            "JSON_OBJECT",
    1867            *expression.expressions,
    1868            suffix=f"{null_handling}{unique_keys}{return_type}{format_json}{encoding})",
    1869        )

def openjsoncolumndef_sql(self, expression: sqlglot.expressions.OpenJSONColumnDef) -> str: View Source

    1871    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    1872        this = self.sql(expression, "this")
    1873        kind = self.sql(expression, "kind")
    1874        path = self.sql(expression, "path")
    1875        path = f" {path}" if path else ""
    1876        as_json = " AS JSON" if expression.args.get("as_json") else ""
    1877        return f"{this} {kind}{path}{as_json}"

def openjson_sql(self, expression: sqlglot.expressions.OpenJSON) -> str: View Source

    1879    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    1880        this = self.sql(expression, "this")
    1881        path = self.sql(expression, "path")
    1882        path = f", {path}" if path else ""
    1883        expressions = self.expressions(expression)
    1884        with_ = (
    1885            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    1886            if expressions
    1887            else ""
    1888        )
    1889        return f"OPENJSON({this}{path}){with_}"

def in_sql(self, expression: sqlglot.expressions.In) -> str: View Source

    1891    def in_sql(self, expression: exp.In) -> str:
    1892        query = expression.args.get("query")
    1893        unnest = expression.args.get("unnest")
    1894        field = expression.args.get("field")
    1895        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    1896
    1897        if query:
    1898            in_sql = self.wrap(query)
    1899        elif unnest:
    1900            in_sql = self.in_unnest_op(unnest)
    1901        elif field:
    1902            in_sql = self.sql(field)
    1903        else:
    1904            in_sql = f"({self.expressions(expression, flat=True)})"
    1905
    1906        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"

def in_unnest_op(self, unnest: sqlglot.expressions.Unnest) -> str: View Source

    1908    def in_unnest_op(self, unnest: exp.Unnest) -> str:
    1909        return f"(SELECT {self.sql(unnest)})"

def interval_sql(self, expression: sqlglot.expressions.Interval) -> str: View Source

    1911    def interval_sql(self, expression: exp.Interval) -> str:
    1912        unit = self.sql(expression, "unit")
    1913        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    1914            unit = self.TIME_PART_SINGULARS.get(unit.lower(), unit)
    1915        unit = f" {unit}" if unit else ""
    1916
    1917        if self.SINGLE_STRING_INTERVAL:
    1918            this = expression.this.name if expression.this else ""
    1919            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    1920
    1921        this = self.sql(expression, "this")
    1922        if this:
    1923            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    1924            this = f" {this}" if unwrapped else f" ({this})"
    1925
    1926        return f"INTERVAL{this}{unit}"

def return_sql(self, expression: sqlglot.expressions.Return) -> str: View Source

    1928    def return_sql(self, expression: exp.Return) -> str:
    1929        return f"RETURN {self.sql(expression, 'this')}"

def reference_sql(self, expression: sqlglot.expressions.Reference) -> str: View Source

    1931    def reference_sql(self, expression: exp.Reference) -> str:
    1932        this = self.sql(expression, "this")
    1933        expressions = self.expressions(expression, flat=True)
    1934        expressions = f"({expressions})" if expressions else ""
    1935        options = self.expressions(expression, key="options", flat=True, sep=" ")
    1936        options = f" {options}" if options else ""
    1937        return f"REFERENCES {this}{expressions}{options}"

def anonymous_sql(self, expression: sqlglot.expressions.Anonymous) -> str: View Source

    1939    def anonymous_sql(self, expression: exp.Anonymous) -> str:
    1940        return self.func(expression.name, *expression.expressions)

def paren_sql(self, expression: sqlglot.expressions.Paren) -> str: View Source

    1942    def paren_sql(self, expression: exp.Paren) -> str:
    1943        if isinstance(expression.unnest(), exp.Select):
    1944            sql = self.wrap(expression)
    1945        else:
    1946            sql = self.seg(self.indent(self.sql(expression, "this")), sep="")
    1947            sql = f"({sql}{self.seg(')', sep='')}"
    1948
    1949        return self.prepend_ctes(expression, sql)

def neg_sql(self, expression: sqlglot.expressions.Neg) -> str: View Source

    1951    def neg_sql(self, expression: exp.Neg) -> str:
    1952        # This makes sure we don't convert "- - 5" to "--5", which is a comment
    1953        this_sql = self.sql(expression, "this")
    1954        sep = " " if this_sql[0] == "-" else ""
    1955        return f"-{sep}{this_sql}"

def not_sql(self, expression: sqlglot.expressions.Not) -> str: View Source

    1957    def not_sql(self, expression: exp.Not) -> str:
    1958        return f"NOT {self.sql(expression, 'this')}"

def alias_sql(self, expression: sqlglot.expressions.Alias) -> str: View Source

    1960    def alias_sql(self, expression: exp.Alias) -> str:
    1961        alias = self.sql(expression, "alias")
    1962        alias = f" AS {alias}" if alias else ""
    1963        return f"{self.sql(expression, 'this')}{alias}"

def aliases_sql(self, expression: sqlglot.expressions.Aliases) -> str: View Source

    1965    def aliases_sql(self, expression: exp.Aliases) -> str:
    1966        return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})"

def attimezone_sql(self, expression: sqlglot.expressions.AtTimeZone) -> str: View Source

    1968    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    1969        this = self.sql(expression, "this")
    1970        zone = self.sql(expression, "zone")
    1971        return f"{this} AT TIME ZONE {zone}"

def add_sql(self, expression: sqlglot.expressions.Add) -> str: View Source

    1973    def add_sql(self, expression: exp.Add) -> str:
    1974        return self.binary(expression, "+")

def and_sql(self, expression: sqlglot.expressions.And) -> str: View Source

    1976    def and_sql(self, expression: exp.And) -> str:
    1977        return self.connector_sql(expression, "AND")

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

    1979    def connector_sql(self, expression: exp.Connector, op: str) -> str:
    1980        if not self.pretty:
    1981            return self.binary(expression, op)
    1982
    1983        sqls = tuple(
    1984            self.maybe_comment(self.sql(e), e, e.parent.comments or []) if i != 1 else self.sql(e)
    1985            for i, e in enumerate(expression.flatten(unnest=False))
    1986        )
    1987
    1988        sep = "\n" if self.text_width(sqls) > self.max_text_width else " "
    1989        return f"{sep}{op} ".join(sqls)

def bitwiseand_sql(self, expression: sqlglot.expressions.BitwiseAnd) -> str: View Source

    1991    def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str:
    1992        return self.binary(expression, "&")

def bitwiseleftshift_sql(self, expression: sqlglot.expressions.BitwiseLeftShift) -> str: View Source

    1994    def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str:
    1995        return self.binary(expression, "<<")

def bitwisenot_sql(self, expression: sqlglot.expressions.BitwiseNot) -> str: View Source

    1997    def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str:
    1998        return f"~{self.sql(expression, 'this')}"

def bitwiseor_sql(self, expression: sqlglot.expressions.BitwiseOr) -> str: View Source

    2000    def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str:
    2001        return self.binary(expression, "|")

def bitwiserightshift_sql(self, expression: sqlglot.expressions.BitwiseRightShift) -> str: View Source

    2003    def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str:
    2004        return self.binary(expression, ">>")

def bitwisexor_sql(self, expression: sqlglot.expressions.BitwiseXor) -> str: View Source

    2006    def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str:
    2007        return self.binary(expression, "^")

def cast_sql( self, expression: sqlglot.expressions.Cast, safe_prefix: Optional[str] = None) -> str: View Source

    2009    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    2010        format_sql = self.sql(expression, "format")
    2011        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    2012        return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS {self.sql(expression, 'to')}{format_sql})"

def currentdate_sql(self, expression: sqlglot.expressions.CurrentDate) -> str: View Source

    2014    def currentdate_sql(self, expression: exp.CurrentDate) -> str:
    2015        zone = self.sql(expression, "this")
    2016        return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE"

def collate_sql(self, expression: sqlglot.expressions.Collate) -> str: View Source

    2018    def collate_sql(self, expression: exp.Collate) -> str:
    2019        return self.binary(expression, "COLLATE")

def command_sql(self, expression: sqlglot.expressions.Command) -> str: View Source

    2021    def command_sql(self, expression: exp.Command) -> str:
    2022        return f"{self.sql(expression, 'this').upper()} {expression.text('expression').strip()}"

def comment_sql(self, expression: sqlglot.expressions.Comment) -> str: View Source

    2024    def comment_sql(self, expression: exp.Comment) -> str:
    2025        this = self.sql(expression, "this")
    2026        kind = expression.args["kind"]
    2027        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    2028        expression_sql = self.sql(expression, "expression")
    2029        return f"COMMENT{exists_sql}ON {kind} {this} IS {expression_sql}"

def mergetreettlaction_sql(self, expression: sqlglot.expressions.MergeTreeTTLAction) -> str: View Source

    2031    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    2032        this = self.sql(expression, "this")
    2033        delete = " DELETE" if expression.args.get("delete") else ""
    2034        recompress = self.sql(expression, "recompress")
    2035        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    2036        to_disk = self.sql(expression, "to_disk")
    2037        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    2038        to_volume = self.sql(expression, "to_volume")
    2039        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    2040        return f"{this}{delete}{recompress}{to_disk}{to_volume}"

def mergetreettl_sql(self, expression: sqlglot.expressions.MergeTreeTTL) -> str: View Source

    2042    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    2043        where = self.sql(expression, "where")
    2044        group = self.sql(expression, "group")
    2045        aggregates = self.expressions(expression, key="aggregates")
    2046        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    2047
    2048        if not (where or group or aggregates) and len(expression.expressions) == 1:
    2049            return f"TTL {self.expressions(expression, flat=True)}"
    2050
    2051        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"

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

    2053    def transaction_sql(self, expression: exp.Transaction) -> str:
    2054        return "BEGIN"

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

    2056    def commit_sql(self, expression: exp.Commit) -> str:
    2057        chain = expression.args.get("chain")
    2058        if chain is not None:
    2059            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    2060
    2061        return f"COMMIT{chain or ''}"

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

    2063    def rollback_sql(self, expression: exp.Rollback) -> str:
    2064        savepoint = expression.args.get("savepoint")
    2065        savepoint = f" TO {savepoint}" if savepoint else ""
    2066        return f"ROLLBACK{savepoint}"

def altercolumn_sql(self, expression: sqlglot.expressions.AlterColumn) -> str: View Source

    2068    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    2069        this = self.sql(expression, "this")
    2070
    2071        dtype = self.sql(expression, "dtype")
    2072        if dtype:
    2073            collate = self.sql(expression, "collate")
    2074            collate = f" COLLATE {collate}" if collate else ""
    2075            using = self.sql(expression, "using")
    2076            using = f" USING {using}" if using else ""
    2077            return f"ALTER COLUMN {this} TYPE {dtype}{collate}{using}"
    2078
    2079        default = self.sql(expression, "default")
    2080        if default:
    2081            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    2082
    2083        if not expression.args.get("drop"):
    2084            self.unsupported("Unsupported ALTER COLUMN syntax")
    2085
    2086        return f"ALTER COLUMN {this} DROP DEFAULT"

def renametable_sql(self, expression: sqlglot.expressions.RenameTable) -> str: View Source

    2088    def renametable_sql(self, expression: exp.RenameTable) -> str:
    2089        if not self.RENAME_TABLE_WITH_DB:
    2090            # Remove db from tables
    2091            expression = expression.transform(
    2092                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    2093            )
    2094        this = self.sql(expression, "this")
    2095        return f"RENAME TO {this}"

def altertable_sql(self, expression: sqlglot.expressions.AlterTable) -> str: View Source

    2097    def altertable_sql(self, expression: exp.AlterTable) -> str:
    2098        actions = expression.args["actions"]
    2099
    2100        if isinstance(actions[0], exp.ColumnDef):
    2101            actions = self.expressions(expression, key="actions", prefix="ADD COLUMN ")
    2102        elif isinstance(actions[0], exp.Schema):
    2103            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    2104        elif isinstance(actions[0], exp.Delete):
    2105            actions = self.expressions(expression, key="actions", flat=True)
    2106        else:
    2107            actions = self.expressions(expression, key="actions")
    2108
    2109        exists = " IF EXISTS" if expression.args.get("exists") else ""
    2110        return f"ALTER TABLE{exists} {self.sql(expression, 'this')} {actions}"

def droppartition_sql(self, expression: sqlglot.expressions.DropPartition) -> str: View Source

    2112    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    2113        expressions = self.expressions(expression)
    2114        exists = " IF EXISTS " if expression.args.get("exists") else " "
    2115        return f"DROP{exists}{expressions}"

def addconstraint_sql(self, expression: sqlglot.expressions.AddConstraint) -> str: View Source

    2117    def addconstraint_sql(self, expression: exp.AddConstraint) -> str:
    2118        this = self.sql(expression, "this")
    2119        expression_ = self.sql(expression, "expression")
    2120        add_constraint = f"ADD CONSTRAINT {this}" if this else "ADD"
    2121
    2122        enforced = expression.args.get("enforced")
    2123        if enforced is not None:
    2124            return f"{add_constraint} CHECK ({expression_}){' ENFORCED' if enforced else ''}"
    2125
    2126        return f"{add_constraint} {expression_}"

def distinct_sql(self, expression: sqlglot.expressions.Distinct) -> str: View Source

    2128    def distinct_sql(self, expression: exp.Distinct) -> str:
    2129        this = self.expressions(expression, flat=True)
    2130        this = f" {this}" if this else ""
    2131
    2132        on = self.sql(expression, "on")
    2133        on = f" ON {on}" if on else ""
    2134        return f"DISTINCT{this}{on}"

def ignorenulls_sql(self, expression: sqlglot.expressions.IgnoreNulls) -> str: View Source

    2136    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
    2137        return f"{self.sql(expression, 'this')} IGNORE NULLS"

def respectnulls_sql(self, expression: sqlglot.expressions.RespectNulls) -> str: View Source

    2139    def respectnulls_sql(self, expression: exp.RespectNulls) -> str:
    2140        return f"{self.sql(expression, 'this')} RESPECT NULLS"

def intdiv_sql(self, expression: sqlglot.expressions.IntDiv) -> str: View Source

    2142    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    2143        return self.sql(
    2144            exp.Cast(
    2145                this=exp.Div(this=expression.this, expression=expression.expression),
    2146                to=exp.DataType(this=exp.DataType.Type.INT),
    2147            )
    2148        )

def dpipe_sql(self, expression: sqlglot.expressions.DPipe) -> str: View Source

    2150    def dpipe_sql(self, expression: exp.DPipe) -> str:
    2151        return self.binary(expression, "||")

def safedpipe_sql(self, expression: sqlglot.expressions.SafeDPipe) -> str: View Source

    2153    def safedpipe_sql(self, expression: exp.SafeDPipe) -> str:
    2154        if self.STRICT_STRING_CONCAT:
    2155            return self.func("CONCAT", *(exp.cast(e, "text") for e in expression.flatten()))
    2156        return self.dpipe_sql(expression)

def div_sql(self, expression: sqlglot.expressions.Div) -> str: View Source

    2158    def div_sql(self, expression: exp.Div) -> str:
    2159        return self.binary(expression, "/")

def overlaps_sql(self, expression: sqlglot.expressions.Overlaps) -> str: View Source

    2161    def overlaps_sql(self, expression: exp.Overlaps) -> str:
    2162        return self.binary(expression, "OVERLAPS")

def distance_sql(self, expression: sqlglot.expressions.Distance) -> str: View Source

    2164    def distance_sql(self, expression: exp.Distance) -> str:
    2165        return self.binary(expression, "<->")

def dot_sql(self, expression: sqlglot.expressions.Dot) -> str: View Source

    2167    def dot_sql(self, expression: exp.Dot) -> str:
    2168        return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}"

def eq_sql(self, expression: sqlglot.expressions.EQ) -> str: View Source

    2170    def eq_sql(self, expression: exp.EQ) -> str:
    2171        return self.binary(expression, "=")

def escape_sql(self, expression: sqlglot.expressions.Escape) -> str: View Source

    2173    def escape_sql(self, expression: exp.Escape) -> str:
    2174        return self.binary(expression, "ESCAPE")

def glob_sql(self, expression: sqlglot.expressions.Glob) -> str: View Source

    2176    def glob_sql(self, expression: exp.Glob) -> str:
    2177        return self.binary(expression, "GLOB")

def gt_sql(self, expression: sqlglot.expressions.GT) -> str: View Source

    2179    def gt_sql(self, expression: exp.GT) -> str:
    2180        return self.binary(expression, ">")

def gte_sql(self, expression: sqlglot.expressions.GTE) -> str: View Source

    2182    def gte_sql(self, expression: exp.GTE) -> str:
    2183        return self.binary(expression, ">=")

def ilike_sql(self, expression: sqlglot.expressions.ILike) -> str: View Source

    2185    def ilike_sql(self, expression: exp.ILike) -> str:
    2186        return self.binary(expression, "ILIKE")

def ilikeany_sql(self, expression: sqlglot.expressions.ILikeAny) -> str: View Source

    2188    def ilikeany_sql(self, expression: exp.ILikeAny) -> str:
    2189        return self.binary(expression, "ILIKE ANY")

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

    2191    def is_sql(self, expression: exp.Is) -> str:
    2192        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    2193            return self.sql(
    2194                expression.this if expression.expression.this else exp.not_(expression.this)
    2195            )
    2196        return self.binary(expression, "IS")

def like_sql(self, expression: sqlglot.expressions.Like) -> str: View Source

    2198    def like_sql(self, expression: exp.Like) -> str:
    2199        return self.binary(expression, "LIKE")

def likeany_sql(self, expression: sqlglot.expressions.LikeAny) -> str: View Source

    2201    def likeany_sql(self, expression: exp.LikeAny) -> str:
    2202        return self.binary(expression, "LIKE ANY")

def similarto_sql(self, expression: sqlglot.expressions.SimilarTo) -> str: View Source

    2204    def similarto_sql(self, expression: exp.SimilarTo) -> str:
    2205        return self.binary(expression, "SIMILAR TO")

def lt_sql(self, expression: sqlglot.expressions.LT) -> str: View Source

    2207    def lt_sql(self, expression: exp.LT) -> str:
    2208        return self.binary(expression, "<")

def lte_sql(self, expression: sqlglot.expressions.LTE) -> str: View Source

    2210    def lte_sql(self, expression: exp.LTE) -> str:
    2211        return self.binary(expression, "<=")

def mod_sql(self, expression: sqlglot.expressions.Mod) -> str: View Source

    2213    def mod_sql(self, expression: exp.Mod) -> str:
    2214        return self.binary(expression, "%")

def mul_sql(self, expression: sqlglot.expressions.Mul) -> str: View Source

    2216    def mul_sql(self, expression: exp.Mul) -> str:
    2217        return self.binary(expression, "*")

def neq_sql(self, expression: sqlglot.expressions.NEQ) -> str: View Source

    2219    def neq_sql(self, expression: exp.NEQ) -> str:
    2220        return self.binary(expression, "<>")

def nullsafeeq_sql(self, expression: sqlglot.expressions.NullSafeEQ) -> str: View Source

    2222    def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str:
    2223        return self.binary(expression, "IS NOT DISTINCT FROM")

def nullsafeneq_sql(self, expression: sqlglot.expressions.NullSafeNEQ) -> str: View Source

    2225    def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str:
    2226        return self.binary(expression, "IS DISTINCT FROM")

def or_sql(self, expression: sqlglot.expressions.Or) -> str: View Source

    2228    def or_sql(self, expression: exp.Or) -> str:
    2229        return self.connector_sql(expression, "OR")

def slice_sql(self, expression: sqlglot.expressions.Slice) -> str: View Source

    2231    def slice_sql(self, expression: exp.Slice) -> str:
    2232        return self.binary(expression, ":")

def sub_sql(self, expression: sqlglot.expressions.Sub) -> str: View Source

    2234    def sub_sql(self, expression: exp.Sub) -> str:
    2235        return self.binary(expression, "-")

def trycast_sql(self, expression: sqlglot.expressions.TryCast) -> str: View Source

    2237    def trycast_sql(self, expression: exp.TryCast) -> str:
    2238        return self.cast_sql(expression, safe_prefix="TRY_")

def use_sql(self, expression: sqlglot.expressions.Use) -> str: View Source

    2240    def use_sql(self, expression: exp.Use) -> str:
    2241        kind = self.sql(expression, "kind")
    2242        kind = f" {kind}" if kind else ""
    2243        this = self.sql(expression, "this")
    2244        this = f" {this}" if this else ""
    2245        return f"USE{kind}{this}"

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

    2247    def binary(self, expression: exp.Binary, op: str) -> str:
    2248        op = self.maybe_comment(op, comments=expression.comments)
    2249        return f"{self.sql(expression, 'this')} {op} {self.sql(expression, 'expression')}"

def function_fallback_sql(self, expression: sqlglot.expressions.Func) -> str: View Source

    2251    def function_fallback_sql(self, expression: exp.Func) -> str:
    2252        args = []
    2253        for arg_value in expression.args.values():
    2254            if isinstance(arg_value, list):
    2255                for value in arg_value:
    2256                    args.append(value)
    2257            else:
    2258                args.append(arg_value)
    2259
    2260        return self.func(expression.sql_name(), *args)

def func( self, name: str, *args: Union[str, sqlglot.expressions.Expression, NoneType], prefix: str = '(', suffix: str = ')') -> str: View Source

    2262    def func(
    2263        self,
    2264        name: str,
    2265        *args: t.Optional[exp.Expression | str],
    2266        prefix: str = "(",
    2267        suffix: str = ")",
    2268    ) -> str:
    2269        return f"{self.normalize_func(name)}{prefix}{self.format_args(*args)}{suffix}"

def format_args(self, *args: Union[str, sqlglot.expressions.Expression, NoneType]) -> str: View Source

    2271    def format_args(self, *args: t.Optional[str | exp.Expression]) -> str:
    2272        arg_sqls = tuple(self.sql(arg) for arg in args if arg is not None)
    2273        if self.pretty and self.text_width(arg_sqls) > self.max_text_width:
    2274            return self.indent("\n" + f",\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True)
    2275        return ", ".join(arg_sqls)

def text_width(self, args: Iterable) -> int: View Source

    2277    def text_width(self, args: t.Iterable) -> int:
    2278        return sum(len(arg) for arg in args)

def format_time(self, expression: sqlglot.expressions.Expression) -> Optional[str]: View Source

    2280    def format_time(self, expression: exp.Expression) -> t.Optional[str]:
    2281        return format_time(
    2282            self.sql(expression, "format"), self.INVERSE_TIME_MAPPING, self.INVERSE_TIME_TRIE
    2283        )

def expressions( self, expression: Optional[sqlglot.expressions.Expression] = None, key: Optional[str] = None, sqls: Optional[List[str]] = None, flat: bool = False, indent: bool = True, sep: str = ', ', prefix: str = '') -> str: View Source

    2285    def expressions(
    2286        self,
    2287        expression: t.Optional[exp.Expression] = None,
    2288        key: t.Optional[str] = None,
    2289        sqls: t.Optional[t.List[str]] = None,
    2290        flat: bool = False,
    2291        indent: bool = True,
    2292        sep: str = ", ",
    2293        prefix: str = "",
    2294    ) -> str:
    2295        expressions = expression.args.get(key or "expressions") if expression else sqls
    2296
    2297        if not expressions:
    2298            return ""
    2299
    2300        if flat:
    2301            return sep.join(self.sql(e) for e in expressions)
    2302
    2303        num_sqls = len(expressions)
    2304
    2305        # These are calculated once in case we have the leading_comma / pretty option set, correspondingly
    2306        pad = " " * self.pad
    2307        stripped_sep = sep.strip()
    2308
    2309        result_sqls = []
    2310        for i, e in enumerate(expressions):
    2311            sql = self.sql(e, comment=False)
    2312            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    2313
    2314            if self.pretty:
    2315                if self.leading_comma:
    2316                    result_sqls.append(f"{sep if i > 0 else pad}{prefix}{sql}{comments}")
    2317                else:
    2318                    result_sqls.append(
    2319                        f"{prefix}{sql}{stripped_sep if i + 1 < num_sqls else ''}{comments}"
    2320                    )
    2321            else:
    2322                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    2323
    2324        result_sql = "\n".join(result_sqls) if self.pretty else "".join(result_sqls)
    2325        return self.indent(result_sql, skip_first=False) if indent else result_sql

def op_expressions( self, op: str, expression: sqlglot.expressions.Expression, flat: bool = False) -> str: View Source

    2327    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    2328        flat = flat or isinstance(expression.parent, exp.Properties)
    2329        expressions_sql = self.expressions(expression, flat=flat)
    2330        if flat:
    2331            return f"{op} {expressions_sql}"
    2332        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"

def naked_property(self, expression: sqlglot.expressions.Property) -> str: View Source

    2334    def naked_property(self, expression: exp.Property) -> str:
    2335        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    2336        if not property_name:
    2337            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    2338        return f"{property_name} {self.sql(expression, 'this')}"

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

    2340    def set_operation(self, expression: exp.Expression, op: str) -> str:
    2341        this = self.sql(expression, "this")
    2342        op = self.seg(op)
    2343        return self.query_modifiers(
    2344            expression, f"{this}{op}{self.sep()}{self.sql(expression, 'expression')}"
    2345        )

def tag_sql(self, expression: sqlglot.expressions.Tag) -> str: View Source

    2347    def tag_sql(self, expression: exp.Tag) -> str:
    2348        return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}"

def token_sql(self, token_type: sqlglot.tokens.TokenType) -> str: View Source

    2350    def token_sql(self, token_type: TokenType) -> str:
    2351        return self.TOKEN_MAPPING.get(token_type, token_type.name)

def userdefinedfunction_sql(self, expression: sqlglot.expressions.UserDefinedFunction) -> str: View Source

    2353    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    2354        this = self.sql(expression, "this")
    2355        expressions = self.no_identify(self.expressions, expression)
    2356        expressions = (
    2357            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    2358        )
    2359        return f"{this}{expressions}"

def joinhint_sql(self, expression: sqlglot.expressions.JoinHint) -> str: View Source

    2361    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    2362        this = self.sql(expression, "this")
    2363        expressions = self.expressions(expression, flat=True)
    2364        return f"{this}({expressions})"

def kwarg_sql(self, expression: sqlglot.expressions.Kwarg) -> str: View Source

    2366    def kwarg_sql(self, expression: exp.Kwarg) -> str:
    2367        return self.binary(expression, "=>")

def when_sql(self, expression: sqlglot.expressions.When) -> str: View Source

    2369    def when_sql(self, expression: exp.When) -> str:
    2370        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    2371        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    2372        condition = self.sql(expression, "condition")
    2373        condition = f" AND {condition}" if condition else ""
    2374
    2375        then_expression = expression.args.get("then")
    2376        if isinstance(then_expression, exp.Insert):
    2377            then = f"INSERT {self.sql(then_expression, 'this')}"
    2378            if "expression" in then_expression.args:
    2379                then += f" VALUES {self.sql(then_expression, 'expression')}"
    2380        elif isinstance(then_expression, exp.Update):
    2381            if isinstance(then_expression.args.get("expressions"), exp.Star):
    2382                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    2383            else:
    2384                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    2385        else:
    2386            then = self.sql(then_expression)
    2387        return f"WHEN {matched}{source}{condition} THEN {then}"

def merge_sql(self, expression: sqlglot.expressions.Merge) -> str: View Source

    2389    def merge_sql(self, expression: exp.Merge) -> str:
    2390        this = self.sql(expression, "this")
    2391        using = f"USING {self.sql(expression, 'using')}"
    2392        on = f"ON {self.sql(expression, 'on')}"
    2393        return f"MERGE INTO {this} {using} {on} {self.expressions(expression, sep=' ')}"

def tochar_sql(self, expression: sqlglot.expressions.ToChar) -> str: View Source

    2395    def tochar_sql(self, expression: exp.ToChar) -> str:
    2396        if expression.args.get("format"):
    2397            self.unsupported("Format argument unsupported for TO_CHAR/TO_VARCHAR function")
    2398
    2399        return self.sql(exp.cast(expression.this, "text"))

def dictproperty_sql(self, expression: sqlglot.expressions.DictProperty) -> str: View Source

    2401    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    2402        this = self.sql(expression, "this")
    2403        kind = self.sql(expression, "kind")
    2404        settings_sql = self.expressions(expression, key="settings", sep=" ")
    2405        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    2406        return f"{this}({kind}{args})"

def dictrange_sql(self, expression: sqlglot.expressions.DictRange) -> str: View Source

    2408    def dictrange_sql(self, expression: exp.DictRange) -> str:
    2409        this = self.sql(expression, "this")
    2410        max = self.sql(expression, "max")
    2411        min = self.sql(expression, "min")
    2412        return f"{this}(MIN {min} MAX {max})"

def dictsubproperty_sql(self, expression: sqlglot.expressions.DictSubProperty) -> str: View Source

    2414    def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str:
    2415        return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}"

def oncluster_sql(self, expression: sqlglot.expressions.OnCluster) -> str: View Source

    2417    def oncluster_sql(self, expression: exp.OnCluster) -> str:
    2418        return ""

def clusteredbyproperty_sql(self, expression: sqlglot.expressions.ClusteredByProperty) -> str: View Source

    2420    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    2421        expressions = self.expressions(expression, key="expressions", flat=True)
    2422        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    2423        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    2424        buckets = self.sql(expression, "buckets")
    2425        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"

def cached_generator( cache: Optional[Dict[int, str]] = None) -> Callable[[sqlglot.expressions.Expression], str]: View Source

    2428def cached_generator(
    2429    cache: t.Optional[t.Dict[int, str]] = None
    2430) -> t.Callable[[exp.Expression], str]:
    2431    """Returns a cached generator."""
    2432    cache = {} if cache is None else cache
    2433    generator = Generator(normalize=True, identify="safe")
    2434    return lambda e: generator.generate(e, cache)

Returns a cached generator.