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

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

    342    def __init__(
    343        self,
    344        pretty: t.Optional[bool] = None,
    345        identify: str | bool = False,
    346        normalize: bool = False,
    347        pad: int = 2,
    348        indent: int = 2,
    349        normalize_functions: t.Optional[str | bool] = None,
    350        unsupported_level: ErrorLevel = ErrorLevel.WARN,
    351        max_unsupported: int = 3,
    352        leading_comma: bool = False,
    353        max_text_width: int = 80,
    354        comments: bool = True,
    355    ):
    356        import sqlglot
    357
    358        self.pretty = pretty if pretty is not None else sqlglot.pretty
    359        self.identify = identify
    360        self.normalize = normalize
    361        self.pad = pad
    362        self._indent = indent
    363        self.unsupported_level = unsupported_level
    364        self.max_unsupported = max_unsupported
    365        self.leading_comma = leading_comma
    366        self.max_text_width = max_text_width
    367        self.comments = comments
    368
    369        # This is both a Dialect property and a Generator argument, so we prioritize the latter
    370        self.normalize_functions = (
    371            self.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions
    372        )
    373
    374        self.unsupported_messages: t.List[str] = []
    375        self._escaped_quote_end: str = self.STRING_ESCAPE + self.QUOTE_END
    376        self._escaped_identifier_end: str = self.IDENTIFIER_ESCAPE + self.IDENTIFIER_END
    377        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.HeapProperty'>: <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
