sqlglot.generator API documentation

Edit on GitHub

# sqlglot.generator

View Source

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

class Generator: View Source

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

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

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

@classmethod
def can_identify(text: str, identify: str | bool = 'safe') -> bool: View Source

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

Checks if text can be identified given an identify option.

###### Arguments:

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

###### Returns:

> Whether or not the given text can be identified.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    914    def partition_sql(self, expression: exp.Partition) -> str:
    915        return f"PARTITION({self.expressions(expression)})"

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    1124    def intersect_sql(self, expression: exp.Intersect) -> str:
    1125        return self.prepend_ctes(
    1126            expression,
    1127            self.set_operation(expression, self.intersect_op(expression)),
    1128        )

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

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

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

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

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

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

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

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

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

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

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

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

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

    1170    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1171        table = ".".join(
    1172            part
    1173            for part in [
    1174                self.sql(expression, "catalog"),
    1175                self.sql(expression, "db"),
    1176                self.sql(expression, "this"),
    1177            ]
    1178            if part
    1179        )
    1180
    1181        alias = self.sql(expression, "alias")
    1182        alias = f"{sep}{alias}" if alias else ""
    1183        hints = self.expressions(expression, key="hints", flat=True)
    1184        hints = f" WITH ({hints})" if hints and self.TABLE_HINTS else ""
    1185        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    1186        pivots = f" {pivots}" if pivots else ""
    1187        joins = self.expressions(expression, key="joins", sep="")
    1188        laterals = self.expressions(expression, key="laterals", sep="")
    1189        system_time = expression.args.get("system_time")
    1190        system_time = f" {self.sql(expression, 'system_time')}" if system_time else ""
    1191
    1192        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

    1194    def tablesample_sql(
    1195        self, expression: exp.TableSample, seed_prefix: str = "SEED", sep=" AS "
    1196    ) -> str:
    1197        if self.ALIAS_POST_TABLESAMPLE and expression.this.alias:
    1198            table = expression.this.copy()
    1199            table.set("alias", None)
    1200            this = self.sql(table)
    1201            alias = f"{sep}{self.sql(expression.this, 'alias')}"
    1202        else:
    1203            this = self.sql(expression, "this")
    1204            alias = ""
    1205        method = self.sql(expression, "method")
    1206        method = f"{method.upper()} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    1207        numerator = self.sql(expression, "bucket_numerator")
    1208        denominator = self.sql(expression, "bucket_denominator")
    1209        field = self.sql(expression, "bucket_field")
    1210        field = f" ON {field}" if field else ""
    1211        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    1212        percent = self.sql(expression, "percent")
    1213        percent = f"{percent} PERCENT" if percent else ""
    1214        rows = self.sql(expression, "rows")
    1215        rows = f"{rows} ROWS" if rows else ""
    1216        size = self.sql(expression, "size")
    1217        if size and self.TABLESAMPLE_SIZE_IS_PERCENT:
    1218            size = f"{size} PERCENT"
    1219        seed = self.sql(expression, "seed")
    1220        seed = f" {seed_prefix} ({seed})" if seed else ""
    1221        kind = expression.args.get("kind", "TABLESAMPLE")
    1222        return f"{this} {kind} {method}({bucket}{percent}{rows}{size}){seed}{alias}"

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

    1224    def pivot_sql(self, expression: exp.Pivot) -> str:
    1225        expressions = self.expressions(expression, flat=True)
    1226
    1227        if expression.this:
    1228            this = self.sql(expression, "this")
    1229            on = f"{self.seg('ON')} {expressions}"
    1230            using = self.expressions(expression, key="using", flat=True)
    1231            using = f"{self.seg('USING')} {using}" if using else ""
    1232            group = self.sql(expression, "group")
    1233            return f"PIVOT {this}{on}{using}{group}"
    1234
    1235        alias = self.sql(expression, "alias")
    1236        alias = f" AS {alias}" if alias else ""
    1237        unpivot = expression.args.get("unpivot")
    1238        direction = "UNPIVOT" if unpivot else "PIVOT"
    1239        field = self.sql(expression, "field")
    1240        return f"{direction}({expressions} FOR {field}){alias}"

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

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

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

    1245    def update_sql(self, expression: exp.Update) -> str:
    1246        this = self.sql(expression, "this")
    1247        set_sql = self.expressions(expression, flat=True)
    1248        from_sql = self.sql(expression, "from")
    1249        where_sql = self.sql(expression, "where")
    1250        returning = self.sql(expression, "returning")
    1251        sql = f"UPDATE {this} SET {set_sql}{from_sql}{where_sql}{returning}"
    1252        return self.prepend_ctes(expression, sql)

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

    1254    def values_sql(self, expression: exp.Values) -> str:
    1255        args = self.expressions(expression)
    1256        alias = self.sql(expression, "alias")
    1257        values = f"VALUES{self.seg('')}{args}"
    1258        values = (
    1259            f"({values})"
    1260            if self.WRAP_DERIVED_VALUES and (alias or isinstance(expression.parent, exp.From))
    1261            else values
    1262        )
    1263        return f"{values} AS {alias}" if alias else values

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

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

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

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

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

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

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

    1276    def group_sql(self, expression: exp.Group) -> str:
    1277        group_by = self.op_expressions("GROUP BY", expression)
    1278        grouping_sets = self.expressions(expression, key="grouping_sets", indent=False)
    1279        grouping_sets = (
    1280            f"{self.seg('GROUPING SETS')} {self.wrap(grouping_sets)}" if grouping_sets else ""
    1281        )
    1282
    1283        cube = expression.args.get("cube", [])
    1284        if seq_get(cube, 0) is True:
    1285            return f"{group_by}{self.seg('WITH CUBE')}"
    1286        else:
    1287            cube_sql = self.expressions(expression, key="cube", indent=False)
    1288            cube_sql = f"{self.seg('CUBE')} {self.wrap(cube_sql)}" if cube_sql else ""
    1289
    1290        rollup = expression.args.get("rollup", [])
    1291        if seq_get(rollup, 0) is True:
    1292            return f"{group_by}{self.seg('WITH ROLLUP')}"
    1293        else:
    1294            rollup_sql = self.expressions(expression, key="rollup", indent=False)
    1295            rollup_sql = f"{self.seg('ROLLUP')} {self.wrap(rollup_sql)}" if rollup_sql else ""
    1296
    1297        groupings = csv(
    1298            grouping_sets,
    1299            cube_sql,
    1300            rollup_sql,
    1301            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    1302            sep=self.GROUPINGS_SEP,
    1303        )
    1304
    1305        if expression.args.get("expressions") and groupings:
    1306            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    1307
    1308        return f"{group_by}{groupings}"

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

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

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

    1314    def join_sql(self, expression: exp.Join) -> str:
    1315        op_sql = " ".join(
    1316            op
    1317            for op in (
    1318                expression.method,
    1319                "GLOBAL" if expression.args.get("global") else None,
    1320                expression.side,
    1321                expression.kind,
    1322                expression.hint if self.JOIN_HINTS else None,
    1323            )
    1324            if op
    1325        )
    1326        on_sql = self.sql(expression, "on")
    1327        using = expression.args.get("using")
    1328
    1329        if not on_sql and using:
    1330            on_sql = csv(*(self.sql(column) for column in using))
    1331
    1332        this_sql = self.sql(expression, "this")
    1333
    1334        if on_sql:
    1335            on_sql = self.indent(on_sql, skip_first=True)
    1336            space = self.seg(" " * self.pad) if self.pretty else " "
    1337            if using:
    1338                on_sql = f"{space}USING ({on_sql})"
    1339            else:
    1340                on_sql = f"{space}ON {on_sql}"
    1341        elif not op_sql:
    1342            return f", {this_sql}"
    1343
    1344        op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    1345        return f"{self.seg(op_sql)} {this_sql}{on_sql}"

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

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

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

    1352    def lateral_sql(self, expression: exp.Lateral) -> str:
    1353        this = self.sql(expression, "this")
    1354
    1355        if isinstance(expression.this, exp.Subquery):
    1356            return f"LATERAL {this}"
    1357
    1358        if expression.args.get("view"):
    1359            alias = expression.args["alias"]
    1360            columns = self.expressions(alias, key="columns", flat=True)
    1361            table = f" {alias.name}" if alias.name else ""
    1362            columns = f" AS {columns}" if columns else ""
    1363            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    1364            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    1365
    1366        alias = self.sql(expression, "alias")
    1367        alias = f" AS {alias}" if alias else ""
    1368        return f"LATERAL {this}{alias}"

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

    1370    def limit_sql(self, expression: exp.Limit) -> str:
    1371        this = self.sql(expression, "this")
    1372        args = ", ".join(
    1373            sql
    1374            for sql in (
    1375                self.sql(expression, "offset"),
    1376                self.sql(expression, "expression"),
    1377            )
    1378            if sql
    1379        )
    1380        return f"{this}{self.seg('LIMIT')} {args}"

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

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

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

    1386    def setitem_sql(self, expression: exp.SetItem) -> str:
    1387        kind = self.sql(expression, "kind")
    1388        kind = f"{kind} " if kind else ""
    1389        this = self.sql(expression, "this")
    1390        expressions = self.expressions(expression)
    1391        collate = self.sql(expression, "collate")
    1392        collate = f" COLLATE {collate}" if collate else ""
    1393        global_ = "GLOBAL " if expression.args.get("global") else ""
    1394        return f"{global_}{kind}{this}{expressions}{collate}"

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

    1396    def set_sql(self, expression: exp.Set) -> str:
    1397        expressions = (
    1398            f" {self.expressions(expression, flat=True)}" if expression.expressions else ""
    1399        )
    1400        return f"SET{expressions}"

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

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

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

    1405    def lock_sql(self, expression: exp.Lock) -> str:
    1406        if not self.LOCKING_READS_SUPPORTED:
    1407            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    1408            return ""
    1409
    1410        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    1411        expressions = self.expressions(expression, flat=True)
    1412        expressions = f" OF {expressions}" if expressions else ""
    1413        wait = expression.args.get("wait")
    1414
    1415        if wait is not None:
    1416            if isinstance(wait, exp.Literal):
    1417                wait = f" WAIT {self.sql(wait)}"
    1418            else:
    1419                wait = " NOWAIT" if wait else " SKIP LOCKED"
    1420
    1421        return f"{lock_type}{expressions}{wait or ''}"

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

    1423    def literal_sql(self, expression: exp.Literal) -> str:
    1424        text = expression.this or ""
    1425        if expression.is_string:
    1426            text = f"{self.QUOTE_START}{self.escape_str(text)}{self.QUOTE_END}"
    1427        return text

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

    1429    def escape_str(self, text: str) -> str:
    1430        text = text.replace(self.QUOTE_END, self._escaped_quote_end)
    1431        if self.pretty:
    1432            text = text.replace("\n", self.SENTINEL_LINE_BREAK)
    1433        return text

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

    1435    def loaddata_sql(self, expression: exp.LoadData) -> str:
    1436        local = " LOCAL" if expression.args.get("local") else ""
    1437        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    1438        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    1439        this = f" INTO TABLE {self.sql(expression, 'this')}"
    1440        partition = self.sql(expression, "partition")
    1441        partition = f" {partition}" if partition else ""
    1442        input_format = self.sql(expression, "input_format")
    1443        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    1444        serde = self.sql(expression, "serde")
    1445        serde = f" SERDE {serde}" if serde else ""
    1446        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"

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

    1448    def null_sql(self, *_) -> str:
    1449        return "NULL"

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

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

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

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

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

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

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

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

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

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

    1468    def ordered_sql(self, expression: exp.Ordered) -> str:
    1469        desc = expression.args.get("desc")
    1470        asc = not desc
    1471
    1472        nulls_first = expression.args.get("nulls_first")
    1473        nulls_last = not nulls_first
    1474        nulls_are_large = self.NULL_ORDERING == "nulls_are_large"
    1475        nulls_are_small = self.NULL_ORDERING == "nulls_are_small"
    1476        nulls_are_last = self.NULL_ORDERING == "nulls_are_last"
    1477
    1478        sort_order = " DESC" if desc else ""
    1479        nulls_sort_change = ""
    1480        if nulls_first and (
    1481            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
    1482        ):
    1483            nulls_sort_change = " NULLS FIRST"
    1484        elif (
    1485            nulls_last
    1486            and ((asc and nulls_are_small) or (desc and nulls_are_large))
    1487            and not nulls_are_last
    1488        ):
    1489            nulls_sort_change = " NULLS LAST"
    1490
    1491        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
    1492            self.unsupported(
    1493                "Sorting in an ORDER BY on NULLS FIRST/NULLS LAST is not supported by this dialect"
    1494            )
    1495            nulls_sort_change = ""
    1496
    1497        return f"{self.sql(expression, 'this')}{sort_order}{nulls_sort_change}"

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

    1499    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    1500        partition = self.partition_by_sql(expression)
    1501        order = self.sql(expression, "order")
    1502        measures = self.expressions(expression, key="measures")
    1503        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    1504        rows = self.sql(expression, "rows")
    1505        rows = self.seg(rows) if rows else ""
    1506        after = self.sql(expression, "after")
    1507        after = self.seg(after) if after else ""
    1508        pattern = self.sql(expression, "pattern")
    1509        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    1510        definition_sqls = [
    1511            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    1512            for definition in expression.args.get("define", [])
    1513        ]
    1514        definitions = self.expressions(sqls=definition_sqls)
    1515        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    1516        body = "".join(
    1517            (
    1518                partition,
    1519                order,
    1520                measures,
    1521                rows,
    1522                after,
    1523                pattern,
    1524                define,
    1525            )
    1526        )
    1527        alias = self.sql(expression, "alias")
    1528        alias = f" {alias}" if alias else ""
    1529        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"

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

    1531    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    1532        limit: t.Optional[exp.Fetch | exp.Limit] = expression.args.get("limit")
    1533
    1534        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    1535            limit = exp.Limit(expression=limit.args.get("count"))
    1536        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    1537            limit = exp.Fetch(direction="FIRST", count=limit.expression)
    1538
    1539        fetch = isinstance(limit, exp.Fetch)
    1540
    1541        return csv(
    1542            *sqls,
    1543            *[self.sql(join) for join in expression.args.get("joins") or []],
    1544            self.sql(expression, "match"),
    1545            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    1546            self.sql(expression, "where"),
    1547            self.sql(expression, "group"),
    1548            self.sql(expression, "having"),
    1549            *self.after_having_modifiers(expression),
    1550            self.sql(expression, "order"),
    1551            *self.offset_limit_modifiers(expression, fetch, limit),
    1552            *self.after_limit_modifiers(expression),
    1553            sep="",
    1554        )

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

    1556    def offset_limit_modifiers(
    1557        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    1558    ) -> t.List[str]:
    1559        return [
    1560            self.sql(expression, "offset") if fetch else self.sql(limit),
    1561            self.sql(limit) if fetch else self.sql(expression, "offset"),
    1562        ]

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

    1564    def after_having_modifiers(self, expression: exp.Expression) -> t.List[str]:
    1565        return [
    1566            self.sql(expression, "qualify"),
    1567            self.seg("WINDOW ") + self.expressions(expression, key="windows", flat=True)
    1568            if expression.args.get("windows")
    1569            else "",
    1570        ]

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

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

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

    1577    def select_sql(self, expression: exp.Select) -> str:
    1578        hint = self.sql(expression, "hint")
    1579        distinct = self.sql(expression, "distinct")
    1580        distinct = f" {distinct}" if distinct else ""
    1581        kind = self.sql(expression, "kind").upper()
    1582        expressions = self.expressions(expression)
    1583
    1584        if kind:
    1585            if kind in self.SELECT_KINDS:
    1586                kind = f" AS {kind}"
    1587            else:
    1588                if kind == "STRUCT":
    1589                    expressions = self.expressions(
    1590                        sqls=[
    1591                            self.sql(
    1592                                exp.Struct(
    1593                                    expressions=[
    1594                                        exp.column(e.output_name).eq(
    1595                                            e.this if isinstance(e, exp.Alias) else e
    1596                                        )
    1597                                        for e in expression.expressions
    1598                                    ]
    1599                                )
    1600                            )
    1601                        ]
    1602                    )
    1603                kind = ""
    1604
    1605        expressions = f"{self.sep()}{expressions}" if expressions else expressions
    1606        sql = self.query_modifiers(
    1607            expression,
    1608            f"SELECT{hint}{distinct}{kind}{expressions}",
    1609            self.sql(expression, "into", comment=False),
    1610            self.sql(expression, "from", comment=False),
    1611        )
    1612        return self.prepend_ctes(expression, sql)

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

    1614    def schema_sql(self, expression: exp.Schema) -> str:
    1615        this = self.sql(expression, "this")
    1616        this = f"{this} " if this else ""
    1617        sql = self.schema_columns_sql(expression)
    1618        return f"{this}{sql}"

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

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

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

    1623    def star_sql(self, expression: exp.Star) -> str:
    1624        except_ = self.expressions(expression, key="except", flat=True)
    1625        except_ = f"{self.seg(self.STAR_MAPPING['except'])} ({except_})" if except_ else ""
    1626        replace = self.expressions(expression, key="replace", flat=True)
    1627        replace = f"{self.seg(self.STAR_MAPPING['replace'])} ({replace})" if replace else ""
    1628        return f"*{except_}{replace}"

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

    1630    def parameter_sql(self, expression: exp.Parameter) -> str:
    1631        this = self.sql(expression, "this")
    1632        this = f"{{{this}}}" if expression.args.get("wrapped") else f"{this}"
    1633        return f"{self.PARAMETER_TOKEN}{this}"

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

    1635    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    1636        this = self.sql(expression, "this")
    1637        kind = expression.text("kind")
    1638        if kind:
    1639            kind = f"{kind}."
    1640        return f"@@{kind}{this}"

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

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

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

    1645    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    1646        alias = self.sql(expression, "alias")
    1647        alias = f"{sep}{alias}" if alias else ""
    1648
    1649        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    1650        pivots = f" {pivots}" if pivots else ""
    1651
    1652        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    1653        return self.prepend_ctes(expression, sql)

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

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

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

    1659    def union_sql(self, expression: exp.Union) -> str:
    1660        return self.prepend_ctes(
    1661            expression,
    1662            self.set_operation(expression, self.union_op(expression)),
    1663        )

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

    1665    def union_op(self, expression: exp.Union) -> str:
    1666        kind = " DISTINCT" if self.EXPLICIT_UNION else ""
    1667        kind = kind if expression.args.get("distinct") else " ALL"
    1668        return f"UNION{kind}"

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

    1670    def unnest_sql(self, expression: exp.Unnest) -> str:
    1671        args = self.expressions(expression, flat=True)
    1672        alias = expression.args.get("alias")
    1673        if alias and self.UNNEST_COLUMN_ONLY:
    1674            columns = alias.columns
    1675            alias = self.sql(columns[0]) if columns else ""
    1676        else:
    1677            alias = self.sql(expression, "alias")
    1678        alias = f" AS {alias}" if alias else alias
    1679        ordinality = " WITH ORDINALITY" if expression.args.get("ordinality") else ""
    1680        offset = expression.args.get("offset")
    1681        offset = f" WITH OFFSET AS {self.sql(offset)}" if offset else ""
    1682        return f"UNNEST({args}){ordinality}{alias}{offset}"

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

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

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

    1688    def window_sql(self, expression: exp.Window) -> str:
    1689        this = self.sql(expression, "this")
    1690        partition = self.partition_by_sql(expression)
    1691        order = expression.args.get("order")
    1692        order = self.order_sql(order, flat=True) if order else ""
    1693        spec = self.sql(expression, "spec")
    1694        alias = self.sql(expression, "alias")
    1695        over = self.sql(expression, "over") or "OVER"
    1696
    1697        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    1698
    1699        first = expression.args.get("first")
    1700        if first is None:
    1701            first = ""
    1702        else:
    1703            first = "FIRST" if first else "LAST"
    1704
    1705        if not partition and not order and not spec and alias:
    1706            return f"{this} {alias}"
    1707
    1708        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
    1709        return f"{this} ({args})"

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

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

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

    1715    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    1716        kind = self.sql(expression, "kind")
    1717        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    1718        end = (
    1719            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    1720            or "CURRENT ROW"
    1721        )
    1722        return f"{kind} BETWEEN {start} AND {end}"

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

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

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

    1729    def between_sql(self, expression: exp.Between) -> str:
    1730        this = self.sql(expression, "this")
    1731        low = self.sql(expression, "low")
    1732        high = self.sql(expression, "high")
    1733        return f"{this} BETWEEN {low} AND {high}"

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

    1735    def bracket_sql(self, expression: exp.Bracket) -> str:
    1736        expressions = apply_index_offset(expression.this, expression.expressions, self.INDEX_OFFSET)
    1737        expressions_sql = ", ".join(self.sql(e) for e in expressions)
    1738
    1739        return f"{self.sql(expression, 'this')}[{expressions_sql}]"

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

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

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

    1744    def any_sql(self, expression: exp.Any) -> str:
    1745        this = self.sql(expression, "this")
    1746        if isinstance(expression.this, exp.Subqueryable):
    1747            this = self.wrap(this)
    1748        return f"ANY {this}"

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

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

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

    1753    def case_sql(self, expression: exp.Case) -> str:
    1754        this = self.sql(expression, "this")
    1755        statements = [f"CASE {this}" if this else "CASE"]
    1756
    1757        for e in expression.args["ifs"]:
    1758            statements.append(f"WHEN {self.sql(e, 'this')}")
    1759            statements.append(f"THEN {self.sql(e, 'true')}")
    1760
    1761        default = self.sql(expression, "default")
    1762
    1763        if default:
    1764            statements.append(f"ELSE {default}")
    1765
    1766        statements.append("END")
    1767
    1768        if self.pretty and self.text_width(statements) > self.max_text_width:
    1769            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    1770
    1771        return " ".join(statements)

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

    1773    def constraint_sql(self, expression: exp.Constraint) -> str:
    1774        this = self.sql(expression, "this")
    1775        expressions = self.expressions(expression, flat=True)
    1776        return f"CONSTRAINT {this} {expressions}"

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

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

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

    1783    def extract_sql(self, expression: exp.Extract) -> str:
    1784        this = self.sql(expression, "this")
    1785        expression_sql = self.sql(expression, "expression")
    1786        return f"EXTRACT({this} FROM {expression_sql})"

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

    1788    def trim_sql(self, expression: exp.Trim) -> str:
    1789        trim_type = self.sql(expression, "position")
    1790
    1791        if trim_type == "LEADING":
    1792            return self.func("LTRIM", expression.this)
    1793        elif trim_type == "TRAILING":
    1794            return self.func("RTRIM", expression.this)
    1795        else:
    1796            return self.func("TRIM", expression.this, expression.expression)

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

    1798    def safeconcat_sql(self, expression: exp.SafeConcat) -> str:
    1799        expressions = expression.expressions
    1800        if self.STRICT_STRING_CONCAT:
    1801            expressions = (exp.cast(e, "text") for e in expressions)
    1802        return self.func("CONCAT", *expressions)

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

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

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

    1808    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    1809        expressions = self.expressions(expression, flat=True)
    1810        reference = self.sql(expression, "reference")
    1811        reference = f" {reference}" if reference else ""
    1812        delete = self.sql(expression, "delete")
    1813        delete = f" ON DELETE {delete}" if delete else ""
    1814        update = self.sql(expression, "update")
    1815        update = f" ON UPDATE {update}" if update else ""
    1816        return f"FOREIGN KEY ({expressions}){reference}{delete}{update}"

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

    1818    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    1819        expressions = self.expressions(expression, flat=True)
    1820        options = self.expressions(expression, key="options", flat=True, sep=" ")
    1821        options = f" {options}" if options else ""
    1822        return f"PRIMARY KEY ({expressions}){options}"

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

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

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

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

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

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

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

    1835    def jsonobject_sql(self, expression: exp.JSONObject) -> str:
    1836        null_handling = expression.args.get("null_handling")
    1837        null_handling = f" {null_handling}" if null_handling else ""
    1838        unique_keys = expression.args.get("unique_keys")
    1839        if unique_keys is not None:
    1840            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    1841        else:
    1842            unique_keys = ""
    1843        return_type = self.sql(expression, "return_type")
    1844        return_type = f" RETURNING {return_type}" if return_type else ""
    1845        format_json = " FORMAT JSON" if expression.args.get("format_json") else ""
    1846        encoding = self.sql(expression, "encoding")
    1847        encoding = f" ENCODING {encoding}" if encoding else ""
    1848        return self.func(
    1849            "JSON_OBJECT",
    1850            *expression.expressions,
    1851            suffix=f"{null_handling}{unique_keys}{return_type}{format_json}{encoding})",
    1852        )

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

    1854    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    1855        this = self.sql(expression, "this")
    1856        kind = self.sql(expression, "kind")
    1857        path = self.sql(expression, "path")
    1858        path = f" {path}" if path else ""
    1859        as_json = " AS JSON" if expression.args.get("as_json") else ""
    1860        return f"{this} {kind}{path}{as_json}"

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

    1862    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    1863        this = self.sql(expression, "this")
    1864        path = self.sql(expression, "path")
    1865        path = f", {path}" if path else ""
    1866        expressions = self.expressions(expression)
    1867        with_ = (
    1868            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    1869            if expressions
    1870            else ""
    1871        )
    1872        return f"OPENJSON({this}{path}){with_}"

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

    1874    def in_sql(self, expression: exp.In) -> str:
    1875        query = expression.args.get("query")
    1876        unnest = expression.args.get("unnest")
    1877        field = expression.args.get("field")
    1878        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    1879
    1880        if query:
    1881            in_sql = self.wrap(query)
    1882        elif unnest:
    1883            in_sql = self.in_unnest_op(unnest)
    1884        elif field:
    1885            in_sql = self.sql(field)
    1886        else:
    1887            in_sql = f"({self.expressions(expression, flat=True)})"
    1888
    1889        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"

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

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

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

    1894    def interval_sql(self, expression: exp.Interval) -> str:
    1895        unit = self.sql(expression, "unit")
    1896        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    1897            unit = self.TIME_PART_SINGULARS.get(unit.lower(), unit)
    1898        unit = f" {unit}" if unit else ""
    1899
    1900        if self.SINGLE_STRING_INTERVAL:
    1901            this = expression.this.name if expression.this else ""
    1902            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    1903
    1904        this = self.sql(expression, "this")
    1905        if this:
    1906            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    1907            this = f" {this}" if unwrapped else f" ({this})"
    1908
    1909        return f"INTERVAL{this}{unit}"

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

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

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

    1914    def reference_sql(self, expression: exp.Reference) -> str:
    1915        this = self.sql(expression, "this")
    1916        expressions = self.expressions(expression, flat=True)
    1917        expressions = f"({expressions})" if expressions else ""
    1918        options = self.expressions(expression, key="options", flat=True, sep=" ")
    1919        options = f" {options}" if options else ""
    1920        return f"REFERENCES {this}{expressions}{options}"

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

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

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

    1925    def paren_sql(self, expression: exp.Paren) -> str:
    1926        if isinstance(expression.unnest(), exp.Select):
    1927            sql = self.wrap(expression)
    1928        else:
    1929            sql = self.seg(self.indent(self.sql(expression, "this")), sep="")
    1930            sql = f"({sql}{self.seg(')', sep='')}"
    1931
    1932        return self.prepend_ctes(expression, sql)

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

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

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

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

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

    1943    def alias_sql(self, expression: exp.Alias) -> str:
    1944        alias = self.sql(expression, "alias")
    1945        alias = f" AS {alias}" if alias else ""
    1946        return f"{self.sql(expression, 'this')}{alias}"

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

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

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

    1951    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    1952        this = self.sql(expression, "this")
    1953        zone = self.sql(expression, "zone")
    1954        return f"{this} AT TIME ZONE {zone}"

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

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

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

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

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

    1962    def connector_sql(self, expression: exp.Connector, op: str) -> str:
    1963        if not self.pretty:
    1964            return self.binary(expression, op)
    1965
    1966        sqls = tuple(
    1967            self.maybe_comment(self.sql(e), e, e.parent.comments or []) if i != 1 else self.sql(e)
    1968            for i, e in enumerate(expression.flatten(unnest=False))
    1969        )
    1970
    1971        sep = "\n" if self.text_width(sqls) > self.max_text_width else " "
    1972        return f"{sep}{op} ".join(sqls)

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

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

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

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

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

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

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

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

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

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

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

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

