sqlglot.generator API documentation

Edit on GitHub

# sqlglot.generator

View Source

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

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

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

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

    328    def __init__(
    329        self,
    330        pretty: t.Optional[bool] = None,
    331        identify: str | bool = False,
    332        normalize: bool = False,
    333        pad: int = 2,
    334        indent: int = 2,
    335        normalize_functions: t.Optional[str | bool] = None,
    336        unsupported_level: ErrorLevel = ErrorLevel.WARN,
    337        max_unsupported: int = 3,
    338        leading_comma: bool = False,
    339        max_text_width: int = 80,
    340        comments: bool = True,
    341    ):
    342        import sqlglot
    343
    344        self.pretty = pretty if pretty is not None else sqlglot.pretty
    345        self.identify = identify
    346        self.normalize = normalize
    347        self.pad = pad
    348        self._indent = indent
    349        self.unsupported_level = unsupported_level
    350        self.max_unsupported = max_unsupported
    351        self.leading_comma = leading_comma
    352        self.max_text_width = max_text_width
    353        self.comments = comments
    354
    355        # This is both a Dialect property and a Generator argument, so we prioritize the latter
    356        self.normalize_functions = (
    357            self.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions
    358        )
    359
    360        self.unsupported_messages: t.List[str] = []
    361        self._escaped_quote_end: str = self.STRING_ESCAPE + self.QUOTE_END
    362        self._escaped_identifier_end: str = self.IDENTIFIER_ESCAPE + self.IDENTIFIER_END
    363        self._cache: t.Optional[t.Dict[int, str]] = None

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

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

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

    401    def unsupported(self, message: str) -> None:
    402        if self.unsupported_level == ErrorLevel.IMMEDIATE:
    403            raise UnsupportedError(message)
    404        self.unsupported_messages.append(message)

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

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

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

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

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

    412    def pad_comment(self, comment: str) -> str:
    413        comment = " " + comment if comment[0].strip() else comment
    414        comment = comment + " " if comment[-1].strip() else comment
    415        return comment

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

    417    def maybe_comment(
    418        self,
    419        sql: str,
    420        expression: t.Optional[exp.Expression] = None,
    421        comments: t.Optional[t.List[str]] = None,
    422    ) -> str:
    423        comments = (
    424            ((expression and expression.comments) if comments is None else comments)  # type: ignore
    425            if self.comments
    426            else None
    427        )
    428
    429        if not comments or isinstance(expression, exp.Binary):
    430            return sql
    431
    432        sep = "\n" if self.pretty else " "
    433        comments_sql = sep.join(
    434            f"/*{self.pad_comment(comment)}*/" for comment in comments if comment
    435        )
    436
    437        if not comments_sql:
    438            return sql
    439
    440        if isinstance(expression, self.WITH_SEPARATED_COMMENTS):
    441            return (
    442                f"{self.sep()}{comments_sql}{sql}"
    443                if sql[0].isspace()
    444                else f"{comments_sql}{self.sep()}{sql}"
    445            )
    446
    447        return f"{sql} {comments_sql}"

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

    449    def wrap(self, expression: exp.Expression | str) -> str:
    450        this_sql = self.indent(
    451            self.sql(expression)
    452            if isinstance(expression, (exp.Select, exp.Union))
    453            else self.sql(expression, "this"),
    454            level=1,
    455            pad=0,
    456        )
    457        return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"

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

    459    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
    460        original = self.identify
    461        self.identify = False
    462        result = func(*args, **kwargs)
    463        self.identify = original
    464        return result

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

    466    def normalize_func(self, name: str) -> str:
    467        if self.normalize_functions == "upper" or self.normalize_functions is True:
    468            return name.upper()
    469        if self.normalize_functions == "lower":
    470            return name.lower()
    471        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

    473    def indent(
    474        self,
    475        sql: str,
    476        level: int = 0,
    477        pad: t.Optional[int] = None,
    478        skip_first: bool = False,
    479        skip_last: bool = False,
    480    ) -> str:
    481        if not self.pretty:
    482            return sql
    483
    484        pad = self.pad if pad is None else pad
    485        lines = sql.split("\n")
    486
    487        return "\n".join(
    488            line
    489            if (skip_first and i == 0) or (skip_last and i == len(lines) - 1)
    490            else f"{' ' * (level * self._indent + pad)}{line}"
    491            for i, line in enumerate(lines)
    492        )

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

    494    def sql(
    495        self,
    496        expression: t.Optional[str | exp.Expression],
    497        key: t.Optional[str] = None,
    498        comment: bool = True,
    499    ) -> str:
    500        if not expression:
    501            return ""
    502
    503        if isinstance(expression, str):
    504            return expression
    505
    506        if key:
    507            value = expression.args.get(key)
    508            if value:
    509                return self.sql(value)
    510            return ""
    511
    512        if self._cache is not None:
    513            expression_id = hash(expression)
    514
    515            if expression_id in self._cache:
    516                return self._cache[expression_id]
    517
    518        transform = self.TRANSFORMS.get(expression.__class__)
    519
    520        if callable(transform):
    521            sql = transform(self, expression)
    522        elif transform:
    523            sql = transform
    524        elif isinstance(expression, exp.Expression):
    525            exp_handler_name = f"{expression.key}_sql"
    526
    527            if hasattr(self, exp_handler_name):
    528                sql = getattr(self, exp_handler_name)(expression)
    529            elif isinstance(expression, exp.Func):
    530                sql = self.function_fallback_sql(expression)
    531            elif isinstance(expression, exp.Property):
    532                sql = self.property_sql(expression)
    533            else:
    534                raise ValueError(f"Unsupported expression type {expression.__class__.__name__}")
    535        else:
    536            raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}")
    537
    538        sql = self.maybe_comment(sql, expression) if self.comments and comment else sql
    539
    540        if self._cache is not None:
    541            self._cache[expression_id] = sql
    542        return sql

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

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

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

    549    def cache_sql(self, expression: exp.Cache) -> str:
    550        lazy = " LAZY" if expression.args.get("lazy") else ""
    551        table = self.sql(expression, "this")
    552        options = expression.args.get("options")
    553        options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else ""
    554        sql = self.sql(expression, "expression")
    555        sql = f" AS{self.sep()}{sql}" if sql else ""
    556        sql = f"CACHE{lazy} TABLE {table}{options}{sql}"
    557        return self.prepend_ctes(expression, sql)

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

    559    def characterset_sql(self, expression: exp.CharacterSet) -> str:
    560        if isinstance(expression.parent, exp.Cast):
    561            return f"CHAR CHARACTER SET {self.sql(expression, 'this')}"
    562        default = "DEFAULT " if expression.args.get("default") else ""
    563        return f"{default}CHARACTER SET={self.sql(expression, 'this')}"

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

    565    def column_sql(self, expression: exp.Column) -> str:
    566        join_mark = " (+)" if expression.args.get("join_mark") else ""
    567
    568        if join_mark and not self.COLUMN_JOIN_MARKS_SUPPORTED:
    569            join_mark = ""
    570            self.unsupported("Outer join syntax using the (+) operator is not supported.")
    571
    572        column = ".".join(
    573            self.sql(part)
    574            for part in (
    575                expression.args.get("catalog"),
    576                expression.args.get("db"),
    577                expression.args.get("table"),
    578                expression.args.get("this"),
    579            )
    580            if part
    581        )
    582
    583        return f"{column}{join_mark}"

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

    585    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
    586        this = self.sql(expression, "this")
    587        this = f" {this}" if this else ""
    588        position = self.sql(expression, "position")
    589        return f"{position}{this}"

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

    591    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
    592        column = self.sql(expression, "this")
    593        kind = self.sql(expression, "kind")
    594        constraints = self.expressions(expression, key="constraints", sep=" ", flat=True)
    595        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
    596        kind = f"{sep}{kind}" if kind else ""
    597        constraints = f" {constraints}" if constraints else ""
    598        position = self.sql(expression, "position")
    599        position = f" {position}" if position else ""
    600
    601        return f"{exists}{column}{kind}{constraints}{position}"

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

    603    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
    604        this = self.sql(expression, "this")
    605        kind_sql = self.sql(expression, "kind").strip()
    606        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql

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

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

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

    611    def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str:
    612        if isinstance(expression.this, list):
    613            this = self.wrap(self.expressions(expression, key="this", flat=True))
    614        else:
    615            this = self.sql(expression, "this")
    616
    617        return f"COMPRESS {this}"

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

    619    def generatedasidentitycolumnconstraint_sql(
    620        self, expression: exp.GeneratedAsIdentityColumnConstraint
    621    ) -> str:
    622        this = ""
    623        if expression.this is not None:
    624            on_null = "ON NULL " if expression.args.get("on_null") else ""
    625            this = " ALWAYS " if expression.this else f" BY DEFAULT {on_null}"
    626
    627        start = expression.args.get("start")
    628        start = f"START WITH {start}" if start else ""
    629        increment = expression.args.get("increment")
    630        increment = f" INCREMENT BY {increment}" if increment else ""
    631        minvalue = expression.args.get("minvalue")
    632        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    633        maxvalue = expression.args.get("maxvalue")
    634        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    635        cycle = expression.args.get("cycle")
    636        cycle_sql = ""
    637
    638        if cycle is not None:
    639            cycle_sql = f"{' NO' if not cycle else ''} CYCLE"
    640            cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql
    641
    642        sequence_opts = ""
    643        if start or increment or cycle_sql:
    644            sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}"
    645            sequence_opts = f" ({sequence_opts.strip()})"
    646
    647        expr = self.sql(expression, "expression")
    648        expr = f"({expr})" if expr else "IDENTITY"
    649
    650        return f"GENERATED{this}AS {expr}{sequence_opts}"

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

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

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

    655    def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str:
    656        desc = expression.args.get("desc")
    657        if desc is not None:
    658            return f"PRIMARY KEY{' DESC' if desc else ' ASC'}"
    659        return f"PRIMARY KEY"

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

    661    def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str:
    662        this = self.sql(expression, "this")
    663        this = f" {this}" if this else ""
    664        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

    666    def createable_sql(
    667        self, expression: exp.Create, locations: dict[exp.Properties.Location, list[exp.Property]]
    668    ) -> str:
    669        return self.sql(expression, "this")

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

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

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

    756    def clone_sql(self, expression: exp.Clone) -> str:
    757        this = self.sql(expression, "this")
    758        when = self.sql(expression, "when")
    759
    760        if when:
    761            kind = self.sql(expression, "kind")
    762            expr = self.sql(expression, "expression")
    763            return f"CLONE {this} {when} ({kind} => {expr})"
    764
    765        return f"CLONE {this}"

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

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

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

    770    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
    771        with_ = self.sql(expression, "with")
    772        if with_:
    773            sql = f"{with_}{self.sep()}{sql}"
    774        return sql

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

    776    def with_sql(self, expression: exp.With) -> str:
    777        sql = self.expressions(expression, flat=True)
    778        recursive = "RECURSIVE " if expression.args.get("recursive") else ""
    779
    780        return f"WITH {recursive}{sql}"

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

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

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

    786    def tablealias_sql(self, expression: exp.TableAlias) -> str:
    787        alias = self.sql(expression, "this")
    788        columns = self.expressions(expression, key="columns", flat=True)
    789        columns = f"({columns})" if columns else ""
    790        return f"{alias}{columns}"

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

    792    def bitstring_sql(self, expression: exp.BitString) -> str:
    793        this = self.sql(expression, "this")
    794        if self.BIT_START:
    795            return f"{self.BIT_START}{this}{self.BIT_END}"
    796        return f"{int(this, 2)}"

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

    798    def hexstring_sql(self, expression: exp.HexString) -> str:
    799        this = self.sql(expression, "this")
    800        if self.HEX_START:
    801            return f"{self.HEX_START}{this}{self.HEX_END}"
    802        return f"{int(this, 16)}"

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

    804    def bytestring_sql(self, expression: exp.ByteString) -> str:
    805        this = self.sql(expression, "this")
    806        if self.BYTE_START:
    807            return f"{self.BYTE_START}{this}{self.BYTE_END}"
    808        return this

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

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

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

    814    def datatypesize_sql(self, expression: exp.DataTypeSize) -> str:
    815        this = self.sql(expression, "this")
    816        specifier = self.sql(expression, "expression")
    817        specifier = f" {specifier}" if specifier else ""
    818        return f"{this}{specifier}"

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

    820    def datatype_sql(self, expression: exp.DataType) -> str:
    821        type_value = expression.this
    822        type_sql = self.TYPE_MAPPING.get(type_value, type_value.value)
    823        nested = ""
    824        interior = self.expressions(expression, flat=True)
    825        values = ""
    826        if interior:
    827            if expression.args.get("nested"):
    828                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
    829                if expression.args.get("values") is not None:
    830                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
    831                    values = self.expressions(expression, key="values", flat=True)
    832                    values = f"{delimiters[0]}{values}{delimiters[1]}"
    833            else:
    834                nested = f"({interior})"
    835
    836        return f"{type_sql}{nested}{values}"

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

    838    def directory_sql(self, expression: exp.Directory) -> str:
    839        local = "LOCAL " if expression.args.get("local") else ""
    840        row_format = self.sql(expression, "row_format")
    841        row_format = f" {row_format}" if row_format else ""
    842        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"

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

    844    def delete_sql(self, expression: exp.Delete) -> str:
    845        this = self.sql(expression, "this")
    846        this = f" FROM {this}" if this else ""
    847        using = self.sql(expression, "using")
    848        using = f" USING {using}" if using else ""
    849        where = self.sql(expression, "where")
    850        returning = self.sql(expression, "returning")
    851        limit = self.sql(expression, "limit")
    852        tables = self.expressions(expression, key="tables")
    853        tables = f" {tables}" if tables else ""
    854        if self.RETURNING_END:
    855            expression_sql = f"{this}{using}{where}{returning}{limit}"
    856        else:
    857            expression_sql = f"{returning}{this}{using}{where}{limit}"
    858        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")

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

    860    def drop_sql(self, expression: exp.Drop) -> str:
    861        this = self.sql(expression, "this")
    862        kind = expression.args["kind"]
    863        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    864        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    865        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    866        cascade = " CASCADE" if expression.args.get("cascade") else ""
    867        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
    868        purge = " PURGE" if expression.args.get("purge") else ""
    869        return (
    870            f"DROP{temporary}{materialized} {kind}{exists_sql}{this}{cascade}{constraints}{purge}"
    871        )

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

    873    def except_sql(self, expression: exp.Except) -> str:
    874        return self.prepend_ctes(
    875            expression,
    876            self.set_operation(expression, self.except_op(expression)),
    877        )

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

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

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

    882    def fetch_sql(self, expression: exp.Fetch) -> str:
    883        direction = expression.args.get("direction")
    884        direction = f" {direction.upper()}" if direction else ""
    885        count = expression.args.get("count")
    886        count = f" {count}" if count else ""
    887        if expression.args.get("percent"):
    888            count = f"{count} PERCENT"
    889        with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY"
    890        return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}"

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

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

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

    897    def hint_sql(self, expression: exp.Hint) -> str:
    898        if not self.QUERY_HINTS:
    899            self.unsupported("Hints are not supported")
    900            return ""
    901
    902        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"

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

    904    def index_sql(self, expression: exp.Index) -> str:
    905        unique = "UNIQUE " if expression.args.get("unique") else ""
    906        primary = "PRIMARY " if expression.args.get("primary") else ""
    907        amp = "AMP " if expression.args.get("amp") else ""
    908        name = self.sql(expression, "this")
    909        name = f"{name} " if name else ""
    910        table = self.sql(expression, "table")
    911        table = f"{self.INDEX_ON} {table} " if table else ""
    912        using = self.sql(expression, "using")
    913        using = f"USING {using} " if using else ""
    914        index = "INDEX " if not table else ""
    915        columns = self.expressions(expression, key="columns", flat=True)
    916        columns = f"({columns})" if columns else ""
    917        partition_by = self.expressions(expression, key="partition_by", flat=True)
    918        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
    919        return f"{unique}{primary}{amp}{index}{name}{table}{using}{columns}{partition_by}"

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

    921    def identifier_sql(self, expression: exp.Identifier) -> str:
    922        text = expression.name
    923        lower = text.lower()
    924        text = lower if self.normalize and not expression.quoted else text
    925        text = text.replace(self.IDENTIFIER_END, self._escaped_identifier_end)
    926        if (
    927            expression.quoted
    928            or self.can_identify(text, self.identify)
    929            or lower in self.RESERVED_KEYWORDS
    930            or (not self.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
    931        ):
    932            text = f"{self.IDENTIFIER_START}{text}{self.IDENTIFIER_END}"
    933        return text

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

    935    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    936        input_format = self.sql(expression, "input_format")
    937        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    938        output_format = self.sql(expression, "output_format")
    939        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    940        return self.sep().join((input_format, output_format))

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

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

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

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

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

    949    def properties_sql(self, expression: exp.Properties) -> str:
    950        root_properties = []
    951        with_properties = []
    952
    953        for p in expression.expressions:
    954            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    955            if p_loc == exp.Properties.Location.POST_WITH:
    956                with_properties.append(p)
    957            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    958                root_properties.append(p)
    959
    960        return self.root_properties(
    961            exp.Properties(expressions=root_properties)
    962        ) + self.with_properties(exp.Properties(expressions=with_properties))

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

    964    def root_properties(self, properties: exp.Properties) -> str:
    965        if properties.expressions:
    966            return self.sep() + self.expressions(properties, indent=False, sep=" ")
    967        return ""

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

    969    def properties(
    970        self,
    971        properties: exp.Properties,
    972        prefix: str = "",
    973        sep: str = ", ",
    974        suffix: str = "",
    975        wrapped: bool = True,
    976    ) -> str:
    977        if properties.expressions:
    978            expressions = self.expressions(properties, sep=sep, indent=False)
    979            expressions = self.wrap(expressions) if wrapped else expressions
    980            return f"{prefix}{' ' if prefix and prefix != ' ' else ''}{expressions}{suffix}"
    981        return ""

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

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

     986    def locate_properties(
     987        self, properties: exp.Properties
     988    ) -> t.Dict[exp.Properties.Location, list[exp.Property]]:
     989        properties_locs: t.Dict[exp.Properties.Location, list[exp.Property]] = {
     990            key: [] for key in exp.Properties.Location
     991        }
     992
     993        for p in properties.expressions:
     994            p_loc = self.PROPERTIES_LOCATION[p.__class__]
     995            if p_loc == exp.Properties.Location.POST_NAME:
     996                properties_locs[exp.Properties.Location.POST_NAME].append(p)
     997            elif p_loc == exp.Properties.Location.POST_INDEX:
     998                properties_locs[exp.Properties.Location.POST_INDEX].append(p)
     999            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    1000                properties_locs[exp.Properties.Location.POST_SCHEMA].append(p)
    1001            elif p_loc == exp.Properties.Location.POST_WITH:
    1002                properties_locs[exp.Properties.Location.POST_WITH].append(p)
    1003            elif p_loc == exp.Properties.Location.POST_CREATE:
    1004                properties_locs[exp.Properties.Location.POST_CREATE].append(p)
    1005            elif p_loc == exp.Properties.Location.POST_ALIAS:
    1006                properties_locs[exp.Properties.Location.POST_ALIAS].append(p)
    1007            elif p_loc == exp.Properties.Location.POST_EXPRESSION:
    1008                properties_locs[exp.Properties.Location.POST_EXPRESSION].append(p)
    1009            elif p_loc == exp.Properties.Location.UNSUPPORTED:
    1010                self.unsupported(f"Unsupported property {p.key}")
    1011
    1012        return properties_locs

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

    1014    def property_sql(self, expression: exp.Property) -> str:
    1015        property_cls = expression.__class__
    1016        if property_cls == exp.Property:
    1017            return f"{expression.name}={self.sql(expression, 'value')}"
    1018
    1019        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    1020        if not property_name:
    1021            self.unsupported(f"Unsupported property {expression.key}")
    1022
    1023        return f"{property_name}={self.sql(expression, 'this')}"

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

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

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

    1030    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1031        no = "NO " if expression.args.get("no") else ""
    1032        protection = " PROTECTION" if expression.args.get("protection") else ""
    1033        return f"{no}FALLBACK{protection}"

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

    1035    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1036        no = "NO " if expression.args.get("no") else ""
    1037        local = expression.args.get("local")
    1038        local = f"{local} " if local else ""
    1039        dual = "DUAL " if expression.args.get("dual") else ""
    1040        before = "BEFORE " if expression.args.get("before") else ""
    1041        after = "AFTER " if expression.args.get("after") else ""
    1042        return f"{no}{local}{dual}{before}{after}JOURNAL"

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

    1044    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1045        freespace = self.sql(expression, "this")
    1046        percent = " PERCENT" if expression.args.get("percent") else ""
    1047        return f"FREESPACE={freespace}{percent}"

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

    1049    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1050        if expression.args.get("default"):
    1051            property = "DEFAULT"
    1052        elif expression.args.get("on"):
    1053            property = "ON"
    1054        else:
    1055            property = "OFF"
    1056        return f"CHECKSUM={property}"

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

    1058    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1059        if expression.args.get("no"):
    1060            return "NO MERGEBLOCKRATIO"
    1061        if expression.args.get("default"):
    1062            return "DEFAULT MERGEBLOCKRATIO"
    1063
    1064        percent = " PERCENT" if expression.args.get("percent") else ""
    1065        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"

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

    1067    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1068        default = expression.args.get("default")
    1069        minimum = expression.args.get("minimum")
    1070        maximum = expression.args.get("maximum")
    1071        if default or minimum or maximum:
    1072            if default:
    1073                prop = "DEFAULT"
    1074            elif minimum:
    1075                prop = "MINIMUM"
    1076            else:
    1077                prop = "MAXIMUM"
    1078            return f"{prop} DATABLOCKSIZE"
    1079        units = expression.args.get("units")
    1080        units = f" {units}" if units else ""
    1081        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"

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

    1083    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1084        autotemp = expression.args.get("autotemp")
    1085        always = expression.args.get("always")
    1086        default = expression.args.get("default")
    1087        manual = expression.args.get("manual")
    1088        never = expression.args.get("never")
    1089
    1090        if autotemp is not None:
    1091            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1092        elif always:
    1093            prop = "ALWAYS"
    1094        elif default:
    1095            prop = "DEFAULT"
    1096        elif manual:
    1097            prop = "MANUAL"
    1098        elif never:
    1099            prop = "NEVER"
    1100        return f"BLOCKCOMPRESSION={prop}"

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

    1102    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1103        no = expression.args.get("no")
    1104        no = " NO" if no else ""
    1105        concurrent = expression.args.get("concurrent")
    1106        concurrent = " CONCURRENT" if concurrent else ""
    1107
    1108        for_ = ""
    1109        if expression.args.get("for_all"):
    1110            for_ = " FOR ALL"
    1111        elif expression.args.get("for_insert"):
    1112            for_ = " FOR INSERT"
    1113        elif expression.args.get("for_none"):
    1114            for_ = " FOR NONE"
    1115        return f"WITH{no}{concurrent} ISOLATED LOADING{for_}"

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

    1117    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1118        kind = expression.args.get("kind")
    1119        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1120        for_or_in = expression.args.get("for_or_in")
    1121        lock_type = expression.args.get("lock_type")
    1122        override = " OVERRIDE" if expression.args.get("override") else ""
    1123        return f"LOCKING {kind}{this} {for_or_in} {lock_type}{override}"

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

    1125    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1126        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1127        statistics = expression.args.get("statistics")
    1128        statistics_sql = ""
    1129        if statistics is not None:
    1130            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1131        return f"{data_sql}{statistics_sql}"

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

    1133    def insert_sql(self, expression: exp.Insert) -> str:
    1134        overwrite = expression.args.get("overwrite")
    1135
    1136        if isinstance(expression.this, exp.Directory):
    1137            this = " OVERWRITE" if overwrite else " INTO"
    1138        else:
    1139            this = " OVERWRITE TABLE" if overwrite else " INTO"
    1140
    1141        alternative = expression.args.get("alternative")
    1142        alternative = f" OR {alternative}" if alternative else ""
    1143        ignore = " IGNORE" if expression.args.get("ignore") else ""
    1144
    1145        this = f"{this} {self.sql(expression, 'this')}"
    1146
    1147        exists = " IF EXISTS" if expression.args.get("exists") else ""
    1148        partition_sql = (
    1149            f" {self.sql(expression, 'partition')}" if expression.args.get("partition") else ""
    1150        )
    1151        where = self.sql(expression, "where")
    1152        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
    1153        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
    1154        conflict = self.sql(expression, "conflict")
    1155        returning = self.sql(expression, "returning")
    1156
    1157        if self.RETURNING_END:
    1158            expression_sql = f"{expression_sql}{conflict}{returning}"
    1159        else:
    1160            expression_sql = f"{returning}{expression_sql}{conflict}"
    1161
    1162        sql = f"INSERT{alternative}{ignore}{this}{exists}{partition_sql}{where}{expression_sql}"
    1163        return self.prepend_ctes(expression, sql)

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

    1165    def intersect_sql(self, expression: exp.Intersect) -> str:
    1166        return self.prepend_ctes(
    1167            expression,
    1168            self.set_operation(expression, self.intersect_op(expression)),
    1169        )

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

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

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

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

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

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

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

    1180    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1181        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1182        constraint = self.sql(expression, "constraint")
    1183        if constraint:
    1184            constraint = f"ON CONSTRAINT {constraint}"
    1185        key = self.expressions(expression, key="key", flat=True)
    1186        do = "" if expression.args.get("duplicate") else " DO "
    1187        nothing = "NOTHING" if expression.args.get("nothing") else ""
    1188        expressions = self.expressions(expression, flat=True)
    1189        set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
    1190        if expressions:
    1191            expressions = f"UPDATE {set_keyword}{expressions}"
    1192        return f"{self.seg(conflict)} {constraint}{key}{do}{nothing}{expressions}"

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

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

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

    1197    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1198        fields = expression.args.get("fields")
    1199        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1200        escaped = expression.args.get("escaped")
    1201        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1202        items = expression.args.get("collection_items")
    1203        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1204        keys = expression.args.get("map_keys")
    1205        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1206        lines = expression.args.get("lines")
    1207        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1208        null = expression.args.get("null")
    1209        null = f" NULL DEFINED AS {null}" if null else ""
    1210        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"

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

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

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

    1215    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1216        this = f"{self.sql(expression, 'this')} INDEX"
    1217        target = self.sql(expression, "target")
    1218        target = f" FOR {target}" if target else ""
    1219        return f"{this}{target} ({self.expressions(expression, flat=True)})"

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

    1221    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1222        table = ".".join(
    1223            part
    1224            for part in [
    1225                self.sql(expression, "catalog"),
    1226                self.sql(expression, "db"),
    1227                self.sql(expression, "this"),
    1228            ]
    1229            if part
    1230        )
    1231
    1232        alias = self.sql(expression, "alias")
    1233        alias = f"{sep}{alias}" if alias else ""
    1234        hints = self.expressions(expression, key="hints", sep=" ")
    1235        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
    1236        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    1237        pivots = f" {pivots}" if pivots else ""
    1238        joins = self.expressions(expression, key="joins", sep="", skip_first=True)
    1239        laterals = self.expressions(expression, key="laterals", sep="")
    1240        system_time = expression.args.get("system_time")
    1241        system_time = f" {self.sql(expression, 'system_time')}" if system_time else ""
    1242
    1243        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

    1245    def tablesample_sql(
    1246        self, expression: exp.TableSample, seed_prefix: str = "SEED", sep=" AS "
    1247    ) -> str:
    1248        if self.ALIAS_POST_TABLESAMPLE and expression.this.alias:
    1249            table = expression.this.copy()
    1250            table.set("alias", None)
    1251            this = self.sql(table)
    1252            alias = f"{sep}{self.sql(expression.this, 'alias')}"
    1253        else:
    1254            this = self.sql(expression, "this")
    1255            alias = ""
    1256        method = self.sql(expression, "method")
    1257        method = f"{method.upper()} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    1258        numerator = self.sql(expression, "bucket_numerator")
    1259        denominator = self.sql(expression, "bucket_denominator")
    1260        field = self.sql(expression, "bucket_field")
    1261        field = f" ON {field}" if field else ""
    1262        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    1263        percent = self.sql(expression, "percent")
    1264        percent = f"{percent} PERCENT" if percent else ""
    1265        rows = self.sql(expression, "rows")
    1266        rows = f"{rows} ROWS" if rows else ""
    1267        size = self.sql(expression, "size")
    1268        if size and self.TABLESAMPLE_SIZE_IS_PERCENT:
    1269            size = f"{size} PERCENT"
    1270        seed = self.sql(expression, "seed")
    1271        seed = f" {seed_prefix} ({seed})" if seed else ""
    1272        kind = expression.args.get("kind", "TABLESAMPLE")
    1273        return f"{this} {kind} {method}({bucket}{percent}{rows}{size}){seed}{alias}"

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

    1275    def pivot_sql(self, expression: exp.Pivot) -> str:
    1276        expressions = self.expressions(expression, flat=True)
    1277
    1278        if expression.this:
    1279            this = self.sql(expression, "this")
    1280            on = f"{self.seg('ON')} {expressions}"
    1281            using = self.expressions(expression, key="using", flat=True)
    1282            using = f"{self.seg('USING')} {using}" if using else ""
    1283            group = self.sql(expression, "group")
    1284            return f"PIVOT {this}{on}{using}{group}"
    1285
    1286        alias = self.sql(expression, "alias")
    1287        alias = f" AS {alias}" if alias else ""
    1288        unpivot = expression.args.get("unpivot")
    1289        direction = "UNPIVOT" if unpivot else "PIVOT"
    1290        field = self.sql(expression, "field")
    1291        return f"{direction}({expressions} FOR {field}){alias}"

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

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

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

    1296    def update_sql(self, expression: exp.Update) -> str:
    1297        this = self.sql(expression, "this")
    1298        set_sql = self.expressions(expression, flat=True)
    1299        from_sql = self.sql(expression, "from")
    1300        where_sql = self.sql(expression, "where")
    1301        returning = self.sql(expression, "returning")
    1302        limit = self.sql(expression, "limit")
    1303        if self.RETURNING_END:
    1304            expression_sql = f"{from_sql}{where_sql}{returning}{limit}"
    1305        else:
    1306            expression_sql = f"{returning}{from_sql}{where_sql}{limit}"
    1307        sql = f"UPDATE {this} SET {set_sql}{expression_sql}"
    1308        return self.prepend_ctes(expression, sql)

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

    1310    def values_sql(self, expression: exp.Values) -> str:
    1311        args = self.expressions(expression)
    1312        alias = self.sql(expression, "alias")
    1313        values = f"VALUES{self.seg('')}{args}"
    1314        values = (
    1315            f"({values})"
    1316            if self.WRAP_DERIVED_VALUES and (alias or isinstance(expression.parent, exp.From))
    1317            else values
    1318        )
    1319        return f"{values} AS {alias}" if alias else values

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

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

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

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

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

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

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

    1332    def group_sql(self, expression: exp.Group) -> str:
    1333        group_by = self.op_expressions("GROUP BY", expression)
    1334
    1335        if expression.args.get("all"):
    1336            return f"{group_by} ALL"
    1337
    1338        grouping_sets = self.expressions(expression, key="grouping_sets", indent=False)
    1339        grouping_sets = (
    1340            f"{self.seg('GROUPING SETS')} {self.wrap(grouping_sets)}" if grouping_sets else ""
    1341        )
    1342
    1343        cube = expression.args.get("cube", [])
    1344        if seq_get(cube, 0) is True:
    1345            return f"{group_by}{self.seg('WITH CUBE')}"
    1346        else:
    1347            cube_sql = self.expressions(expression, key="cube", indent=False)
    1348            cube_sql = f"{self.seg('CUBE')} {self.wrap(cube_sql)}" if cube_sql else ""
    1349
    1350        rollup = expression.args.get("rollup", [])
    1351        if seq_get(rollup, 0) is True:
    1352            return f"{group_by}{self.seg('WITH ROLLUP')}"
    1353        else:
    1354            rollup_sql = self.expressions(expression, key="rollup", indent=False)
    1355            rollup_sql = f"{self.seg('ROLLUP')} {self.wrap(rollup_sql)}" if rollup_sql else ""
    1356
    1357        groupings = csv(
    1358            grouping_sets,
    1359            cube_sql,
    1360            rollup_sql,
    1361            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    1362            sep=self.GROUPINGS_SEP,
    1363        )
    1364
    1365        if expression.args.get("expressions") and groupings:
    1366            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    1367
    1368        return f"{group_by}{groupings}"

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

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

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

    1374    def join_sql(self, expression: exp.Join) -> str:
    1375        op_sql = " ".join(
    1376            op
    1377            for op in (
    1378                expression.method,
    1379                "GLOBAL" if expression.args.get("global") else None,
    1380                expression.side,
    1381                expression.kind,
    1382                expression.hint if self.JOIN_HINTS else None,
    1383            )
    1384            if op
    1385        )
    1386        on_sql = self.sql(expression, "on")
    1387        using = expression.args.get("using")
    1388
    1389        if not on_sql and using:
    1390            on_sql = csv(*(self.sql(column) for column in using))
    1391
    1392        this_sql = self.sql(expression, "this")
    1393
    1394        if on_sql:
    1395            on_sql = self.indent(on_sql, skip_first=True)
    1396            space = self.seg(" " * self.pad) if self.pretty else " "
    1397            if using:
    1398                on_sql = f"{space}USING ({on_sql})"
    1399            else:
    1400                on_sql = f"{space}ON {on_sql}"
    1401        elif not op_sql:
    1402            return f", {this_sql}"
    1403
    1404        op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    1405        return f"{self.seg(op_sql)} {this_sql}{on_sql}"

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

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

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

    1412    def lateral_sql(self, expression: exp.Lateral) -> str:
    1413        this = self.sql(expression, "this")
    1414
    1415        if isinstance(expression.this, exp.Subquery):
    1416            return f"LATERAL {this}"
    1417
    1418        if expression.args.get("view"):
    1419            alias = expression.args["alias"]
    1420            columns = self.expressions(alias, key="columns", flat=True)
    1421            table = f" {alias.name}" if alias.name else ""
    1422            columns = f" AS {columns}" if columns else ""
    1423            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    1424            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    1425
    1426        alias = self.sql(expression, "alias")
    1427        alias = f" AS {alias}" if alias else ""
    1428        return f"LATERAL {this}{alias}"

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

    1430    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    1431        this = self.sql(expression, "this")
    1432        args = ", ".join(
    1433            sql
    1434            for sql in (
    1435                self.sql(expression, "offset"),
    1436                self.sql(expression, "expression"),
    1437            )
    1438            if sql
    1439        )
    1440        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args}"

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

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

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

    1446    def setitem_sql(self, expression: exp.SetItem) -> str:
    1447        kind = self.sql(expression, "kind")
    1448        kind = f"{kind} " if kind else ""
    1449        this = self.sql(expression, "this")
    1450        expressions = self.expressions(expression)
    1451        collate = self.sql(expression, "collate")
    1452        collate = f" COLLATE {collate}" if collate else ""
    1453        global_ = "GLOBAL " if expression.args.get("global") else ""
    1454        return f"{global_}{kind}{this}{expressions}{collate}"

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

    1456    def set_sql(self, expression: exp.Set) -> str:
    1457        expressions = (
    1458            f" {self.expressions(expression, flat=True)}" if expression.expressions else ""
    1459        )
    1460        tag = " TAG" if expression.args.get("tag") else ""
    1461        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"

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

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

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

    1466    def lock_sql(self, expression: exp.Lock) -> str:
    1467        if not self.LOCKING_READS_SUPPORTED:
    1468            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    1469            return ""
    1470
    1471        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    1472        expressions = self.expressions(expression, flat=True)
    1473        expressions = f" OF {expressions}" if expressions else ""
    1474        wait = expression.args.get("wait")
    1475
    1476        if wait is not None:
    1477            if isinstance(wait, exp.Literal):
    1478                wait = f" WAIT {self.sql(wait)}"
    1479            else:
    1480                wait = " NOWAIT" if wait else " SKIP LOCKED"
    1481
    1482        return f"{lock_type}{expressions}{wait or ''}"

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

    1484    def literal_sql(self, expression: exp.Literal) -> str:
    1485        text = expression.this or ""
    1486        if expression.is_string:
    1487            text = f"{self.QUOTE_START}{self.escape_str(text)}{self.QUOTE_END}"
    1488        return text

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

    1490    def escape_str(self, text: str) -> str:
    1491        text = text.replace(self.QUOTE_END, self._escaped_quote_end)
    1492        if self.ESCAPE_LINE_BREAK:
    1493            text = text.replace("\n", "\\n")
    1494        elif self.pretty:
    1495            text = text.replace("\n", self.SENTINEL_LINE_BREAK)
    1496        return text

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

    1498    def loaddata_sql(self, expression: exp.LoadData) -> str:
    1499        local = " LOCAL" if expression.args.get("local") else ""
    1500        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    1501        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    1502        this = f" INTO TABLE {self.sql(expression, 'this')}"
    1503        partition = self.sql(expression, "partition")
    1504        partition = f" {partition}" if partition else ""
    1505        input_format = self.sql(expression, "input_format")
    1506        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    1507        serde = self.sql(expression, "serde")
    1508        serde = f" SERDE {serde}" if serde else ""
    1509        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"

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

    1511    def null_sql(self, *_) -> str:
    1512        return "NULL"

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

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

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

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

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

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

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

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

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

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

    1531    def ordered_sql(self, expression: exp.Ordered) -> str:
    1532        desc = expression.args.get("desc")
    1533        asc = not desc
    1534
    1535        nulls_first = expression.args.get("nulls_first")
    1536        nulls_last = not nulls_first
    1537        nulls_are_large = self.NULL_ORDERING == "nulls_are_large"
    1538        nulls_are_small = self.NULL_ORDERING == "nulls_are_small"
    1539        nulls_are_last = self.NULL_ORDERING == "nulls_are_last"
    1540
    1541        sort_order = " DESC" if desc else ""
    1542        nulls_sort_change = ""
    1543        if nulls_first and (
    1544            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
    1545        ):
    1546            nulls_sort_change = " NULLS FIRST"
    1547        elif (
    1548            nulls_last
    1549            and ((asc and nulls_are_small) or (desc and nulls_are_large))
    1550            and not nulls_are_last
    1551        ):
    1552            nulls_sort_change = " NULLS LAST"
    1553
    1554        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
    1555            self.unsupported(
    1556                "Sorting in an ORDER BY on NULLS FIRST/NULLS LAST is not supported by this dialect"
    1557            )
    1558            nulls_sort_change = ""
    1559
    1560        return f"{self.sql(expression, 'this')}{sort_order}{nulls_sort_change}"

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

    1562    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    1563        partition = self.partition_by_sql(expression)
    1564        order = self.sql(expression, "order")
    1565        measures = self.expressions(expression, key="measures")
    1566        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    1567        rows = self.sql(expression, "rows")
    1568        rows = self.seg(rows) if rows else ""
    1569        after = self.sql(expression, "after")
    1570        after = self.seg(after) if after else ""
    1571        pattern = self.sql(expression, "pattern")
    1572        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    1573        definition_sqls = [
    1574            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    1575            for definition in expression.args.get("define", [])
    1576        ]
    1577        definitions = self.expressions(sqls=definition_sqls)
    1578        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    1579        body = "".join(
    1580            (
    1581                partition,
    1582                order,
    1583                measures,
    1584                rows,
    1585                after,
    1586                pattern,
    1587                define,
    1588            )
    1589        )
    1590        alias = self.sql(expression, "alias")
    1591        alias = f" {alias}" if alias else ""
    1592        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"

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

    1594    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    1595        limit: t.Optional[exp.Fetch | exp.Limit] = expression.args.get("limit")
    1596
    1597        # If the limit is generated as TOP, we need to ensure it's not generated twice
    1598        with_offset_limit_modifiers = not isinstance(limit, exp.Limit) or not self.LIMIT_IS_TOP
    1599
    1600        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    1601            limit = exp.Limit(expression=limit.args.get("count"))
    1602        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    1603            limit = exp.Fetch(direction="FIRST", count=limit.expression)
    1604
    1605        fetch = isinstance(limit, exp.Fetch)
    1606
    1607        offset_limit_modifiers = (
    1608            self.offset_limit_modifiers(expression, fetch, limit)
    1609            if with_offset_limit_modifiers
    1610            else []
    1611        )
    1612
    1613        return csv(
    1614            *sqls,
    1615            *[self.sql(join) for join in expression.args.get("joins") or []],
    1616            self.sql(expression, "match"),
    1617            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    1618            self.sql(expression, "where"),
    1619            self.sql(expression, "group"),
    1620            self.sql(expression, "having"),
    1621            *self.after_having_modifiers(expression),
    1622            self.sql(expression, "order"),
    1623            *offset_limit_modifiers,
    1624            *self.after_limit_modifiers(expression),
    1625            sep="",
    1626        )

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

    1628    def offset_limit_modifiers(
    1629        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    1630    ) -> t.List[str]:
    1631        return [
    1632            self.sql(expression, "offset") if fetch else self.sql(limit),
    1633            self.sql(limit) if fetch else self.sql(expression, "offset"),
    1634        ]

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

    1636    def after_having_modifiers(self, expression: exp.Expression) -> t.List[str]:
    1637        return [
    1638            self.sql(expression, "qualify"),
    1639            self.seg("WINDOW ") + self.expressions(expression, key="windows", flat=True)
    1640            if expression.args.get("windows")
    1641            else "",
    1642            self.sql(expression, "distribute"),
    1643            self.sql(expression, "sort"),
    1644            self.sql(expression, "cluster"),
    1645        ]

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

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

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

    1652    def select_sql(self, expression: exp.Select) -> str:
    1653        hint = self.sql(expression, "hint")
    1654        distinct = self.sql(expression, "distinct")
    1655        distinct = f" {distinct}" if distinct else ""
    1656        kind = self.sql(expression, "kind").upper()
    1657        limit = expression.args.get("limit")
    1658        top = (
    1659            self.limit_sql(limit, top=True)
    1660            if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP
    1661            else ""
    1662        )
    1663
    1664        expressions = self.expressions(expression)
    1665
    1666        if kind:
    1667            if kind in self.SELECT_KINDS:
    1668                kind = f" AS {kind}"
    1669            else:
    1670                if kind == "STRUCT":
    1671                    expressions = self.expressions(
    1672                        sqls=[
    1673                            self.sql(
    1674                                exp.Struct(
    1675                                    expressions=[
    1676                                        exp.column(e.output_name).eq(
    1677                                            e.this if isinstance(e, exp.Alias) else e
    1678                                        )
    1679                                        for e in expression.expressions
    1680                                    ]
    1681                                )
    1682                            )
    1683                        ]
    1684                    )
    1685                kind = ""
    1686
    1687        expressions = f"{self.sep()}{expressions}" if expressions else expressions
    1688        sql = self.query_modifiers(
    1689            expression,
    1690            f"SELECT{top}{hint}{distinct}{kind}{expressions}",
    1691            self.sql(expression, "into", comment=False),
    1692            self.sql(expression, "from", comment=False),
    1693        )
    1694        return self.prepend_ctes(expression, sql)

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

    1696    def schema_sql(self, expression: exp.Schema) -> str:
    1697        this = self.sql(expression, "this")
    1698        this = f"{this} " if this else ""
    1699        sql = self.schema_columns_sql(expression)
    1700        return f"{this}{sql}"

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

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

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

    1705    def star_sql(self, expression: exp.Star) -> str:
    1706        except_ = self.expressions(expression, key="except", flat=True)
    1707        except_ = f"{self.seg(self.STAR_MAPPING['except'])} ({except_})" if except_ else ""
    1708        replace = self.expressions(expression, key="replace", flat=True)
    1709        replace = f"{self.seg(self.STAR_MAPPING['replace'])} ({replace})" if replace else ""
    1710        return f"*{except_}{replace}"

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

    1712    def parameter_sql(self, expression: exp.Parameter) -> str:
    1713        this = self.sql(expression, "this")
    1714        this = f"{{{this}}}" if expression.args.get("wrapped") else f"{this}"
    1715        return f"{self.PARAMETER_TOKEN}{this}"

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

    1717    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    1718        this = self.sql(expression, "this")
    1719        kind = expression.text("kind")
    1720        if kind:
    1721            kind = f"{kind}."
    1722        return f"@@{kind}{this}"

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

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

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

    1727    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    1728        alias = self.sql(expression, "alias")
    1729        alias = f"{sep}{alias}" if alias else ""
    1730
    1731        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    1732        pivots = f" {pivots}" if pivots else ""
    1733
    1734        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    1735        return self.prepend_ctes(expression, sql)

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

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

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

    1741    def union_sql(self, expression: exp.Union) -> str:
    1742        return self.prepend_ctes(
    1743            expression,
    1744            self.set_operation(expression, self.union_op(expression)),
    1745        )

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

    1747    def union_op(self, expression: exp.Union) -> str:
    1748        kind = " DISTINCT" if self.EXPLICIT_UNION else ""
    1749        kind = kind if expression.args.get("distinct") else " ALL"
    1750        return f"UNION{kind}"

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

    1752    def unnest_sql(self, expression: exp.Unnest) -> str:
    1753        args = self.expressions(expression, flat=True)
    1754        alias = expression.args.get("alias")
    1755        if alias and self.UNNEST_COLUMN_ONLY:
    1756            columns = alias.columns
    1757            alias = self.sql(columns[0]) if columns else ""
    1758        else:
    1759            alias = self.sql(expression, "alias")
    1760        alias = f" AS {alias}" if alias else alias
    1761        ordinality = " WITH ORDINALITY" if expression.args.get("ordinality") else ""
    1762        offset = expression.args.get("offset")
    1763        offset = f" WITH OFFSET AS {self.sql(offset)}" if offset else ""
    1764        return f"UNNEST({args}){ordinality}{alias}{offset}"

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

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

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

    1770    def window_sql(self, expression: exp.Window) -> str:
    1771        this = self.sql(expression, "this")
    1772        partition = self.partition_by_sql(expression)
    1773        order = expression.args.get("order")
    1774        order = self.order_sql(order, flat=True) if order else ""
    1775        spec = self.sql(expression, "spec")
    1776        alias = self.sql(expression, "alias")
    1777        over = self.sql(expression, "over") or "OVER"
    1778
    1779        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    1780
    1781        first = expression.args.get("first")
    1782        if first is None:
    1783            first = ""
    1784        else:
    1785            first = "FIRST" if first else "LAST"
    1786
    1787        if not partition and not order and not spec and alias:
    1788            return f"{this} {alias}"
    1789
    1790        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
    1791        return f"{this} ({args})"

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

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

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

    1797    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    1798        kind = self.sql(expression, "kind")
    1799        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    1800        end = (
    1801            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    1802            or "CURRENT ROW"
    1803        )
    1804        return f"{kind} BETWEEN {start} AND {end}"

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

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

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

    1811    def between_sql(self, expression: exp.Between) -> str:
    1812        this = self.sql(expression, "this")
    1813        low = self.sql(expression, "low")
    1814        high = self.sql(expression, "high")
    1815        return f"{this} BETWEEN {low} AND {high}"

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

    1817    def bracket_sql(self, expression: exp.Bracket) -> str:
    1818        expressions = apply_index_offset(expression.this, expression.expressions, self.INDEX_OFFSET)
    1819        expressions_sql = ", ".join(self.sql(e) for e in expressions)
    1820
    1821        return f"{self.sql(expression, 'this')}[{expressions_sql}]"

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

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

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

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

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

    1829    def any_sql(self, expression: exp.Any) -> str:
    1830        this = self.sql(expression, "this")
    1831        if isinstance(expression.this, exp.Subqueryable):
    1832            this = self.wrap(this)
    1833        return f"ANY {this}"

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

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

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

    1838    def case_sql(self, expression: exp.Case) -> str:
    1839        this = self.sql(expression, "this")
    1840        statements = [f"CASE {this}" if this else "CASE"]
    1841
    1842        for e in expression.args["ifs"]:
    1843            statements.append(f"WHEN {self.sql(e, 'this')}")
    1844            statements.append(f"THEN {self.sql(e, 'true')}")
    1845
    1846        default = self.sql(expression, "default")
    1847
    1848        if default:
    1849            statements.append(f"ELSE {default}")
    1850
    1851        statements.append("END")
    1852
    1853        if self.pretty and self.text_width(statements) > self.max_text_width:
    1854            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    1855
    1856        return " ".join(statements)

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

    1858    def constraint_sql(self, expression: exp.Constraint) -> str:
    1859        this = self.sql(expression, "this")
    1860        expressions = self.expressions(expression, flat=True)
    1861        return f"CONSTRAINT {this} {expressions}"

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

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

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

    1868    def extract_sql(self, expression: exp.Extract) -> str:
    1869        this = self.sql(expression, "this")
    1870        expression_sql = self.sql(expression, "expression")
    1871        return f"EXTRACT({this} FROM {expression_sql})"

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

    1873    def trim_sql(self, expression: exp.Trim) -> str:
    1874        trim_type = self.sql(expression, "position")
    1875
    1876        if trim_type == "LEADING":
    1877            return self.func("LTRIM", expression.this)
    1878        elif trim_type == "TRAILING":
    1879            return self.func("RTRIM", expression.this)
    1880        else:
    1881            return self.func("TRIM", expression.this, expression.expression)

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

    1883    def safeconcat_sql(self, expression: exp.SafeConcat) -> str:
    1884        expressions = expression.expressions
    1885        if self.STRICT_STRING_CONCAT:
    1886            expressions = (exp.cast(e, "text") for e in expressions)
    1887        return self.func("CONCAT", *expressions)

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

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

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

    1893    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    1894        expressions = self.expressions(expression, flat=True)
    1895        reference = self.sql(expression, "reference")
    1896        reference = f" {reference}" if reference else ""
    1897        delete = self.sql(expression, "delete")
    1898        delete = f" ON DELETE {delete}" if delete else ""
    1899        update = self.sql(expression, "update")
    1900        update = f" ON UPDATE {update}" if update else ""
    1901        return f"FOREIGN KEY ({expressions}){reference}{delete}{update}"

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

    1903    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    1904        expressions = self.expressions(expression, flat=True)
    1905        options = self.expressions(expression, key="options", flat=True, sep=" ")
    1906        options = f" {options}" if options else ""
    1907        return f"PRIMARY KEY ({expressions}){options}"

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

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

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

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

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

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

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

    1920    def jsonobject_sql(self, expression: exp.JSONObject) -> str:
    1921        null_handling = expression.args.get("null_handling")
    1922        null_handling = f" {null_handling}" if null_handling else ""
    1923        unique_keys = expression.args.get("unique_keys")
    1924        if unique_keys is not None:
    1925            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    1926        else:
    1927            unique_keys = ""
    1928        return_type = self.sql(expression, "return_type")
    1929        return_type = f" RETURNING {return_type}" if return_type else ""
    1930        format_json = " FORMAT JSON" if expression.args.get("format_json") else ""
    1931        encoding = self.sql(expression, "encoding")
    1932        encoding = f" ENCODING {encoding}" if encoding else ""
    1933        return self.func(
    1934            "JSON_OBJECT",
    1935            *expression.expressions,
    1936            suffix=f"{null_handling}{unique_keys}{return_type}{format_json}{encoding})",
    1937        )

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

    1939    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    1940        this = self.sql(expression, "this")
    1941        kind = self.sql(expression, "kind")
    1942        path = self.sql(expression, "path")
    1943        path = f" {path}" if path else ""
    1944        as_json = " AS JSON" if expression.args.get("as_json") else ""
    1945        return f"{this} {kind}{path}{as_json}"

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

    1947    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    1948        this = self.sql(expression, "this")
    1949        path = self.sql(expression, "path")
    1950        path = f", {path}" if path else ""
    1951        expressions = self.expressions(expression)
    1952        with_ = (
    1953            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    1954            if expressions
    1955            else ""
    1956        )
    1957        return f"OPENJSON({this}{path}){with_}"

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

    1959    def in_sql(self, expression: exp.In) -> str:
    1960        query = expression.args.get("query")
    1961        unnest = expression.args.get("unnest")
    1962        field = expression.args.get("field")
    1963        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    1964
    1965        if query:
    1966            in_sql = self.wrap(query)
    1967        elif unnest:
    1968            in_sql = self.in_unnest_op(unnest)
    1969        elif field:
    1970            in_sql = self.sql(field)
    1971        else:
    1972            in_sql = f"({self.expressions(expression, flat=True)})"
    1973
    1974        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"

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

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

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

    1979    def interval_sql(self, expression: exp.Interval) -> str:
    1980        unit = self.sql(expression, "unit")
    1981        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    1982            unit = self.TIME_PART_SINGULARS.get(unit.lower(), unit)
    1983        unit = f" {unit}" if unit else ""
    1984
    1985        if self.SINGLE_STRING_INTERVAL:
    1986            this = expression.this.name if expression.this else ""
    1987            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    1988
    1989        this = self.sql(expression, "this")
    1990        if this:
    1991            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    1992            this = f" {this}" if unwrapped else f" ({this})"
    1993
    1994        return f"INTERVAL{this}{unit}"

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

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

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

    1999    def reference_sql(self, expression: exp.Reference) -> str:
    2000        this = self.sql(expression, "this")
    2001        expressions = self.expressions(expression, flat=True)
    2002        expressions = f"({expressions})" if expressions else ""
    2003        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2004        options = f" {options}" if options else ""
    2005        return f"REFERENCES {this}{expressions}{options}"

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

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

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

    2010    def paren_sql(self, expression: exp.Paren) -> str:
    2011        if isinstance(expression.unnest(), exp.Select):
    2012            sql = self.wrap(expression)
    2013        else:
    2014            sql = self.seg(self.indent(self.sql(expression, "this")), sep="")
    2015            sql = f"({sql}{self.seg(')', sep='')}"
    2016
    2017        return self.prepend_ctes(expression, sql)

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

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

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

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

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

    2028    def alias_sql(self, expression: exp.Alias) -> str:
    2029        alias = self.sql(expression, "alias")
    2030        alias = f" AS {alias}" if alias else ""
    2031        return f"{self.sql(expression, 'this')}{alias}"

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

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

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

    2036    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    2037        this = self.sql(expression, "this")
    2038        zone = self.sql(expression, "zone")
    2039        return f"{this} AT TIME ZONE {zone}"

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

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

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

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

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

    2047    def xor_sql(self, expression: exp.And) -> str:
    2048        return self.connector_sql(expression, "XOR")

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

    2050    def connector_sql(self, expression: exp.Connector, op: str) -> str:
    2051        if not self.pretty:
    2052            return self.binary(expression, op)
    2053
    2054        sqls = tuple(
    2055            self.maybe_comment(self.sql(e), e, e.parent.comments or []) if i != 1 else self.sql(e)
    2056            for i, e in enumerate(expression.flatten(unnest=False))
    2057        )
    2058
    2059        sep = "\n" if self.text_width(sqls) > self.max_text_width else " "
    2060        return f"{sep}{op} ".join(sqls)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    2095    def comment_sql(self, expression: exp.Comment) -> str:
    2096        this = self.sql(expression, "this")
    2097        kind = expression.args["kind"]
    2098        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    2099        expression_sql = self.sql(expression, "expression")
    2100        return f"COMMENT{exists_sql}ON {kind} {this} IS {expression_sql}"

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

    2102    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    2103        this = self.sql(expression, "this")
    2104        delete = " DELETE" if expression.args.get("delete") else ""
    2105        recompress = self.sql(expression, "recompress")
    2106        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    2107        to_disk = self.sql(expression, "to_disk")
    2108        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    2109        to_volume = self.sql(expression, "to_volume")
    2110        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    2111        return f"{this}{delete}{recompress}{to_disk}{to_volume}"

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

    2113    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    2114        where = self.sql(expression, "where")
    2115        group = self.sql(expression, "group")
    2116        aggregates = self.expressions(expression, key="aggregates")
    2117        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    2118
    2119        if not (where or group or aggregates) and len(expression.expressions) == 1:
    2120            return f"TTL {self.expressions(expression, flat=True)}"
    2121
    2122        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"

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

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

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

    2127    def commit_sql(self, expression: exp.Commit) -> str:
    2128        chain = expression.args.get("chain")
    2129        if chain is not None:
    2130            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    2131
    2132        return f"COMMIT{chain or ''}"

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

    2134    def rollback_sql(self, expression: exp.Rollback) -> str:
    2135        savepoint = expression.args.get("savepoint")
    2136        savepoint = f" TO {savepoint}" if savepoint else ""
    2137        return f"ROLLBACK{savepoint}"

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

    2139    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    2140        this = self.sql(expression, "this")
    2141
    2142        dtype = self.sql(expression, "dtype")
    2143        if dtype:
    2144            collate = self.sql(expression, "collate")
    2145            collate = f" COLLATE {collate}" if collate else ""
    2146            using = self.sql(expression, "using")
    2147            using = f" USING {using}" if using else ""
    2148            return f"ALTER COLUMN {this} TYPE {dtype}{collate}{using}"
    2149
    2150        default = self.sql(expression, "default")
    2151        if default:
    2152            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    2153
    2154        if not expression.args.get("drop"):
    2155            self.unsupported("Unsupported ALTER COLUMN syntax")
    2156
    2157        return f"ALTER COLUMN {this} DROP DEFAULT"

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

    2159    def renametable_sql(self, expression: exp.RenameTable) -> str:
    2160        if not self.RENAME_TABLE_WITH_DB:
    2161            # Remove db from tables
    2162            expression = expression.transform(
    2163                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    2164            )
    2165        this = self.sql(expression, "this")
    2166        return f"RENAME TO {this}"

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

    2168    def altertable_sql(self, expression: exp.AlterTable) -> str:
    2169        actions = expression.args["actions"]
    2170
    2171        if isinstance(actions[0], exp.ColumnDef):
    2172            actions = self.expressions(expression, key="actions", prefix="ADD COLUMN ")
    2173        elif isinstance(actions[0], exp.Schema):
    2174            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    2175        elif isinstance(actions[0], exp.Delete):
    2176            actions = self.expressions(expression, key="actions", flat=True)
    2177        else:
    2178            actions = self.expressions(expression, key="actions")
    2179
    2180        exists = " IF EXISTS" if expression.args.get("exists") else ""
    2181        return f"ALTER TABLE{exists} {self.sql(expression, 'this')} {actions}"

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

    2183    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    2184        expressions = self.expressions(expression)
    2185        exists = " IF EXISTS " if expression.args.get("exists") else " "
    2186        return f"DROP{exists}{expressions}"

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

    2188    def addconstraint_sql(self, expression: exp.AddConstraint) -> str:
    2189        this = self.sql(expression, "this")
    2190        expression_ = self.sql(expression, "expression")
    2191        add_constraint = f"ADD CONSTRAINT {this}" if this else "ADD"
    2192
    2193        enforced = expression.args.get("enforced")
    2194        if enforced is not None:
    2195            return f"{add_constraint} CHECK ({expression_}){' ENFORCED' if enforced else ''}"
    2196
    2197        return f"{add_constraint} {expression_}"

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

    2199    def distinct_sql(self, expression: exp.Distinct) -> str:
    2200        this = self.expressions(expression, flat=True)
    2201        this = f" {this}" if this else ""
    2202
    2203        on = self.sql(expression, "on")
    2204        on = f" ON {on}" if on else ""
    2205        return f"DISTINCT{this}{on}"

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

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

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

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

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

    2213    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    2214        return self.sql(
    2215            exp.Cast(
    2216                this=exp.Div(this=expression.this, expression=expression.expression),
    2217                to=exp.DataType(this=exp.DataType.Type.INT),
    2218            )
    2219        )

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

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

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

    2224    def safedpipe_sql(self, expression: exp.SafeDPipe) -> str:
    2225        if self.STRICT_STRING_CONCAT:
    2226            return self.func("CONCAT", *(exp.cast(e, "text") for e in expression.flatten()))
    2227        return self.dpipe_sql(expression)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    2262    def is_sql(self, expression: exp.Is) -> str:
    2263        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    2264            return self.sql(
    2265                expression.this if expression.expression.this else exp.not_(expression.this)
    2266            )
    2267        return self.binary(expression, "IS")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    2311    def use_sql(self, expression: exp.Use) -> str:
    2312        kind = self.sql(expression, "kind")
    2313        kind = f" {kind}" if kind else ""
    2314        this = self.sql(expression, "this")
    2315        this = f" {this}" if this else ""
    2316        return f"USE{kind}{this}"

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

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

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

    2322    def function_fallback_sql(self, expression: exp.Func) -> str:
    2323        args = []
    2324
    2325        for key in expression.arg_types:
    2326            arg_value = expression.args.get(key)
    2327
    2328            if isinstance(arg_value, list):
    2329                for value in arg_value:
    2330                    args.append(value)
    2331            elif arg_value is not None:
    2332                args.append(arg_value)
    2333
    2334        return self.func(expression.sql_name(), *args)

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

    2336    def func(
    2337        self,
    2338        name: str,
    2339        *args: t.Optional[exp.Expression | str],
    2340        prefix: str = "(",
    2341        suffix: str = ")",
    2342    ) -> str:
    2343        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

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

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

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

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

    2354    def format_time(self, expression: exp.Expression) -> t.Optional[str]:
    2355        return format_time(
    2356            self.sql(expression, "format"), self.INVERSE_TIME_MAPPING, self.INVERSE_TIME_TRIE
    2357        )

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

    2359    def expressions(
    2360        self,
    2361        expression: t.Optional[exp.Expression] = None,
    2362        key: t.Optional[str] = None,
    2363        sqls: t.Optional[t.List[str]] = None,
    2364        flat: bool = False,
    2365        indent: bool = True,
    2366        skip_first: bool = False,
    2367        sep: str = ", ",
    2368        prefix: str = "",
    2369    ) -> str:
    2370        expressions = expression.args.get(key or "expressions") if expression else sqls
    2371
    2372        if not expressions:
    2373            return ""
    2374
    2375        if flat:
    2376            return sep.join(self.sql(e) for e in expressions)
    2377
    2378        num_sqls = len(expressions)
    2379
    2380        # These are calculated once in case we have the leading_comma / pretty option set, correspondingly
    2381        pad = " " * self.pad
    2382        stripped_sep = sep.strip()
    2383
    2384        result_sqls = []
    2385        for i, e in enumerate(expressions):
    2386            sql = self.sql(e, comment=False)
    2387            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    2388
    2389            if self.pretty:
    2390                if self.leading_comma:
    2391                    result_sqls.append(f"{sep if i > 0 else pad}{prefix}{sql}{comments}")
    2392                else:
    2393                    result_sqls.append(
    2394                        f"{prefix}{sql}{stripped_sep if i + 1 < num_sqls else ''}{comments}"
    2395                    )
    2396            else:
    2397                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    2398
    2399        result_sql = "\n".join(result_sqls) if self.pretty else "".join(result_sqls)
    2400        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

    2402    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    2403        flat = flat or isinstance(expression.parent, exp.Properties)
    2404        expressions_sql = self.expressions(expression, flat=flat)
    2405        if flat:
    2406            return f"{op} {expressions_sql}"
    2407        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"

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

    2409    def naked_property(self, expression: exp.Property) -> str:
    2410        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    2411        if not property_name:
    2412            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    2413        return f"{property_name} {self.sql(expression, 'this')}"

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

    2415    def set_operation(self, expression: exp.Expression, op: str) -> str:
    2416        this = self.sql(expression, "this")
    2417        op = self.seg(op)
    2418        return self.query_modifiers(
    2419            expression, f"{this}{op}{self.sep()}{self.sql(expression, 'expression')}"
    2420        )

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

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

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

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

    2428    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    2429        this = self.sql(expression, "this")
    2430        expressions = self.no_identify(self.expressions, expression)
    2431        expressions = (
    2432            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    2433        )
    2434        return f"{this}{expressions}"

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

    2436    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    2437        this = self.sql(expression, "this")
    2438        expressions = self.expressions(expression, flat=True)
    2439        return f"{this}({expressions})"

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

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

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

    2444    def when_sql(self, expression: exp.When) -> str:
    2445        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    2446        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    2447        condition = self.sql(expression, "condition")
    2448        condition = f" AND {condition}" if condition else ""
    2449
    2450        then_expression = expression.args.get("then")
    2451        if isinstance(then_expression, exp.Insert):
    2452            then = f"INSERT {self.sql(then_expression, 'this')}"
    2453            if "expression" in then_expression.args:
    2454                then += f" VALUES {self.sql(then_expression, 'expression')}"
    2455        elif isinstance(then_expression, exp.Update):
    2456            if isinstance(then_expression.args.get("expressions"), exp.Star):
    2457                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    2458            else:
    2459                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    2460        else:
    2461            then = self.sql(then_expression)
    2462        return f"WHEN {matched}{source}{condition} THEN {then}"

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

    2464    def merge_sql(self, expression: exp.Merge) -> str:
    2465        this = self.sql(expression, "this")
    2466        using = f"USING {self.sql(expression, 'using')}"
    2467        on = f"ON {self.sql(expression, 'on')}"
    2468        return f"MERGE INTO {this} {using} {on} {self.expressions(expression, sep=' ')}"

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

    2470    def tochar_sql(self, expression: exp.ToChar) -> str:
    2471        if expression.args.get("format"):
    2472            self.unsupported("Format argument unsupported for TO_CHAR/TO_VARCHAR function")
    2473
    2474        return self.sql(exp.cast(expression.this, "text"))

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

    2476    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    2477        this = self.sql(expression, "this")
    2478        kind = self.sql(expression, "kind")
    2479        settings_sql = self.expressions(expression, key="settings", sep=" ")
    2480        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    2481        return f"{this}({kind}{args})"

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

    2483    def dictrange_sql(self, expression: exp.DictRange) -> str:
    2484        this = self.sql(expression, "this")
    2485        max = self.sql(expression, "max")
    2486        min = self.sql(expression, "min")
    2487        return f"{this}(MIN {min} MAX {max})"

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

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

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

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

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

    2495    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    2496        expressions = self.expressions(expression, key="expressions", flat=True)
    2497        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    2498        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    2499        buckets = self.sql(expression, "buckets")
    2500        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"

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

    2502    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    2503        this = self.sql(expression, "this")
    2504        having = self.sql(expression, "having")
    2505
    2506        if having:
    2507            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    2508
    2509        return self.func("ANY_VALUE", this)

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

    2512def cached_generator(
    2513    cache: t.Optional[t.Dict[int, str]] = None
    2514) -> t.Callable[[exp.Expression], str]:
    2515    """Returns a cached generator."""
    2516    cache = {} if cache is None else cache
    2517    generator = Generator(normalize=True, identify="safe")
    2518    return lambda e: generator.generate(e, cache)

Returns a cached generator.