QUERY_HINTS = True
QUERY_HINT_SEP = ', '
IS_BOOL_ALLOWED = True
DUPLICATE_KEY_UPDATE_WITH_SET = True
LIMIT_IS_TOP = False
RETURNING_END = True
COLUMN_JOIN_MARKS_SUPPORTED = False
EXTRACT_ALLOWS_QUOTES = True
SELECT_KINDS: Tuple[str, ...] = ('STRUCT', 'VALUE')
VALUES_AS_TABLE = True
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.HeapProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.IsolatedLoadingProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.JournalProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.LanguageProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LikeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LocationProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LockingProperty'>: <Location.POST_ALIAS: 'POST_ALIAS'>, <class 'sqlglot.expressions.LogProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.MaterializedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.MergeBlockRatioProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.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.Delete'>, <class 'sqlglot.expressions.Drop'>, <class 'sqlglot.expressions.From'>, <class 'sqlglot.expressions.Insert'>, <class 'sqlglot.expressions.Select'>, <class 'sqlglot.expressions.Update'>, <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'
ESCAPE_LINE_BREAK = False
@classmethod
def can_identify(text: str, identify: str | bool = 'safe') -> bool: View Source

    253    @classmethod
    254    def can_identify(cls, text: str, identify: str | bool = "safe") -> bool:
    255        """Checks if text can be identified given an identify option.
    256
    257        Args:
    258            text: The text to check.
    259            identify:
    260                "always" or `True`: Always returns true.
    261                "safe": True if the identifier is case-insensitive.
    262
    263        Returns:
    264            Whether or not the given text can be identified.
    265        """
    266        if identify is True or identify == "always":
    267            return True
    268
    269        if identify == "safe":
    270            return not cls.case_sensitive(text)
    271
    272        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
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

    379    def generate(
    380        self,
    381        expression: t.Optional[exp.Expression],
    382        cache: t.Optional[t.Dict[int, str]] = None,
    383    ) -> str:
    384        """
    385        Generates the SQL string corresponding to the given syntax tree.
    386
    387        Args:
    388            expression: The syntax tree.
    389            cache: An optional sql string cache. This leverages the hash of an Expression
    390                which can be slow to compute, so only use it if you set _hash on each node.
    391
    392        Returns:
    393            The SQL string corresponding to `expression`.
    394        """
    395        if cache is not None:
    396            self._cache = cache
    397
    398        self.unsupported_messages = []
    399        sql = self.sql(expression).strip()
    400        self._cache = None
    401
    402        if self.unsupported_level == ErrorLevel.IGNORE:
    403            return sql
    404
    405        if self.unsupported_level == ErrorLevel.WARN:
    406            for msg in self.unsupported_messages:
    407                logger.warning(msg)
    408        elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages:
    409            raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported))
    410
    411        if self.pretty:
    412            sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n")
    413        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

    415    def unsupported(self, message: str) -> None:
    416        if self.unsupported_level == ErrorLevel.IMMEDIATE:
    417            raise UnsupportedError(message)
    418        self.unsupported_messages.append(message)

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

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

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

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

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

    426    def pad_comment(self, comment: str) -> str:
    427        comment = " " + comment if comment[0].strip() else comment
    428        comment = comment + " " if comment[-1].strip() else comment
    429        return comment

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

    431    def maybe_comment(
    432        self,
    433        sql: str,
    434        expression: t.Optional[exp.Expression] = None,
    435        comments: t.Optional[t.List[str]] = None,
    436    ) -> str:
    437        comments = (
    438            ((expression and expression.comments) if comments is None else comments)  # type: ignore
    439            if self.comments
    440            else None
    441        )
    442
    443        if not comments or isinstance(expression, exp.Binary):
    444            return sql
    445
    446        sep = "\n" if self.pretty else " "
    447        comments_sql = sep.join(
    448            f"/*{self.pad_comment(comment)}*/" for comment in comments if comment
    449        )
    450
    451        if not comments_sql:
    452            return sql
    453
    454        if isinstance(expression, self.WITH_SEPARATED_COMMENTS):
    455            return (
    456                f"{self.sep()}{comments_sql}{sql}"
    457                if sql[0].isspace()
    458                else f"{comments_sql}{self.sep()}{sql}"
    459            )
    460
    461        return f"{sql} {comments_sql}"

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

    463    def wrap(self, expression: exp.Expression | str) -> str:
    464        this_sql = self.indent(
    465            self.sql(expression)
    466            if isinstance(expression, (exp.Select, exp.Union))
    467            else self.sql(expression, "this"),
    468            level=1,
    469            pad=0,
    470        )
    471        return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"

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

    473    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
    474        original = self.identify
    475        self.identify = False
    476        result = func(*args, **kwargs)
    477        self.identify = original
    478        return result

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

    480    def normalize_func(self, name: str) -> str:
    481        if self.normalize_functions == "upper" or self.normalize_functions is True:
    482            return name.upper()
    483        if self.normalize_functions == "lower":
    484            return name.lower()
    485        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

    487    def indent(
    488        self,
    489        sql: str,
    490        level: int = 0,
    491        pad: t.Optional[int] = None,
    492        skip_first: bool = False,
    493        skip_last: bool = False,
    494    ) -> str:
    495        if not self.pretty:
    496            return sql
    497
    498        pad = self.pad if pad is None else pad
    499        lines = sql.split("\n")
    500
    501        return "\n".join(
    502            line
    503            if (skip_first and i == 0) or (skip_last and i == len(lines) - 1)
    504            else f"{' ' * (level * self._indent + pad)}{line}"
    505            for i, line in enumerate(lines)
    506        )

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

    508    def sql(
    509        self,
    510        expression: t.Optional[str | exp.Expression],
    511        key: t.Optional[str] = None,
    512        comment: bool = True,
    513    ) -> str:
    514        if not expression:
    515            return ""
    516
    517        if isinstance(expression, str):
    518            return expression
    519
    520        if key:
    521            value = expression.args.get(key)
    522            if value:
    523                return self.sql(value)
    524            return ""
    525
    526        if self._cache is not None:
    527            expression_id = hash(expression)
    528
    529            if expression_id in self._cache:
    530                return self._cache[expression_id]
    531
    532        transform = self.TRANSFORMS.get(expression.__class__)
    533
    534        if callable(transform):
    535            sql = transform(self, expression)
    536        elif transform:
    537            sql = transform
    538        elif isinstance(expression, exp.Expression):
    539            exp_handler_name = f"{expression.key}_sql"
    540
    541            if hasattr(self, exp_handler_name):
    542                sql = getattr(self, exp_handler_name)(expression)
    543            elif isinstance(expression, exp.Func):
    544                sql = self.function_fallback_sql(expression)
    545            elif isinstance(expression, exp.Property):
    546                sql = self.property_sql(expression)
    547            else:
    548                raise ValueError(f"Unsupported expression type {expression.__class__.__name__}")
    549        else:
    550            raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}")
    551
    552        sql = self.maybe_comment(sql, expression) if self.comments and comment else sql
    553
    554        if self._cache is not None:
    555            self._cache[expression_id] = sql
    556        return sql

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

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

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

    563    def cache_sql(self, expression: exp.Cache) -> str:
    564        lazy = " LAZY" if expression.args.get("lazy") else ""
    565        table = self.sql(expression, "this")
    566        options = expression.args.get("options")
    567        options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else ""
    568        sql = self.sql(expression, "expression")
    569        sql = f" AS{self.sep()}{sql}" if sql else ""
    570        sql = f"CACHE{lazy} TABLE {table}{options}{sql}"
    571        return self.prepend_ctes(expression, sql)

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

    573    def characterset_sql(self, expression: exp.CharacterSet) -> str:
    574        if isinstance(expression.parent, exp.Cast):
    575            return f"CHAR CHARACTER SET {self.sql(expression, 'this')}"
    576        default = "DEFAULT " if expression.args.get("default") else ""
    577        return f"{default}CHARACTER SET={self.sql(expression, 'this')}"

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

    579    def column_sql(self, expression: exp.Column) -> str:
    580        join_mark = " (+)" if expression.args.get("join_mark") else ""
    581
    582        if join_mark and not self.COLUMN_JOIN_MARKS_SUPPORTED:
    583            join_mark = ""
    584            self.unsupported("Outer join syntax using the (+) operator is not supported.")
    585
    586        column = ".".join(
    587            self.sql(part)
    588            for part in (
    589                expression.args.get("catalog"),
    590                expression.args.get("db"),
    591                expression.args.get("table"),
    592                expression.args.get("this"),
    593            )
    594            if part
    595        )
    596
    597        return f"{column}{join_mark}"

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

    599    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
    600        this = self.sql(expression, "this")
    601        this = f" {this}" if this else ""
    602        position = self.sql(expression, "position")
    603        return f"{position}{this}"

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

    605    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
    606        column = self.sql(expression, "this")
    607        kind = self.sql(expression, "kind")
    608        constraints = self.expressions(expression, key="constraints", sep=" ", flat=True)
    609        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
    610        kind = f"{sep}{kind}" if kind else ""
    611        constraints = f" {constraints}" if constraints else ""
    612        position = self.sql(expression, "position")
    613        position = f" {position}" if position else ""
    614
    615        return f"{exists}{column}{kind}{constraints}{position}"

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

    617    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
    618        this = self.sql(expression, "this")
    619        kind_sql = self.sql(expression, "kind").strip()
    620        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql

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

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

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

    625    def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str:
    626        if isinstance(expression.this, list):
    627            this = self.wrap(self.expressions(expression, key="this", flat=True))
    628        else:
    629            this = self.sql(expression, "this")
    630
    631        return f"COMPRESS {this}"

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

    633    def generatedasidentitycolumnconstraint_sql(
    634        self, expression: exp.GeneratedAsIdentityColumnConstraint
    635    ) -> str:
    636        this = ""
    637        if expression.this is not None:
    638            on_null = "ON NULL " if expression.args.get("on_null") else ""
    639            this = " ALWAYS " if expression.this else f" BY DEFAULT {on_null}"
    640
    641        start = expression.args.get("start")
    642        start = f"START WITH {start}" if start else ""
    643        increment = expression.args.get("increment")
    644        increment = f" INCREMENT BY {increment}" if increment else ""
    645        minvalue = expression.args.get("minvalue")
    646        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    647        maxvalue = expression.args.get("maxvalue")
    648        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    649        cycle = expression.args.get("cycle")
    650        cycle_sql = ""
    651
    652        if cycle is not None:
    653            cycle_sql = f"{' NO' if not cycle else ''} CYCLE"
    654            cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql
    655
    656        sequence_opts = ""
    657        if start or increment or cycle_sql:
    658            sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}"
    659            sequence_opts = f" ({sequence_opts.strip()})"
    660
    661        expr = self.sql(expression, "expression")
    662        expr = f"({expr})" if expr else "IDENTITY"
    663
    664        return f"GENERATED{this}AS {expr}{sequence_opts}"

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

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

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

    669    def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str:
    670        desc = expression.args.get("desc")
    671        if desc is not None:
    672            return f"PRIMARY KEY{' DESC' if desc else ' ASC'}"
    673        return f"PRIMARY KEY"

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

    675    def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str:
    676        this = self.sql(expression, "this")
    677        this = f" {this}" if this else ""
    678        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

    680    def createable_sql(
    681        self, expression: exp.Create, locations: dict[exp.Properties.Location, list[exp.Property]]
    682    ) -> str:
    683        return self.sql(expression, "this")

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

    685    def create_sql(self, expression: exp.Create) -> str:
    686        kind = self.sql(expression, "kind").upper()
    687        properties = expression.args.get("properties")
    688        properties_locs = self.locate_properties(properties) if properties else {}
    689
    690        this = self.createable_sql(expression, properties_locs)
    691
    692        properties_sql = ""
    693        if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get(
    694            exp.Properties.Location.POST_WITH
    695        ):
    696            properties_sql = self.sql(
    697                exp.Properties(
    698                    expressions=[
    699                        *properties_locs[exp.Properties.Location.POST_SCHEMA],
    700                        *properties_locs[exp.Properties.Location.POST_WITH],
    701                    ]
    702                )
    703            )
    704
    705        begin = " BEGIN" if expression.args.get("begin") else ""
    706        expression_sql = self.sql(expression, "expression")
    707        if expression_sql:
    708            expression_sql = f"{begin}{self.sep()}{expression_sql}"
    709
    710            if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return):
    711                if properties_locs.get(exp.Properties.Location.POST_ALIAS):
    712                    postalias_props_sql = self.properties(
    713                        exp.Properties(
    714                            expressions=properties_locs[exp.Properties.Location.POST_ALIAS]
    715                        ),
    716                        wrapped=False,
    717                    )
    718                    expression_sql = f" AS {postalias_props_sql}{expression_sql}"
    719                else:
    720                    expression_sql = f" AS{expression_sql}"
    721
    722        postindex_props_sql = ""
    723        if properties_locs.get(exp.Properties.Location.POST_INDEX):
    724            postindex_props_sql = self.properties(
    725                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]),
    726                wrapped=False,
    727                prefix=" ",
    728            )
    729
    730        indexes = self.expressions(expression, key="indexes", indent=False, sep=" ")
    731        indexes = f" {indexes}" if indexes else ""
    732        index_sql = indexes + postindex_props_sql
    733
    734        replace = " OR REPLACE" if expression.args.get("replace") else ""
    735        unique = " UNIQUE" if expression.args.get("unique") else ""
    736
    737        postcreate_props_sql = ""
    738        if properties_locs.get(exp.Properties.Location.POST_CREATE):
    739            postcreate_props_sql = self.properties(
    740                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]),
    741                sep=" ",
    742                prefix=" ",
    743                wrapped=False,
    744            )
    745
    746        modifiers = "".join((replace, unique, postcreate_props_sql))
    747
    748        postexpression_props_sql = ""
    749        if properties_locs.get(exp.Properties.Location.POST_EXPRESSION):
    750            postexpression_props_sql = self.properties(
    751                exp.Properties(
    752                    expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION]
    753                ),
    754                sep=" ",
    755                prefix=" ",
    756                wrapped=False,
    757            )
    758
    759        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
    760        no_schema_binding = (
    761            " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else ""
    762        )
    763
    764        clone = self.sql(expression, "clone")
    765        clone = f" {clone}" if clone else ""
    766
    767        expression_sql = f"CREATE{modifiers} {kind}{exists_sql} {this}{properties_sql}{expression_sql}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}"
    768        return self.prepend_ctes(expression, expression_sql)

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

    770    def clone_sql(self, expression: exp.Clone) -> str:
    771        this = self.sql(expression, "this")
    772        when = self.sql(expression, "when")
    773
    774        if when:
    775            kind = self.sql(expression, "kind")
    776            expr = self.sql(expression, "expression")
    777            return f"CLONE {this} {when} ({kind} => {expr})"
    778
    779        return f"CLONE {this}"

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

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

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

    784    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
    785        with_ = self.sql(expression, "with")
    786        if with_:
    787            sql = f"{with_}{self.sep()}{sql}"
    788        return sql

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

    790    def with_sql(self, expression: exp.With) -> str:
    791        sql = self.expressions(expression, flat=True)
    792        recursive = "RECURSIVE " if expression.args.get("recursive") else ""
    793
    794        return f"WITH {recursive}{sql}"

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

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

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

    800    def tablealias_sql(self, expression: exp.TableAlias) -> str:
    801        alias = self.sql(expression, "this")
    802        columns = self.expressions(expression, key="columns", flat=True)
    803        columns = f"({columns})" if columns else ""
    804        return f"{alias}{columns}"

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

    806    def bitstring_sql(self, expression: exp.BitString) -> str:
    807        this = self.sql(expression, "this")
    808        if self.BIT_START:
    809            return f"{self.BIT_START}{this}{self.BIT_END}"
    810        return f"{int(this, 2)}"

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

    812    def hexstring_sql(self, expression: exp.HexString) -> str:
    813        this = self.sql(expression, "this")
    814        if self.HEX_START:
    815            return f"{self.HEX_START}{this}{self.HEX_END}"
    816        return f"{int(this, 16)}"

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

    818    def bytestring_sql(self, expression: exp.ByteString) -> str:
    819        this = self.sql(expression, "this")
    820        if self.BYTE_START:
    821            return f"{self.BYTE_START}{this}{self.BYTE_END}"
    822        return this

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

    824    def rawstring_sql(self, expression: exp.RawString) -> str:
    825        string = self.escape_str(expression.this.replace("\\", "\\\\"))
    826        return f"{self.QUOTE_START}{string}{self.QUOTE_END}"

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

    828    def datatypesize_sql(self, expression: exp.DataTypeSize) -> str:
    829        this = self.sql(expression, "this")
    830        specifier = self.sql(expression, "expression")
    831        specifier = f" {specifier}" if specifier else ""
    832        return f"{this}{specifier}"

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

    834    def datatype_sql(self, expression: exp.DataType) -> str:
    835        type_value = expression.this
    836        type_sql = (
    837            self.TYPE_MAPPING.get(type_value, type_value.value)
    838            if isinstance(type_value, exp.DataType.Type)
    839            else type_value
    840        )
    841        nested = ""
    842        interior = self.expressions(expression, flat=True)
    843        values = ""
    844        if interior:
    845            if expression.args.get("nested"):
    846                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
    847                if expression.args.get("values") is not None:
    848                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
    849                    values = self.expressions(expression, key="values", flat=True)
    850                    values = f"{delimiters[0]}{values}{delimiters[1]}"
    851            else:
    852                nested = f"({interior})"
    853
    854        return f"{type_sql}{nested}{values}"

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

    856    def directory_sql(self, expression: exp.Directory) -> str:
    857        local = "LOCAL " if expression.args.get("local") else ""
    858        row_format = self.sql(expression, "row_format")
    859        row_format = f" {row_format}" if row_format else ""
    860        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"

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

    862    def delete_sql(self, expression: exp.Delete) -> str:
    863        this = self.sql(expression, "this")
    864        this = f" FROM {this}" if this else ""
    865        using = self.sql(expression, "using")
    866        using = f" USING {using}" if using else ""
    867        where = self.sql(expression, "where")
    868        returning = self.sql(expression, "returning")
    869        limit = self.sql(expression, "limit")
    870        tables = self.expressions(expression, key="tables")
    871        tables = f" {tables}" if tables else ""
    872        if self.RETURNING_END:
    873            expression_sql = f"{this}{using}{where}{returning}{limit}"
    874        else:
    875            expression_sql = f"{returning}{this}{using}{where}{limit}"
    876        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")

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

    878    def drop_sql(self, expression: exp.Drop) -> str:
    879        this = self.sql(expression, "this")
    880        kind = expression.args["kind"]
    881        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    882        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    883        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    884        cascade = " CASCADE" if expression.args.get("cascade") else ""
    885        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
    886        purge = " PURGE" if expression.args.get("purge") else ""
    887        return (
    888            f"DROP{temporary}{materialized} {kind}{exists_sql}{this}{cascade}{constraints}{purge}"
    889        )

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

    891    def except_sql(self, expression: exp.Except) -> str:
    892        return self.prepend_ctes(
    893            expression,
    894            self.set_operation(expression, self.except_op(expression)),
    895        )

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

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

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

    900    def fetch_sql(self, expression: exp.Fetch) -> str:
    901        direction = expression.args.get("direction")
    902        direction = f" {direction.upper()}" if direction else ""
    903        count = expression.args.get("count")
    904        count = f" {count}" if count else ""
    905        if expression.args.get("percent"):
    906            count = f"{count} PERCENT"
    907        with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY"
    908        return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}"

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

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

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

    915    def hint_sql(self, expression: exp.Hint) -> str:
    916        if not self.QUERY_HINTS:
    917            self.unsupported("Hints are not supported")
    918            return ""
    919
    920        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"

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

    922    def index_sql(self, expression: exp.Index) -> str:
    923        unique = "UNIQUE " if expression.args.get("unique") else ""
    924        primary = "PRIMARY " if expression.args.get("primary") else ""
    925        amp = "AMP " if expression.args.get("amp") else ""
    926        name = self.sql(expression, "this")
    927        name = f"{name} " if name else ""
    928        table = self.sql(expression, "table")
    929        table = f"{self.INDEX_ON} {table} " if table else ""
    930        using = self.sql(expression, "using")
    931        using = f"USING {using} " if using else ""
    932        index = "INDEX " if not table else ""
    933        columns = self.expressions(expression, key="columns", flat=True)
    934        columns = f"({columns})" if columns else ""
    935        partition_by = self.expressions(expression, key="partition_by", flat=True)
    936        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
    937        return f"{unique}{primary}{amp}{index}{name}{table}{using}{columns}{partition_by}"

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

    939    def identifier_sql(self, expression: exp.Identifier) -> str:
    940        text = expression.name
    941        lower = text.lower()
    942        text = lower if self.normalize and not expression.quoted else text
    943        text = text.replace(self.IDENTIFIER_END, self._escaped_identifier_end)
    944        if (
    945            expression.quoted
    946            or self.can_identify(text, self.identify)
    947            or lower in self.RESERVED_KEYWORDS
    948            or (not self.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
    949        ):
    950            text = f"{self.IDENTIFIER_START}{text}{self.IDENTIFIER_END}"
    951        return text

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

    953    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    954        input_format = self.sql(expression, "input_format")
    955        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    956        output_format = self.sql(expression, "output_format")
    957        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    958        return self.sep().join((input_format, output_format))

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

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

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

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

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

    967    def properties_sql(self, expression: exp.Properties) -> str:
    968        root_properties = []
    969        with_properties = []
    970
    971        for p in expression.expressions:
    972            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    973            if p_loc == exp.Properties.Location.POST_WITH:
    974                with_properties.append(p)
    975            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    976                root_properties.append(p)
    977
    978        return self.root_properties(
    979            exp.Properties(expressions=root_properties)
    980        ) + self.with_properties(exp.Properties(expressions=with_properties))

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

    982    def root_properties(self, properties: exp.Properties) -> str:
    983        if properties.expressions:
    984            return self.sep() + self.expressions(properties, indent=False, sep=" ")
    985        return ""

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

     987    def properties(
     988        self,
     989        properties: exp.Properties,
     990        prefix: str = "",
     991        sep: str = ", ",
     992        suffix: str = "",
     993        wrapped: bool = True,
     994    ) -> str:
     995        if properties.expressions:
     996            expressions = self.expressions(properties, sep=sep, indent=False)
     997            if expressions:
     998                expressions = self.wrap(expressions) if wrapped else expressions
     999                return f"{prefix}{' ' if prefix and prefix != ' ' else ''}{expressions}{suffix}"
    1000        return ""

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

    1002    def with_properties(self, properties: exp.Properties) -> str:
    1003        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

    1005    def locate_properties(
    1006        self, properties: exp.Properties
    1007    ) -> t.Dict[exp.Properties.Location, list[exp.Property]]:
    1008        properties_locs: t.Dict[exp.Properties.Location, list[exp.Property]] = {
    1009            key: [] for key in exp.Properties.Location
    1010        }
    1011
    1012        for p in properties.expressions:
    1013            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1014            if p_loc == exp.Properties.Location.POST_NAME:
    1015                properties_locs[exp.Properties.Location.POST_NAME].append(p)
    1016            elif p_loc == exp.Properties.Location.POST_INDEX:
    1017                properties_locs[exp.Properties.Location.POST_INDEX].append(p)
    1018            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    1019                properties_locs[exp.Properties.Location.POST_SCHEMA].append(p)
    1020            elif p_loc == exp.Properties.Location.POST_WITH:
    1021                properties_locs[exp.Properties.Location.POST_WITH].append(p)
    1022            elif p_loc == exp.Properties.Location.POST_CREATE:
    1023                properties_locs[exp.Properties.Location.POST_CREATE].append(p)
    1024            elif p_loc == exp.Properties.Location.POST_ALIAS:
    1025                properties_locs[exp.Properties.Location.POST_ALIAS].append(p)
    1026            elif p_loc == exp.Properties.Location.POST_EXPRESSION:
    1027                properties_locs[exp.Properties.Location.POST_EXPRESSION].append(p)
    1028            elif p_loc == exp.Properties.Location.UNSUPPORTED:
    1029                self.unsupported(f"Unsupported property {p.key}")
    1030
    1031        return properties_locs

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

    1033    def property_sql(self, expression: exp.Property) -> str:
    1034        property_cls = expression.__class__
    1035        if property_cls == exp.Property:
    1036            return f"{expression.name}={self.sql(expression, 'value')}"
    1037
    1038        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    1039        if not property_name:
    1040            self.unsupported(f"Unsupported property {expression.key}")
    1041
    1042        return f"{property_name}={self.sql(expression, 'this')}"

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

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

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

    1049    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1050        no = "NO " if expression.args.get("no") else ""
    1051        protection = " PROTECTION" if expression.args.get("protection") else ""
    1052        return f"{no}FALLBACK{protection}"

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

    1054    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1055        no = "NO " if expression.args.get("no") else ""
    1056        local = expression.args.get("local")
    1057        local = f"{local} " if local else ""
    1058        dual = "DUAL " if expression.args.get("dual") else ""
    1059        before = "BEFORE " if expression.args.get("before") else ""
    1060        after = "AFTER " if expression.args.get("after") else ""
    1061        return f"{no}{local}{dual}{before}{after}JOURNAL"

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

    1063    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1064        freespace = self.sql(expression, "this")
    1065        percent = " PERCENT" if expression.args.get("percent") else ""
    1066        return f"FREESPACE={freespace}{percent}"

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

    1068    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1069        if expression.args.get("default"):
    1070            property = "DEFAULT"
    1071        elif expression.args.get("on"):
    1072            property = "ON"
    1073        else:
    1074            property = "OFF"
    1075        return f"CHECKSUM={property}"

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

    1077    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1078        if expression.args.get("no"):
    1079            return "NO MERGEBLOCKRATIO"
    1080        if expression.args.get("default"):
    1081            return "DEFAULT MERGEBLOCKRATIO"
    1082
    1083        percent = " PERCENT" if expression.args.get("percent") else ""
    1084        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"

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

    1086    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1087        default = expression.args.get("default")
    1088        minimum = expression.args.get("minimum")
    1089        maximum = expression.args.get("maximum")
    1090        if default or minimum or maximum:
    1091            if default:
    1092                prop = "DEFAULT"
    1093            elif minimum:
    1094                prop = "MINIMUM"
    1095            else:
    1096                prop = "MAXIMUM"
    1097            return f"{prop} DATABLOCKSIZE"
    1098        units = expression.args.get("units")
    1099        units = f" {units}" if units else ""
    1100        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"

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

    1102    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1103        autotemp = expression.args.get("autotemp")
    1104        always = expression.args.get("always")
    1105        default = expression.args.get("default")
    1106        manual = expression.args.get("manual")
    1107        never = expression.args.get("never")
    1108
    1109        if autotemp is not None:
    1110            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1111        elif always:
    1112            prop = "ALWAYS"
    1113        elif default:
    1114            prop = "DEFAULT"
    1115        elif manual:
    1116            prop = "MANUAL"
    1117        elif never:
    1118            prop = "NEVER"
    1119        return f"BLOCKCOMPRESSION={prop}"

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

    1121    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1122        no = expression.args.get("no")
    1123        no = " NO" if no else ""
    1124        concurrent = expression.args.get("concurrent")
    1125        concurrent = " CONCURRENT" if concurrent else ""
    1126
    1127        for_ = ""
    1128        if expression.args.get("for_all"):
    1129            for_ = " FOR ALL"
    1130        elif expression.args.get("for_insert"):
    1131            for_ = " FOR INSERT"
    1132        elif expression.args.get("for_none"):
    1133            for_ = " FOR NONE"
    1134        return f"WITH{no}{concurrent} ISOLATED LOADING{for_}"

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

    1136    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1137        kind = expression.args.get("kind")
    1138        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1139        for_or_in = expression.args.get("for_or_in")
    1140        lock_type = expression.args.get("lock_type")
    1141        override = " OVERRIDE" if expression.args.get("override") else ""
    1142        return f"LOCKING {kind}{this} {for_or_in} {lock_type}{override}"

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

    1144    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1145        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1146        statistics = expression.args.get("statistics")
    1147        statistics_sql = ""
    1148        if statistics is not None:
    1149            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1150        return f"{data_sql}{statistics_sql}"

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

    1152    def insert_sql(self, expression: exp.Insert) -> str:
    1153        overwrite = expression.args.get("overwrite")
    1154
    1155        if isinstance(expression.this, exp.Directory):
    1156            this = " OVERWRITE" if overwrite else " INTO"
    1157        else:
    1158            this = " OVERWRITE TABLE" if overwrite else " INTO"
    1159
    1160        alternative = expression.args.get("alternative")
    1161        alternative = f" OR {alternative}" if alternative else ""
    1162        ignore = " IGNORE" if expression.args.get("ignore") else ""
    1163
    1164        this = f"{this} {self.sql(expression, 'this')}"
    1165
    1166        exists = " IF EXISTS" if expression.args.get("exists") else ""
    1167        partition_sql = (
    1168            f" {self.sql(expression, 'partition')}" if expression.args.get("partition") else ""
    1169        )
    1170        where = self.sql(expression, "where")
    1171        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
    1172        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
    1173        conflict = self.sql(expression, "conflict")
    1174        returning = self.sql(expression, "returning")
    1175
    1176        if self.RETURNING_END:
    1177            expression_sql = f"{expression_sql}{conflict}{returning}"
    1178        else:
    1179            expression_sql = f"{returning}{expression_sql}{conflict}"
    1180
    1181        sql = f"INSERT{alternative}{ignore}{this}{exists}{partition_sql}{where}{expression_sql}"
    1182        return self.prepend_ctes(expression, sql)

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

    1184    def intersect_sql(self, expression: exp.Intersect) -> str:
    1185        return self.prepend_ctes(
    1186            expression,
    1187            self.set_operation(expression, self.intersect_op(expression)),
    1188        )

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

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

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

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

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

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

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

    1199    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1200        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1201        constraint = self.sql(expression, "constraint")
    1202        if constraint:
    1203            constraint = f"ON CONSTRAINT {constraint}"
    1204        key = self.expressions(expression, key="key", flat=True)
    1205        do = "" if expression.args.get("duplicate") else " DO "
    1206        nothing = "NOTHING" if expression.args.get("nothing") else ""
    1207        expressions = self.expressions(expression, flat=True)
    1208        set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
    1209        if expressions:
    1210            expressions = f"UPDATE {set_keyword}{expressions}"
    1211        return f"{self.seg(conflict)} {constraint}{key}{do}{nothing}{expressions}"

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

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

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

    1216    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1217        fields = expression.args.get("fields")
    1218        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1219        escaped = expression.args.get("escaped")
    1220        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1221        items = expression.args.get("collection_items")
    1222        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1223        keys = expression.args.get("map_keys")
    1224        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1225        lines = expression.args.get("lines")
    1226        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1227        null = expression.args.get("null")
    1228        null = f" NULL DEFINED AS {null}" if null else ""
    1229        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"

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

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

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

    1234    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1235        this = f"{self.sql(expression, 'this')} INDEX"
    1236        target = self.sql(expression, "target")
    1237        target = f" FOR {target}" if target else ""
    1238        return f"{this}{target} ({self.expressions(expression, flat=True)})"

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

    1240    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1241        table = ".".join(
    1242            part
    1243            for part in [
    1244                self.sql(expression, "catalog"),
    1245                self.sql(expression, "db"),
    1246                self.sql(expression, "this"),
    1247            ]
    1248            if part
    1249        )
    1250
    1251        alias = self.sql(expression, "alias")
    1252        alias = f"{sep}{alias}" if alias else ""
    1253        hints = self.expressions(expression, key="hints", sep=" ")
    1254        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
    1255        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    1256        pivots = f" {pivots}" if pivots else ""
    1257        joins = self.expressions(expression, key="joins", sep="", skip_first=True)
    1258        laterals = self.expressions(expression, key="laterals", sep="")
    1259        system_time = expression.args.get("system_time")
    1260        system_time = f" {self.sql(expression, 'system_time')}" if system_time else ""
    1261
    1262        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

    1264    def tablesample_sql(
    1265        self, expression: exp.TableSample, seed_prefix: str = "SEED", sep=" AS "
    1266    ) -> str:
    1267        if self.ALIAS_POST_TABLESAMPLE and expression.this.alias:
    1268            table = expression.this.copy()
    1269            table.set("alias", None)
    1270            this = self.sql(table)
    1271            alias = f"{sep}{self.sql(expression.this, 'alias')}"
    1272        else:
    1273            this = self.sql(expression, "this")
    1274            alias = ""
    1275        method = self.sql(expression, "method")
    1276        method = f"{method.upper()} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    1277        numerator = self.sql(expression, "bucket_numerator")
    1278        denominator = self.sql(expression, "bucket_denominator")
    1279        field = self.sql(expression, "bucket_field")
    1280        field = f" ON {field}" if field else ""
    1281        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    1282        percent = self.sql(expression, "percent")
    1283        percent = f"{percent} PERCENT" if percent else ""
    1284        rows = self.sql(expression, "rows")
    1285        rows = f"{rows} ROWS" if rows else ""
    1286        size = self.sql(expression, "size")
    1287        if size and self.TABLESAMPLE_SIZE_IS_PERCENT:
    1288            size = f"{size} PERCENT"
    1289        seed = self.sql(expression, "seed")
    1290        seed = f" {seed_prefix} ({seed})" if seed else ""
    1291        kind = expression.args.get("kind", "TABLESAMPLE")
    1292        return f"{this} {kind} {method}({bucket}{percent}{rows}{size}){seed}{alias}"

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

    1294    def pivot_sql(self, expression: exp.Pivot) -> str:
    1295        expressions = self.expressions(expression, flat=True)
    1296
    1297        if expression.this:
    1298            this = self.sql(expression, "this")
    1299            on = f"{self.seg('ON')} {expressions}"
    1300            using = self.expressions(expression, key="using", flat=True)
    1301            using = f"{self.seg('USING')} {using}" if using else ""
    1302            group = self.sql(expression, "group")
    1303            return f"PIVOT {this}{on}{using}{group}"
    1304
    1305        alias = self.sql(expression, "alias")
    1306        alias = f" AS {alias}" if alias else ""
    1307        unpivot = expression.args.get("unpivot")
    1308        direction = "UNPIVOT" if unpivot else "PIVOT"
    1309        field = self.sql(expression, "field")
    1310        return f"{direction}({expressions} FOR {field}){alias}"

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

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

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

    1315    def update_sql(self, expression: exp.Update) -> str:
    1316        this = self.sql(expression, "this")
    1317        set_sql = self.expressions(expression, flat=True)
    1318        from_sql = self.sql(expression, "from")
    1319        where_sql = self.sql(expression, "where")
    1320        returning = self.sql(expression, "returning")
    1321        limit = self.sql(expression, "limit")
    1322        if self.RETURNING_END:
    1323            expression_sql = f"{from_sql}{where_sql}{returning}{limit}"
    1324        else:
    1325            expression_sql = f"{returning}{from_sql}{where_sql}{limit}"
    1326        sql = f"UPDATE {this} SET {set_sql}{expression_sql}"
    1327        return self.prepend_ctes(expression, sql)

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

    1329    def values_sql(self, expression: exp.Values) -> str:
    1330        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
    1331        if self.VALUES_AS_TABLE or not expression.find_ancestor(exp.From, exp.Join):
    1332            args = self.expressions(expression)
    1333            alias = self.sql(expression, "alias")
    1334            values = f"VALUES{self.seg('')}{args}"
    1335            values = (
    1336                f"({values})"
    1337                if self.WRAP_DERIVED_VALUES and (alias or isinstance(expression.parent, exp.From))
    1338                else values
    1339            )
    1340            return f"{values} AS {alias}" if alias else values
    1341
    1342        # Converts `VALUES...` expression into a series of select unions.
    1343        # Note: If you have a lot of unions then this will result in a large number of recursive statements to
    1344        # evaluate the expression. You may need to increase `sys.setrecursionlimit` to run and it can also be
    1345        # very slow.
    1346        expression = expression.copy()
    1347        column_names = expression.alias and expression.args["alias"].columns
    1348
    1349        selects = []
    1350
    1351        for i, tup in enumerate(expression.expressions):
    1352            row = tup.expressions
    1353
    1354            if i == 0 and column_names:
    1355                row = [
    1356                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
    1357                ]
    1358
    1359            selects.append(exp.Select(expressions=row))
    1360
    1361        subquery_expression: exp.Select | exp.Union = selects[0]
    1362        if len(selects) > 1:
    1363            for select in selects[1:]:
    1364                subquery_expression = exp.union(
    1365                    subquery_expression, select, distinct=False, copy=False
    1366                )
    1367
    1368        return self.subquery_sql(subquery_expression.subquery(expression.alias, copy=False))

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

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

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

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

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

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

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

    1381    def group_sql(self, expression: exp.Group) -> str:
    1382        group_by = self.op_expressions("GROUP BY", expression)
    1383
    1384        if expression.args.get("all"):
    1385            return f"{group_by} ALL"
    1386
    1387        grouping_sets = self.expressions(expression, key="grouping_sets", indent=False)
    1388        grouping_sets = (
    1389            f"{self.seg('GROUPING SETS')} {self.wrap(grouping_sets)}" if grouping_sets else ""
    1390        )
    1391
    1392        cube = expression.args.get("cube", [])
    1393        if seq_get(cube, 0) is True:
    1394            return f"{group_by}{self.seg('WITH CUBE')}"
    1395        else:
    1396            cube_sql = self.expressions(expression, key="cube", indent=False)
    1397            cube_sql = f"{self.seg('CUBE')} {self.wrap(cube_sql)}" if cube_sql else ""
    1398
    1399        rollup = expression.args.get("rollup", [])
    1400        if seq_get(rollup, 0) is True:
    1401            return f"{group_by}{self.seg('WITH ROLLUP')}"
    1402        else:
    1403            rollup_sql = self.expressions(expression, key="rollup", indent=False)
    1404            rollup_sql = f"{self.seg('ROLLUP')} {self.wrap(rollup_sql)}" if rollup_sql else ""
    1405
    1406        groupings = csv(
    1407            grouping_sets,
    1408            cube_sql,
    1409            rollup_sql,
    1410            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    1411            sep=self.GROUPINGS_SEP,
    1412        )
    1413
    1414        if expression.args.get("expressions") and groupings:
    1415            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    1416
    1417        return f"{group_by}{groupings}"

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

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

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

    1423    def join_sql(self, expression: exp.Join) -> str:
    1424        op_sql = " ".join(
    1425            op
    1426            for op in (
    1427                expression.method,
    1428                "GLOBAL" if expression.args.get("global") else None,
    1429                expression.side,
    1430                expression.kind,
    1431                expression.hint if self.JOIN_HINTS else None,
    1432            )
    1433            if op
    1434        )
    1435        on_sql = self.sql(expression, "on")
    1436        using = expression.args.get("using")
    1437
    1438        if not on_sql and using:
    1439            on_sql = csv(*(self.sql(column) for column in using))
    1440
    1441        this_sql = self.sql(expression, "this")
    1442
    1443        if on_sql:
    1444            on_sql = self.indent(on_sql, skip_first=True)
    1445            space = self.seg(" " * self.pad) if self.pretty else " "
    1446            if using:
    1447                on_sql = f"{space}USING ({on_sql})"
    1448            else:
    1449                on_sql = f"{space}ON {on_sql}"
    1450        elif not op_sql:
    1451            return f", {this_sql}"
    1452
    1453        op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    1454        return f"{self.seg(op_sql)} {this_sql}{on_sql}"

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

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

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

    1461    def lateral_sql(self, expression: exp.Lateral) -> str:
    1462        this = self.sql(expression, "this")
    1463
    1464        if isinstance(expression.this, exp.Subquery):
    1465            return f"LATERAL {this}"
    1466
    1467        if expression.args.get("view"):
    1468            alias = expression.args["alias"]
    1469            columns = self.expressions(alias, key="columns", flat=True)
    1470            table = f" {alias.name}" if alias.name else ""
    1471            columns = f" AS {columns}" if columns else ""
    1472            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    1473            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    1474
    1475        alias = self.sql(expression, "alias")
    1476        alias = f" AS {alias}" if alias else ""
    1477        return f"LATERAL {this}{alias}"

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

    1479    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    1480        this = self.sql(expression, "this")
    1481        args = ", ".join(
    1482            sql
    1483            for sql in (
    1484                self.sql(expression, "offset"),
    1485                self.sql(expression, "expression"),
    1486            )
    1487            if sql
    1488        )
    1489        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args}"

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

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

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

    1495    def setitem_sql(self, expression: exp.SetItem) -> str:
    1496        kind = self.sql(expression, "kind")
    1497        kind = f"{kind} " if kind else ""
    1498        this = self.sql(expression, "this")
    1499        expressions = self.expressions(expression)
    1500        collate = self.sql(expression, "collate")
    1501        collate = f" COLLATE {collate}" if collate else ""
    1502        global_ = "GLOBAL " if expression.args.get("global") else ""
    1503        return f"{global_}{kind}{this}{expressions}{collate}"

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

    1505    def set_sql(self, expression: exp.Set) -> str:
    1506        expressions = (
    1507            f" {self.expressions(expression, flat=True)}" if expression.expressions else ""
    1508        )
    1509        tag = " TAG" if expression.args.get("tag") else ""
    1510        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"

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

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

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

    1515    def lock_sql(self, expression: exp.Lock) -> str:
    1516        if not self.LOCKING_READS_SUPPORTED:
    1517            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    1518            return ""
    1519
    1520        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    1521        expressions = self.expressions(expression, flat=True)
    1522        expressions = f" OF {expressions}" if expressions else ""
    1523        wait = expression.args.get("wait")
    1524
    1525        if wait is not None:
    1526            if isinstance(wait, exp.Literal):
    1527                wait = f" WAIT {self.sql(wait)}"
    1528            else:
    1529                wait = " NOWAIT" if wait else " SKIP LOCKED"
    1530
    1531        return f"{lock_type}{expressions}{wait or ''}"

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

    1533    def literal_sql(self, expression: exp.Literal) -> str:
    1534        text = expression.this or ""
    1535        if expression.is_string:
    1536            text = f"{self.QUOTE_START}{self.escape_str(text)}{self.QUOTE_END}"
    1537        return text

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

    1539    def escape_str(self, text: str) -> str:
    1540        text = text.replace(self.QUOTE_END, self._escaped_quote_end)
    1541        if self.ESCAPE_LINE_BREAK:
    1542            text = text.replace("\n", "\\n")
    1543        elif self.pretty:
    1544            text = text.replace("\n", self.SENTINEL_LINE_BREAK)
    1545        return text

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

    1547    def loaddata_sql(self, expression: exp.LoadData) -> str:
    1548        local = " LOCAL" if expression.args.get("local") else ""
    1549        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    1550        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    1551        this = f" INTO TABLE {self.sql(expression, 'this')}"
    1552        partition = self.sql(expression, "partition")
    1553        partition = f" {partition}" if partition else ""
    1554        input_format = self.sql(expression, "input_format")
    1555        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    1556        serde = self.sql(expression, "serde")
    1557        serde = f" SERDE {serde}" if serde else ""
    1558        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"

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

    1560    def null_sql(self, *_) -> str:
    1561        return "NULL"

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

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

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

    1566    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    1567        this = self.sql(expression, "this")
    1568        this = f"{this} " if this else this
    1569        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

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

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

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

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

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

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

    1580    def ordered_sql(self, expression: exp.Ordered) -> str:
    1581        desc = expression.args.get("desc")
    1582        asc = not desc
    1583
    1584        nulls_first = expression.args.get("nulls_first")
    1585        nulls_last = not nulls_first
    1586        nulls_are_large = self.NULL_ORDERING == "nulls_are_large"
    1587        nulls_are_small = self.NULL_ORDERING == "nulls_are_small"
    1588        nulls_are_last = self.NULL_ORDERING == "nulls_are_last"
    1589
    1590        sort_order = " DESC" if desc else ""
    1591        nulls_sort_change = ""
    1592        if nulls_first and (
    1593            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
    1594        ):
    1595            nulls_sort_change = " NULLS FIRST"
    1596        elif (
    1597            nulls_last
    1598            and ((asc and nulls_are_small) or (desc and nulls_are_large))
    1599            and not nulls_are_last
    1600        ):
    1601            nulls_sort_change = " NULLS LAST"
    1602
    1603        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
    1604            self.unsupported(
    1605                "Sorting in an ORDER BY on NULLS FIRST/NULLS LAST is not supported by this dialect"
    1606            )
    1607            nulls_sort_change = ""
    1608
    1609        return f"{self.sql(expression, 'this')}{sort_order}{nulls_sort_change}"

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

    1611    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    1612        partition = self.partition_by_sql(expression)
    1613        order = self.sql(expression, "order")
    1614        measures = self.expressions(expression, key="measures")
    1615        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    1616        rows = self.sql(expression, "rows")
    1617        rows = self.seg(rows) if rows else ""
    1618        after = self.sql(expression, "after")
    1619        after = self.seg(after) if after else ""
    1620        pattern = self.sql(expression, "pattern")
    1621        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    1622        definition_sqls = [
    1623            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    1624            for definition in expression.args.get("define", [])
    1625        ]
    1626        definitions = self.expressions(sqls=definition_sqls)
    1627        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    1628        body = "".join(
    1629            (
    1630                partition,
    1631                order,
    1632                measures,
    1633                rows,
    1634                after,
    1635                pattern,
    1636                define,
    1637            )
    1638        )
    1639        alias = self.sql(expression, "alias")
    1640        alias = f" {alias}" if alias else ""
    1641        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"

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

    1643    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    1644        limit: t.Optional[exp.Fetch | exp.Limit] = expression.args.get("limit")
    1645
    1646        # If the limit is generated as TOP, we need to ensure it's not generated twice
    1647        with_offset_limit_modifiers = not isinstance(limit, exp.Limit) or not self.LIMIT_IS_TOP
    1648
    1649        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    1650            limit = exp.Limit(expression=limit.args.get("count"))
    1651        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    1652            limit = exp.Fetch(direction="FIRST", count=limit.expression)
    1653
    1654        fetch = isinstance(limit, exp.Fetch)
    1655
    1656        offset_limit_modifiers = (
    1657            self.offset_limit_modifiers(expression, fetch, limit)
    1658            if with_offset_limit_modifiers
    1659            else []
    1660        )
    1661
    1662        return csv(
    1663            *sqls,
    1664            *[self.sql(join) for join in expression.args.get("joins") or []],
    1665            self.sql(expression, "match"),
    1666            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    1667            self.sql(expression, "where"),
    1668            self.sql(expression, "group"),
    1669            self.sql(expression, "having"),
    1670            *self.after_having_modifiers(expression),
    1671            self.sql(expression, "order"),
    1672            *offset_limit_modifiers,
    1673            *self.after_limit_modifiers(expression),
    1674            sep="",
    1675        )

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

    1677    def offset_limit_modifiers(
    1678        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    1679    ) -> t.List[str]:
    1680        return [
    1681            self.sql(expression, "offset") if fetch else self.sql(limit),
    1682            self.sql(limit) if fetch else self.sql(expression, "offset"),
    1683        ]

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

    1685    def after_having_modifiers(self, expression: exp.Expression) -> t.List[str]:
    1686        return [
    1687            self.sql(expression, "qualify"),
    1688            self.seg("WINDOW ") + self.expressions(expression, key="windows", flat=True)
    1689            if expression.args.get("windows")
    1690            else "",
    1691            self.sql(expression, "distribute"),
    1692            self.sql(expression, "sort"),
    1693            self.sql(expression, "cluster"),
    1694        ]

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

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

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

    1701    def select_sql(self, expression: exp.Select) -> str:
    1702        hint = self.sql(expression, "hint")
    1703        distinct = self.sql(expression, "distinct")
    1704        distinct = f" {distinct}" if distinct else ""
    1705        kind = self.sql(expression, "kind").upper()
    1706        limit = expression.args.get("limit")
    1707        top = (
    1708            self.limit_sql(limit, top=True)
    1709            if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP
    1710            else ""
    1711        )
    1712
    1713        expressions = self.expressions(expression)
    1714
    1715        if kind:
    1716            if kind in self.SELECT_KINDS:
    1717                kind = f" AS {kind}"
    1718            else:
    1719                if kind == "STRUCT":
    1720                    expressions = self.expressions(
    1721                        sqls=[
    1722                            self.sql(
    1723                                exp.Struct(
    1724                                    expressions=[
    1725                                        exp.column(e.output_name).eq(
    1726                                            e.this if isinstance(e, exp.Alias) else e
    1727                                        )
    1728                                        for e in expression.expressions
    1729                                    ]
    1730                                )
    1731                            )
    1732                        ]
    1733                    )
    1734                kind = ""
    1735
    1736        expressions = f"{self.sep()}{expressions}" if expressions else expressions
    1737        sql = self.query_modifiers(
    1738            expression,
    1739            f"SELECT{top}{hint}{distinct}{kind}{expressions}",
    1740            self.sql(expression, "into", comment=False),
    1741            self.sql(expression, "from", comment=False),
    1742        )
    1743        return self.prepend_ctes(expression, sql)

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

    1745    def schema_sql(self, expression: exp.Schema) -> str:
    1746        this = self.sql(expression, "this")
    1747        this = f"{this} " if this else ""
    1748        sql = self.schema_columns_sql(expression)
    1749        return f"{this}{sql}"

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

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

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

    1754    def star_sql(self, expression: exp.Star) -> str:
    1755        except_ = self.expressions(expression, key="except", flat=True)
    1756        except_ = f"{self.seg(self.STAR_MAPPING['except'])} ({except_})" if except_ else ""
    1757        replace = self.expressions(expression, key="replace", flat=True)
    1758        replace = f"{self.seg(self.STAR_MAPPING['replace'])} ({replace})" if replace else ""
    1759        return f"*{except_}{replace}"

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

    1761    def parameter_sql(self, expression: exp.Parameter) -> str:
    1762        this = self.sql(expression, "this")
    1763        this = f"{{{this}}}" if expression.args.get("wrapped") else f"{this}"
    1764        return f"{self.PARAMETER_TOKEN}{this}"

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

    1766    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    1767        this = self.sql(expression, "this")
    1768        kind = expression.text("kind")
    1769        if kind:
    1770            kind = f"{kind}."
    1771        return f"@@{kind}{this}"

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

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

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

    1776    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    1777        alias = self.sql(expression, "alias")
    1778        alias = f"{sep}{alias}" if alias else ""
    1779
    1780        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    1781        pivots = f" {pivots}" if pivots else ""
    1782
    1783        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    1784        return self.prepend_ctes(expression, sql)

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

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

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

    1790    def union_sql(self, expression: exp.Union) -> str:
    1791        return self.prepend_ctes(
    1792            expression,
    1793            self.set_operation(expression, self.union_op(expression)),
    1794        )

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

    1796    def union_op(self, expression: exp.Union) -> str:
    1797        kind = " DISTINCT" if self.EXPLICIT_UNION else ""
    1798        kind = kind if expression.args.get("distinct") else " ALL"
    1799        return f"UNION{kind}"

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

    1801    def unnest_sql(self, expression: exp.Unnest) -> str:
    1802        args = self.expressions(expression, flat=True)
    1803        alias = expression.args.get("alias")
    1804        if alias and self.UNNEST_COLUMN_ONLY:
    1805            columns = alias.columns
    1806            alias = self.sql(columns[0]) if columns else ""
    1807        else:
    1808            alias = self.sql(expression, "alias")
    1809        alias = f" AS {alias}" if alias else alias
    1810        ordinality = " WITH ORDINALITY" if expression.args.get("ordinality") else ""
    1811        offset = expression.args.get("offset")
    1812        offset = f" WITH OFFSET AS {self.sql(offset)}" if offset else ""
    1813        return f"UNNEST({args}){ordinality}{alias}{offset}"

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

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

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

    1819    def window_sql(self, expression: exp.Window) -> str:
    1820        this = self.sql(expression, "this")
    1821        partition = self.partition_by_sql(expression)
    1822        order = expression.args.get("order")
    1823        order = self.order_sql(order, flat=True) if order else ""
    1824        spec = self.sql(expression, "spec")
    1825        alias = self.sql(expression, "alias")
    1826        over = self.sql(expression, "over") or "OVER"
    1827
    1828        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    1829
    1830        first = expression.args.get("first")
    1831        if first is None:
    1832            first = ""
    1833        else:
    1834            first = "FIRST" if first else "LAST"
    1835
    1836        if not partition and not order and not spec and alias:
    1837            return f"{this} {alias}"
    1838
    1839        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
    1840        return f"{this} ({args})"

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

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

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

    1846    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    1847        kind = self.sql(expression, "kind")
    1848        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    1849        end = (
    1850            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    1851            or "CURRENT ROW"
    1852        )
    1853        return f"{kind} BETWEEN {start} AND {end}"

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

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

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

    1860    def between_sql(self, expression: exp.Between) -> str:
    1861        this = self.sql(expression, "this")
    1862        low = self.sql(expression, "low")
    1863        high = self.sql(expression, "high")
    1864        return f"{this} BETWEEN {low} AND {high}"

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

    1866    def bracket_sql(self, expression: exp.Bracket) -> str:
    1867        expressions = apply_index_offset(expression.this, expression.expressions, self.INDEX_OFFSET)
    1868        expressions_sql = ", ".join(self.sql(e) for e in expressions)
    1869
    1870        return f"{self.sql(expression, 'this')}[{expressions_sql}]"

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

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

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

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

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

    1878    def any_sql(self, expression: exp.Any) -> str:
    1879        this = self.sql(expression, "this")
    1880        if isinstance(expression.this, exp.Subqueryable):
    1881            this = self.wrap(this)
    1882        return f"ANY {this}"

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

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

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

    1887    def case_sql(self, expression: exp.Case) -> str:
    1888        this = self.sql(expression, "this")
    1889        statements = [f"CASE {this}" if this else "CASE"]
    1890
    1891        for e in expression.args["ifs"]:
    1892            statements.append(f"WHEN {self.sql(e, 'this')}")
    1893            statements.append(f"THEN {self.sql(e, 'true')}")
    1894
    1895        default = self.sql(expression, "default")
    1896
    1897        if default:
    1898            statements.append(f"ELSE {default}")
    1899
    1900        statements.append("END")
    1901
    1902        if self.pretty and self.text_width(statements) > self.max_text_width:
    1903            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    1904
    1905        return " ".join(statements)

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

    1907    def constraint_sql(self, expression: exp.Constraint) -> str:
    1908        this = self.sql(expression, "this")
    1909        expressions = self.expressions(expression, flat=True)
    1910        return f"CONSTRAINT {this} {expressions}"

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

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

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

    1917    def extract_sql(self, expression: exp.Extract) -> str:
    1918        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
    1919        expression_sql = self.sql(expression, "expression")
    1920        return f"EXTRACT({this} FROM {expression_sql})"

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

    1922    def trim_sql(self, expression: exp.Trim) -> str:
    1923        trim_type = self.sql(expression, "position")
    1924
    1925        if trim_type == "LEADING":
    1926            return self.func("LTRIM", expression.this)
    1927        elif trim_type == "TRAILING":
    1928            return self.func("RTRIM", expression.this)
    1929        else:
    1930            return self.func("TRIM", expression.this, expression.expression)

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

    1932    def safeconcat_sql(self, expression: exp.SafeConcat) -> str:
    1933        expressions = expression.expressions
    1934        if self.STRICT_STRING_CONCAT:
    1935            expressions = (exp.cast(e, "text") for e in expressions)
    1936        return self.func("CONCAT", *expressions)

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

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

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

    1942    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    1943        expressions = self.expressions(expression, flat=True)
    1944        reference = self.sql(expression, "reference")
    1945        reference = f" {reference}" if reference else ""
    1946        delete = self.sql(expression, "delete")
    1947        delete = f" ON DELETE {delete}" if delete else ""
    1948        update = self.sql(expression, "update")
    1949        update = f" ON UPDATE {update}" if update else ""
    1950        return f"FOREIGN KEY ({expressions}){reference}{delete}{update}"

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

    1952    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    1953        expressions = self.expressions(expression, flat=True)
    1954        options = self.expressions(expression, key="options", flat=True, sep=" ")
    1955        options = f" {options}" if options else ""
    1956        return f"PRIMARY KEY ({expressions}){options}"

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

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

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

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

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

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

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

    1969    def jsonobject_sql(self, expression: exp.JSONObject) -> str:
    1970        null_handling = expression.args.get("null_handling")
    1971        null_handling = f" {null_handling}" if null_handling else ""
    1972        unique_keys = expression.args.get("unique_keys")
    1973        if unique_keys is not None:
    1974            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    1975        else:
    1976            unique_keys = ""
    1977        return_type = self.sql(expression, "return_type")
    1978        return_type = f" RETURNING {return_type}" if return_type else ""
    1979        format_json = " FORMAT JSON" if expression.args.get("format_json") else ""
    1980        encoding = self.sql(expression, "encoding")
    1981        encoding = f" ENCODING {encoding}" if encoding else ""
    1982        return self.func(
    1983            "JSON_OBJECT",
    1984            *expression.expressions,
    1985            suffix=f"{null_handling}{unique_keys}{return_type}{format_json}{encoding})",
    1986        )

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

    1988    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    1989        this = self.sql(expression, "this")
    1990        kind = self.sql(expression, "kind")
    1991        path = self.sql(expression, "path")
    1992        path = f" {path}" if path else ""
    1993        as_json = " AS JSON" if expression.args.get("as_json") else ""
    1994        return f"{this} {kind}{path}{as_json}"

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

    1996    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    1997        this = self.sql(expression, "this")
    1998        path = self.sql(expression, "path")
    1999        path = f", {path}" if path else ""
    2000        expressions = self.expressions(expression)
    2001        with_ = (
    2002            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    2003            if expressions
    2004            else ""
    2005        )
    2006        return f"OPENJSON({this}{path}){with_}"

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

    2008    def in_sql(self, expression: exp.In) -> str:
    2009        query = expression.args.get("query")
    2010        unnest = expression.args.get("unnest")
    2011        field = expression.args.get("field")
    2012        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    2013
    2014        if query:
    2015            in_sql = self.wrap(query)
    2016        elif unnest:
    2017            in_sql = self.in_unnest_op(unnest)
    2018        elif field:
    2019            in_sql = self.sql(field)
    2020        else:
    2021            in_sql = f"({self.expressions(expression, flat=True)})"
    2022
    2023        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"

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

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

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

    2028    def interval_sql(self, expression: exp.Interval) -> str:
    2029        unit = self.sql(expression, "unit")
    2030        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    2031            unit = self.TIME_PART_SINGULARS.get(unit.lower(), unit)
    2032        unit = f" {unit}" if unit else ""
    2033
    2034        if self.SINGLE_STRING_INTERVAL:
    2035            this = expression.this.name if expression.this else ""
    2036            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    2037
    2038        this = self.sql(expression, "this")
    2039        if this:
    2040            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    2041            this = f" {this}" if unwrapped else f" ({this})"
    2042
    2043        return f"INTERVAL{this}{unit}"

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

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

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

    2048    def reference_sql(self, expression: exp.Reference) -> str:
    2049        this = self.sql(expression, "this")
    2050        expressions = self.expressions(expression, flat=True)
    2051        expressions = f"({expressions})" if expressions else ""
    2052        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2053        options = f" {options}" if options else ""
    2054        return f"REFERENCES {this}{expressions}{options}"

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

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

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

    2059    def paren_sql(self, expression: exp.Paren) -> str:
    2060        if isinstance(expression.unnest(), exp.Select):
    2061            sql = self.wrap(expression)
    2062        else:
    2063            sql = self.seg(self.indent(self.sql(expression, "this")), sep="")
    2064            sql = f"({sql}{self.seg(')', sep='')}"
    2065
    2066        return self.prepend_ctes(expression, sql)

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

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

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

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

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

    2077    def alias_sql(self, expression: exp.Alias) -> str:
    2078        alias = self.sql(expression, "alias")
    2079        alias = f" AS {alias}" if alias else ""
    2080        return f"{self.sql(expression, 'this')}{alias}"

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

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

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

    2085    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    2086        this = self.sql(expression, "this")
    2087        zone = self.sql(expression, "zone")
    2088        return f"{this} AT TIME ZONE {zone}"

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

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

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

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