def cast_sql(self, expression: sqlglot.expressions.Cast) -> str: View Source

    1992    def cast_sql(self, expression: exp.Cast) -> str:
    1993        return f"CAST({self.sql(expression, 'this')} AS {self.sql(expression, 'to')})"

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

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

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

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

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

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

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

    2005    def comment_sql(self, expression: exp.Comment) -> str:
    2006        this = self.sql(expression, "this")
    2007        kind = expression.args["kind"]
    2008        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    2009        expression_sql = self.sql(expression, "expression")
    2010        return f"COMMENT{exists_sql}ON {kind} {this} IS {expression_sql}"

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

    2012    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    2013        this = self.sql(expression, "this")
    2014        delete = " DELETE" if expression.args.get("delete") else ""
    2015        recompress = self.sql(expression, "recompress")
    2016        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    2017        to_disk = self.sql(expression, "to_disk")
    2018        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    2019        to_volume = self.sql(expression, "to_volume")
    2020        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    2021        return f"{this}{delete}{recompress}{to_disk}{to_volume}"

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

    2023    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    2024        where = self.sql(expression, "where")
    2025        group = self.sql(expression, "group")
    2026        aggregates = self.expressions(expression, key="aggregates")
    2027        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    2028
    2029        if not (where or group or aggregates) and len(expression.expressions) == 1:
    2030            return f"TTL {self.expressions(expression, flat=True)}"
    2031
    2032        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"

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

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

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

    2037    def commit_sql(self, expression: exp.Commit) -> str:
    2038        chain = expression.args.get("chain")
    2039        if chain is not None:
    2040            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    2041
    2042        return f"COMMIT{chain or ''}"

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

    2044    def rollback_sql(self, expression: exp.Rollback) -> str:
    2045        savepoint = expression.args.get("savepoint")
    2046        savepoint = f" TO {savepoint}" if savepoint else ""
    2047        return f"ROLLBACK{savepoint}"

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

    2049    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    2050        this = self.sql(expression, "this")
    2051
    2052        dtype = self.sql(expression, "dtype")
    2053        if dtype:
    2054            collate = self.sql(expression, "collate")
    2055            collate = f" COLLATE {collate}" if collate else ""
    2056            using = self.sql(expression, "using")
    2057            using = f" USING {using}" if using else ""
    2058            return f"ALTER COLUMN {this} TYPE {dtype}{collate}{using}"
    2059
    2060        default = self.sql(expression, "default")
    2061        if default:
    2062            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    2063
    2064        if not expression.args.get("drop"):
    2065            self.unsupported("Unsupported ALTER COLUMN syntax")
    2066
    2067        return f"ALTER COLUMN {this} DROP DEFAULT"

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

    2069    def renametable_sql(self, expression: exp.RenameTable) -> str:
    2070        if not self.RENAME_TABLE_WITH_DB:
    2071            # Remove db from tables
    2072            expression = expression.transform(
    2073                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    2074            )
    2075        this = self.sql(expression, "this")
    2076        return f"RENAME TO {this}"

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

    2078    def altertable_sql(self, expression: exp.AlterTable) -> str:
    2079        actions = expression.args["actions"]
    2080
    2081        if isinstance(actions[0], exp.ColumnDef):
    2082            actions = self.expressions(expression, key="actions", prefix="ADD COLUMN ")
    2083        elif isinstance(actions[0], exp.Schema):
    2084            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    2085        elif isinstance(actions[0], exp.Delete):
    2086            actions = self.expressions(expression, key="actions", flat=True)
    2087        else:
    2088            actions = self.expressions(expression, key="actions")
    2089
    2090        exists = " IF EXISTS" if expression.args.get("exists") else ""
    2091        return f"ALTER TABLE{exists} {self.sql(expression, 'this')} {actions}"

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

    2093    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    2094        expressions = self.expressions(expression)
    2095        exists = " IF EXISTS " if expression.args.get("exists") else " "
    2096        return f"DROP{exists}{expressions}"

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

    2098    def addconstraint_sql(self, expression: exp.AddConstraint) -> str:
    2099        this = self.sql(expression, "this")
    2100        expression_ = self.sql(expression, "expression")
    2101        add_constraint = f"ADD CONSTRAINT {this}" if this else "ADD"
    2102
    2103        enforced = expression.args.get("enforced")
    2104        if enforced is not None:
    2105            return f"{add_constraint} CHECK ({expression_}){' ENFORCED' if enforced else ''}"
    2106
    2107        return f"{add_constraint} {expression_}"

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

    2109    def distinct_sql(self, expression: exp.Distinct) -> str:
    2110        this = self.expressions(expression, flat=True)
    2111        this = f" {this}" if this else ""
    2112
    2113        on = self.sql(expression, "on")
    2114        on = f" ON {on}" if on else ""
    2115        return f"DISTINCT{this}{on}"

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

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

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

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

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

    2123    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    2124        return self.sql(
    2125            exp.Cast(
    2126                this=exp.Div(this=expression.this, expression=expression.expression),
    2127                to=exp.DataType(this=exp.DataType.Type.INT),
    2128            )
    2129        )

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

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

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

    2134    def safedpipe_sql(self, expression: exp.SafeDPipe) -> str:
    2135        if self.STRICT_STRING_CONCAT:
    2136            return self.func("CONCAT", *(exp.cast(e, "text") for e in expression.flatten()))
    2137        return self.dpipe_sql(expression)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    2172    def is_sql(self, expression: exp.Is) -> str:
    2173        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    2174            return self.sql(
    2175                expression.this if expression.expression.this else exp.not_(expression.this)
    2176            )
    2177        return self.binary(expression, "IS")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    2218    def trycast_sql(self, expression: exp.TryCast) -> str:
    2219        return f"TRY_CAST({self.sql(expression, 'this')} AS {self.sql(expression, 'to')})"

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

    2221    def use_sql(self, expression: exp.Use) -> str:
    2222        kind = self.sql(expression, "kind")
    2223        kind = f" {kind}" if kind else ""
    2224        this = self.sql(expression, "this")
    2225        this = f" {this}" if this else ""
    2226        return f"USE{kind}{this}"

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

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

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

    2232    def function_fallback_sql(self, expression: exp.Func) -> str:
    2233        args = []
    2234        for arg_value in expression.args.values():
    2235            if isinstance(arg_value, list):
    2236                for value in arg_value:
    2237                    args.append(value)
    2238            else:
    2239                args.append(arg_value)
    2240
    2241        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

    2243    def func(
    2244        self,
    2245        name: str,
    2246        *args: t.Optional[exp.Expression | str],
    2247        prefix: str = "(",
    2248        suffix: str = ")",
    2249    ) -> str:
    2250        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

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

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

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

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

    2261    def format_time(self, expression: exp.Expression) -> t.Optional[str]:
    2262        return format_time(
    2263            self.sql(expression, "format"), self.INVERSE_TIME_MAPPING, self.INVERSE_TIME_TRIE
    2264        )

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

    2266    def expressions(
    2267        self,
    2268        expression: t.Optional[exp.Expression] = None,
    2269        key: t.Optional[str] = None,
    2270        sqls: t.Optional[t.List[str]] = None,
    2271        flat: bool = False,
    2272        indent: bool = True,
    2273        sep: str = ", ",
    2274        prefix: str = "",
    2275    ) -> str:
    2276        expressions = expression.args.get(key or "expressions") if expression else sqls
    2277
    2278        if not expressions:
    2279            return ""
    2280
    2281        if flat:
    2282            return sep.join(self.sql(e) for e in expressions)
    2283
    2284        num_sqls = len(expressions)
    2285
    2286        # These are calculated once in case we have the leading_comma / pretty option set, correspondingly
    2287        pad = " " * self.pad
    2288        stripped_sep = sep.strip()
    2289
    2290        result_sqls = []
    2291        for i, e in enumerate(expressions):
    2292            sql = self.sql(e, comment=False)
    2293            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    2294
    2295            if self.pretty:
    2296                if self.leading_comma:
    2297                    result_sqls.append(f"{sep if i > 0 else pad}{prefix}{sql}{comments}")
    2298                else:
    2299                    result_sqls.append(
    2300                        f"{prefix}{sql}{stripped_sep if i + 1 < num_sqls else ''}{comments}"
    2301                    )
    2302            else:
    2303                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    2304
    2305        result_sql = "\n".join(result_sqls) if self.pretty else "".join(result_sqls)
    2306        return self.indent(result_sql, skip_first=False) if indent else result_sql

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

    2308    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    2309        flat = flat or isinstance(expression.parent, exp.Properties)
    2310        expressions_sql = self.expressions(expression, flat=flat)
    2311        if flat:
    2312            return f"{op} {expressions_sql}"
    2313        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"

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

    2315    def naked_property(self, expression: exp.Property) -> str:
    2316        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    2317        if not property_name:
    2318            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    2319        return f"{property_name} {self.sql(expression, 'this')}"

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

    2321    def set_operation(self, expression: exp.Expression, op: str) -> str:
    2322        this = self.sql(expression, "this")
    2323        op = self.seg(op)
    2324        return self.query_modifiers(
    2325            expression, f"{this}{op}{self.sep()}{self.sql(expression, 'expression')}"
    2326        )

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

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

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

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

    2334    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    2335        this = self.sql(expression, "this")
    2336        expressions = self.no_identify(self.expressions, expression)
    2337        expressions = (
    2338            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    2339        )
    2340        return f"{this}{expressions}"

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

    2342    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    2343        this = self.sql(expression, "this")
    2344        expressions = self.expressions(expression, flat=True)
    2345        return f"{this}({expressions})"

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

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

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

    2350    def when_sql(self, expression: exp.When) -> str:
    2351        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    2352        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    2353        condition = self.sql(expression, "condition")
    2354        condition = f" AND {condition}" if condition else ""
    2355
    2356        then_expression = expression.args.get("then")
    2357        if isinstance(then_expression, exp.Insert):
    2358            then = f"INSERT {self.sql(then_expression, 'this')}"
    2359            if "expression" in then_expression.args:
    2360                then += f" VALUES {self.sql(then_expression, 'expression')}"
    2361        elif isinstance(then_expression, exp.Update):
    2362            if isinstance(then_expression.args.get("expressions"), exp.Star):
    2363                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    2364            else:
    2365                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    2366        else:
    2367            then = self.sql(then_expression)
    2368        return f"WHEN {matched}{source}{condition} THEN {then}"

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

    2370    def merge_sql(self, expression: exp.Merge) -> str:
    2371        this = self.sql(expression, "this")
    2372        using = f"USING {self.sql(expression, 'using')}"
    2373        on = f"ON {self.sql(expression, 'on')}"
    2374        return f"MERGE INTO {this} {using} {on} {self.expressions(expression, sep=' ')}"

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

    2376    def tochar_sql(self, expression: exp.ToChar) -> str:
    2377        if expression.args.get("format"):
    2378            self.unsupported("Format argument unsupported for TO_CHAR/TO_VARCHAR function")
    2379
    2380        return self.sql(exp.cast(expression.this, "text"))

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

    2382    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    2383        this = self.sql(expression, "this")
    2384        kind = self.sql(expression, "kind")
    2385        settings_sql = self.expressions(expression, key="settings", sep=" ")
    2386        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    2387        return f"{this}({kind}{args})"

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

    2389    def dictrange_sql(self, expression: exp.DictRange) -> str:
    2390        this = self.sql(expression, "this")
    2391        max = self.sql(expression, "max")
    2392        min = self.sql(expression, "min")
    2393        return f"{this}(MIN {min} MAX {max})"

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

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

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

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

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

    2402def cached_generator(
    2403    cache: t.Optional[t.Dict[int, str]] = None
    2404) -> t.Callable[[exp.Expression], str]:
    2405    """Returns a cached generator."""
    2406    cache = {} if cache is None else cache
    2407    generator = Generator(normalize=True, identify="safe")
    2408    return lambda e: generator.generate(e, cache)

Returns a cached generator.