def xor_sql(self, expression: sqlglot.expressions.Xor) -> str: View Source

    2096    def xor_sql(self, expression: exp.Xor) -> str:
    2097        return self.connector_sql(expression, "XOR")

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

    2099    def connector_sql(self, expression: exp.Connector, op: str) -> str:
    2100        if not self.pretty:
    2101            return self.binary(expression, op)
    2102
    2103        sqls = tuple(
    2104            self.maybe_comment(self.sql(e), e, e.parent.comments or []) if i != 1 else self.sql(e)
    2105            for i, e in enumerate(expression.flatten(unnest=False))
    2106        )
    2107
    2108        sep = "\n" if self.text_width(sqls) > self.max_text_width else " "
    2109        return f"{sep}{op} ".join(sqls)

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

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

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

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

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

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

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

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

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

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

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

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

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

    2129    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    2130        format_sql = self.sql(expression, "format")
    2131        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    2132        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

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

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

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

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

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

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

    2144    def comment_sql(self, expression: exp.Comment) -> str:
    2145        this = self.sql(expression, "this")
    2146        kind = expression.args["kind"]
    2147        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    2148        expression_sql = self.sql(expression, "expression")
    2149        return f"COMMENT{exists_sql}ON {kind} {this} IS {expression_sql}"

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

    2151    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    2152        this = self.sql(expression, "this")
    2153        delete = " DELETE" if expression.args.get("delete") else ""
    2154        recompress = self.sql(expression, "recompress")
    2155        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    2156        to_disk = self.sql(expression, "to_disk")
    2157        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    2158        to_volume = self.sql(expression, "to_volume")
    2159        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    2160        return f"{this}{delete}{recompress}{to_disk}{to_volume}"

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

    2162    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    2163        where = self.sql(expression, "where")
    2164        group = self.sql(expression, "group")
    2165        aggregates = self.expressions(expression, key="aggregates")
    2166        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    2167
    2168        if not (where or group or aggregates) and len(expression.expressions) == 1:
    2169            return f"TTL {self.expressions(expression, flat=True)}"
    2170
    2171        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"

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

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

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

    2176    def commit_sql(self, expression: exp.Commit) -> str:
    2177        chain = expression.args.get("chain")
    2178        if chain is not None:
    2179            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    2180
    2181        return f"COMMIT{chain or ''}"

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

    2183    def rollback_sql(self, expression: exp.Rollback) -> str:
    2184        savepoint = expression.args.get("savepoint")
    2185        savepoint = f" TO {savepoint}" if savepoint else ""
    2186        return f"ROLLBACK{savepoint}"

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

    2188    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    2189        this = self.sql(expression, "this")
    2190
    2191        dtype = self.sql(expression, "dtype")
    2192        if dtype:
    2193            collate = self.sql(expression, "collate")
    2194            collate = f" COLLATE {collate}" if collate else ""
    2195            using = self.sql(expression, "using")
    2196            using = f" USING {using}" if using else ""
    2197            return f"ALTER COLUMN {this} TYPE {dtype}{collate}{using}"
    2198
    2199        default = self.sql(expression, "default")
    2200        if default:
    2201            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    2202
    2203        if not expression.args.get("drop"):
    2204            self.unsupported("Unsupported ALTER COLUMN syntax")
    2205
    2206        return f"ALTER COLUMN {this} DROP DEFAULT"

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

    2208    def renametable_sql(self, expression: exp.RenameTable) -> str:
    2209        if not self.RENAME_TABLE_WITH_DB:
    2210            # Remove db from tables
    2211            expression = expression.transform(
    2212                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    2213            )
    2214        this = self.sql(expression, "this")
    2215        return f"RENAME TO {this}"

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

    2217    def altertable_sql(self, expression: exp.AlterTable) -> str:
    2218        actions = expression.args["actions"]
    2219
    2220        if isinstance(actions[0], exp.ColumnDef):
    2221            actions = self.expressions(expression, key="actions", prefix="ADD COLUMN ")
    2222        elif isinstance(actions[0], exp.Schema):
    2223            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    2224        elif isinstance(actions[0], exp.Delete):
    2225            actions = self.expressions(expression, key="actions", flat=True)
    2226        else:
    2227            actions = self.expressions(expression, key="actions")
    2228
    2229        exists = " IF EXISTS" if expression.args.get("exists") else ""
    2230        return f"ALTER TABLE{exists} {self.sql(expression, 'this')} {actions}"

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

    2232    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    2233        expressions = self.expressions(expression)
    2234        exists = " IF EXISTS " if expression.args.get("exists") else " "
    2235        return f"DROP{exists}{expressions}"

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

    2237    def addconstraint_sql(self, expression: exp.AddConstraint) -> str:
    2238        this = self.sql(expression, "this")
    2239        expression_ = self.sql(expression, "expression")
    2240        add_constraint = f"ADD CONSTRAINT {this}" if this else "ADD"
    2241
    2242        enforced = expression.args.get("enforced")
    2243        if enforced is not None:
    2244            return f"{add_constraint} CHECK ({expression_}){' ENFORCED' if enforced else ''}"
    2245
    2246        return f"{add_constraint} {expression_}"

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

    2248    def distinct_sql(self, expression: exp.Distinct) -> str:
    2249        this = self.expressions(expression, flat=True)
    2250        this = f" {this}" if this else ""
    2251
    2252        on = self.sql(expression, "on")
    2253        on = f" ON {on}" if on else ""
    2254        return f"DISTINCT{this}{on}"

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

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

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

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

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

    2262    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    2263        return self.sql(
    2264            exp.Cast(
    2265                this=exp.Div(this=expression.this, expression=expression.expression),
    2266                to=exp.DataType(this=exp.DataType.Type.INT),
    2267            )
    2268        )

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

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

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

    2273    def safedpipe_sql(self, expression: exp.SafeDPipe) -> str:
    2274        if self.STRICT_STRING_CONCAT:
    2275            return self.func("CONCAT", *(exp.cast(e, "text") for e in expression.flatten()))
    2276        return self.dpipe_sql(expression)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    2311    def is_sql(self, expression: exp.Is) -> str:
    2312        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    2313            return self.sql(
    2314                expression.this if expression.expression.this else exp.not_(expression.this)
    2315            )
    2316        return self.binary(expression, "IS")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    2360    def use_sql(self, expression: exp.Use) -> str:
    2361        kind = self.sql(expression, "kind")
    2362        kind = f" {kind}" if kind else ""
    2363        this = self.sql(expression, "this")
    2364        this = f" {this}" if this else ""
    2365        return f"USE{kind}{this}"

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

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

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

    2371    def function_fallback_sql(self, expression: exp.Func) -> str:
    2372        args = []
    2373
    2374        for key in expression.arg_types:
    2375            arg_value = expression.args.get(key)
    2376
    2377            if isinstance(arg_value, list):
    2378                for value in arg_value:
    2379                    args.append(value)
    2380            elif arg_value is not None:
    2381                args.append(arg_value)
    2382
    2383        if self.normalize_functions:
    2384            name = expression.sql_name()
    2385        else:
    2386            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
    2387
    2388        return self.func(name, *args)

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

    2390    def func(
    2391        self,
    2392        name: str,
    2393        *args: t.Optional[exp.Expression | str],
    2394        prefix: str = "(",
    2395        suffix: str = ")",
    2396    ) -> str:
    2397        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

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

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

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

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

    2408    def format_time(self, expression: exp.Expression) -> t.Optional[str]:
    2409        return format_time(
    2410            self.sql(expression, "format"), self.INVERSE_TIME_MAPPING, self.INVERSE_TIME_TRIE
    2411        )

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

    2413    def expressions(
    2414        self,
    2415        expression: t.Optional[exp.Expression] = None,
    2416        key: t.Optional[str] = None,
    2417        sqls: t.Optional[t.List[str]] = None,
    2418        flat: bool = False,
    2419        indent: bool = True,
    2420        skip_first: bool = False,
    2421        sep: str = ", ",
    2422        prefix: str = "",
    2423    ) -> str:
    2424        expressions = expression.args.get(key or "expressions") if expression else sqls
    2425
    2426        if not expressions:
    2427            return ""
    2428
    2429        if flat:
    2430            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
    2431
    2432        num_sqls = len(expressions)
    2433
    2434        # These are calculated once in case we have the leading_comma / pretty option set, correspondingly
    2435        pad = " " * self.pad
    2436        stripped_sep = sep.strip()
    2437
    2438        result_sqls = []
    2439        for i, e in enumerate(expressions):
    2440            sql = self.sql(e, comment=False)
    2441            if not sql:
    2442                continue
    2443
    2444            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    2445
    2446            if self.pretty:
    2447                if self.leading_comma:
    2448                    result_sqls.append(f"{sep if i > 0 else pad}{prefix}{sql}{comments}")
    2449                else:
    2450                    result_sqls.append(
    2451                        f"{prefix}{sql}{stripped_sep if i + 1 < num_sqls else ''}{comments}"
    2452                    )
    2453            else:
    2454                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    2455
    2456        result_sql = "\n".join(result_sqls) if self.pretty else "".join(result_sqls)
    2457        return self.indent(result_sql, skip_first=skip_first) if indent else result_sql

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

    2459    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    2460        flat = flat or isinstance(expression.parent, exp.Properties)
    2461        expressions_sql = self.expressions(expression, flat=flat)
    2462        if flat:
    2463            return f"{op} {expressions_sql}"
    2464        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"

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

    2466    def naked_property(self, expression: exp.Property) -> str:
    2467        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    2468        if not property_name:
    2469            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    2470        return f"{property_name} {self.sql(expression, 'this')}"

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

    2472    def set_operation(self, expression: exp.Expression, op: str) -> str:
    2473        this = self.sql(expression, "this")
    2474        op = self.seg(op)
    2475        return self.query_modifiers(
    2476            expression, f"{this}{op}{self.sep()}{self.sql(expression, 'expression')}"
    2477        )

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

    2479    def tag_sql(self, expression: exp.Tag) -> str:
    2480        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

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

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

    2485    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    2486        this = self.sql(expression, "this")
    2487        expressions = self.no_identify(self.expressions, expression)
    2488        expressions = (
    2489            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    2490        )
    2491        return f"{this}{expressions}"

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

    2493    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    2494        this = self.sql(expression, "this")
    2495        expressions = self.expressions(expression, flat=True)
    2496        return f"{this}({expressions})"

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

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

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

    2501    def when_sql(self, expression: exp.When) -> str:
    2502        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    2503        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    2504        condition = self.sql(expression, "condition")
    2505        condition = f" AND {condition}" if condition else ""
    2506
    2507        then_expression = expression.args.get("then")
    2508        if isinstance(then_expression, exp.Insert):
    2509            then = f"INSERT {self.sql(then_expression, 'this')}"
    2510            if "expression" in then_expression.args:
    2511                then += f" VALUES {self.sql(then_expression, 'expression')}"
    2512        elif isinstance(then_expression, exp.Update):
    2513            if isinstance(then_expression.args.get("expressions"), exp.Star):
    2514                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    2515            else:
    2516                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    2517        else:
    2518            then = self.sql(then_expression)
    2519        return f"WHEN {matched}{source}{condition} THEN {then}"

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

    2521    def merge_sql(self, expression: exp.Merge) -> str:
    2522        this = self.sql(expression, "this")
    2523        using = f"USING {self.sql(expression, 'using')}"
    2524        on = f"ON {self.sql(expression, 'on')}"
    2525        return f"MERGE INTO {this} {using} {on} {self.expressions(expression, sep=' ')}"

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

    2527    def tochar_sql(self, expression: exp.ToChar) -> str:
    2528        if expression.args.get("format"):
    2529            self.unsupported("Format argument unsupported for TO_CHAR/TO_VARCHAR function")
    2530
    2531        return self.sql(exp.cast(expression.this, "text"))

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

    2533    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    2534        this = self.sql(expression, "this")
    2535        kind = self.sql(expression, "kind")
    2536        settings_sql = self.expressions(expression, key="settings", sep=" ")
    2537        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    2538        return f"{this}({kind}{args})"

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

    2540    def dictrange_sql(self, expression: exp.DictRange) -> str:
    2541        this = self.sql(expression, "this")
    2542        max = self.sql(expression, "max")
    2543        min = self.sql(expression, "min")
    2544        return f"{this}(MIN {min} MAX {max})"

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

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

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

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

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

    2552    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    2553        expressions = self.expressions(expression, key="expressions", flat=True)
    2554        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    2555        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    2556        buckets = self.sql(expression, "buckets")
    2557        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"

def anyvalue_sql(self, expression: sqlglot.expressions.AnyValue) -> str: View Source

    2559    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    2560        this = self.sql(expression, "this")
    2561        having = self.sql(expression, "having")
    2562
    2563        if having:
    2564            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    2565
    2566        return self.func("ANY_VALUE", this)

def querytransform_sql(self, expression: sqlglot.expressions.QueryTransform) -> str: View Source

    2568    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
    2569        transform = self.func("TRANSFORM", *expression.expressions)
    2570        row_format_before = self.sql(expression, "row_format_before")
    2571        row_format_before = f" {row_format_before}" if row_format_before else ""
    2572        record_writer = self.sql(expression, "record_writer")
    2573        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
    2574        using = f" USING {self.sql(expression, 'command_script')}"
    2575        schema = self.sql(expression, "schema")
    2576        schema = f" AS {schema}" if schema else ""
    2577        row_format_after = self.sql(expression, "row_format_after")
    2578        row_format_after = f" {row_format_after}" if row_format_after else ""
    2579        record_reader = self.sql(expression, "record_reader")
    2580        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
    2581        return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}"

def indexconstraintoption_sql(self, expression: sqlglot.expressions.IndexConstraintOption) -> str: View Source

    2583    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
    2584        key_block_size = self.sql(expression, "key_block_size")
    2585        if key_block_size:
    2586            return f"KEY_BLOCK_SIZE = {key_block_size}"
    2587
    2588        using = self.sql(expression, "using")
    2589        if using:
    2590            return f"USING {using}"
    2591
    2592        parser = self.sql(expression, "parser")
    2593        if parser:
    2594            return f"WITH PARSER {parser}"
    2595
    2596        comment = self.sql(expression, "comment")
    2597        if comment:
    2598            return f"COMMENT {comment}"
    2599
    2600        visible = expression.args.get("visible")
    2601        if visible is not None:
    2602            return "VISIBLE" if visible else "INVISIBLE"
    2603
    2604        engine_attr = self.sql(expression, "engine_attr")
    2605        if engine_attr:
    2606            return f"ENGINE_ATTRIBUTE = {engine_attr}"
    2607
    2608        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
    2609        if secondary_engine_attr:
    2610            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
    2611
    2612        self.unsupported("Unsupported index constraint option.")
    2613        return ""

def indexcolumnconstraint_sql(self, expression: sqlglot.expressions.IndexColumnConstraint) -> str: View Source

    2615    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
    2616        kind = self.sql(expression, "kind")
    2617        kind = f"{kind} INDEX" if kind else "INDEX"
    2618        this = self.sql(expression, "this")
    2619        this = f" {this}" if this else ""
    2620        type_ = self.sql(expression, "type")
    2621        type_ = f" USING {type_}" if type_ else ""
    2622        schema = self.sql(expression, "schema")
    2623        schema = f" {schema}" if schema else ""
    2624        options = self.expressions(expression, key="options", sep=" ")
    2625        options = f" {options}" if options else ""
    2626        return f"{kind}{this}{type_}{schema}{options}"

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

    2629def cached_generator(
    2630    cache: t.Optional[t.Dict[int, str]] = None
    2631) -> t.Callable[[exp.Expression], str]:
    2632    """Returns a cached generator."""
    2633    cache = {} if cache is None else cache
    2634    generator = Generator(normalize=True, identify="safe")
    2635    return lambda e: generator.generate(e, cache)

Returns a cached generator.