Edit on GitHub

# sqlglot.generator

View Source

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

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

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

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

    361    def __init__(
    362        self,
    363        pretty: t.Optional[bool] = None,
    364        identify: str | bool = False,
    365        normalize: bool = False,
    366        pad: int = 2,
    367        indent: int = 2,
    368        normalize_functions: t.Optional[str | bool] = None,
    369        unsupported_level: ErrorLevel = ErrorLevel.WARN,
    370        max_unsupported: int = 3,
    371        leading_comma: bool = False,
    372        max_text_width: int = 80,
    373        comments: bool = True,
    374    ):
    375        import sqlglot
    376
    377        self.pretty = pretty if pretty is not None else sqlglot.pretty
    378        self.identify = identify
    379        self.normalize = normalize
    380        self.pad = pad
    381        self._indent = indent
    382        self.unsupported_level = unsupported_level
    383        self.max_unsupported = max_unsupported
    384        self.leading_comma = leading_comma
    385        self.max_text_width = max_text_width
    386        self.comments = comments
    387
    388        # This is both a Dialect property and a Generator argument, so we prioritize the latter
    389        self.normalize_functions = (
    390            self.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions
    391        )
    392
    393        self.unsupported_messages: t.List[str] = []
    394        self._escaped_quote_end: str = self.TOKENIZER_CLASS.STRING_ESCAPES[0] + self.QUOTE_END
    395        self._escaped_identifier_end: str = (
    396            self.TOKENIZER_CLASS.IDENTIFIER_ESCAPES[0] + self.IDENTIFIER_END
    397        )
    398        self._cache: t.Optional[t.Dict[int, str]] = None

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

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

Checks if text can be identified given an identify option.

###### Arguments:

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

###### Returns:

> Whether or not the given text can be identified.

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

    400    def generate(
    401        self,
    402        expression: t.Optional[exp.Expression],
    403        cache: t.Optional[t.Dict[int, str]] = None,
    404    ) -> str:
    405        """
    406        Generates the SQL string corresponding to the given syntax tree.
    407
    408        Args:
    409            expression: The syntax tree.
    410            cache: An optional sql string cache. This leverages the hash of an Expression
    411                which can be slow to compute, so only use it if you set _hash on each node.
    412
    413        Returns:
    414            The SQL string corresponding to `expression`.
    415        """
    416        if cache is not None:
    417            self._cache = cache
    418
    419        self.unsupported_messages = []
    420        sql = self.sql(expression).strip()
    421        self._cache = None
    422
    423        if self.unsupported_level == ErrorLevel.IGNORE:
    424            return sql
    425
    426        if self.unsupported_level == ErrorLevel.WARN:
    427            for msg in self.unsupported_messages:
    428                logger.warning(msg)
    429        elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages:
    430            raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported))
    431
    432        if self.pretty:
    433            sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n")
    434        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

    436    def unsupported(self, message: str) -> None:
    437        if self.unsupported_level == ErrorLevel.IMMEDIATE:
    438            raise UnsupportedError(message)
    439        self.unsupported_messages.append(message)

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

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

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

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

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

    447    def pad_comment(self, comment: str) -> str:
    448        comment = " " + comment if comment[0].strip() else comment
    449        comment = comment + " " if comment[-1].strip() else comment
    450        return comment

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

    452    def maybe_comment(
    453        self,
    454        sql: str,
    455        expression: t.Optional[exp.Expression] = None,
    456        comments: t.Optional[t.List[str]] = None,
    457    ) -> str:
    458        comments = (
    459            ((expression and expression.comments) if comments is None else comments)  # type: ignore
    460            if self.comments
    461            else None
    462        )
    463
    464        if not comments or isinstance(expression, exp.Binary):
    465            return sql
    466
    467        sep = "\n" if self.pretty else " "
    468        comments_sql = sep.join(
    469            f"/*{self.pad_comment(comment)}*/" for comment in comments if comment
    470        )
    471
    472        if not comments_sql:
    473            return sql
    474
    475        if isinstance(expression, self.WITH_SEPARATED_COMMENTS):
    476            return (
    477                f"{self.sep()}{comments_sql}{sql}"
    478                if sql[0].isspace()
    479                else f"{comments_sql}{self.sep()}{sql}"
    480            )
    481
    482        return f"{sql} {comments_sql}"

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

    484    def wrap(self, expression: exp.Expression | str) -> str:
    485        this_sql = self.indent(
    486            self.sql(expression)
    487            if isinstance(expression, (exp.Select, exp.Union))
    488            else self.sql(expression, "this"),
    489            level=1,
    490            pad=0,
    491        )
    492        return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"

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

    494    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
    495        original = self.identify
    496        self.identify = False
    497        result = func(*args, **kwargs)
    498        self.identify = original
    499        return result

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

    501    def normalize_func(self, name: str) -> str:
    502        if self.normalize_functions == "upper" or self.normalize_functions is True:
    503            return name.upper()
    504        if self.normalize_functions == "lower":
    505            return name.lower()
    506        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

    508    def indent(
    509        self,
    510        sql: str,
    511        level: int = 0,
    512        pad: t.Optional[int] = None,
    513        skip_first: bool = False,
    514        skip_last: bool = False,
    515    ) -> str:
    516        if not self.pretty:
    517            return sql
    518
    519        pad = self.pad if pad is None else pad
    520        lines = sql.split("\n")
    521
    522        return "\n".join(
    523            line
    524            if (skip_first and i == 0) or (skip_last and i == len(lines) - 1)
    525            else f"{' ' * (level * self._indent + pad)}{line}"
    526            for i, line in enumerate(lines)
    527        )

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

    529    def sql(
    530        self,
    531        expression: t.Optional[str | exp.Expression],
    532        key: t.Optional[str] = None,
    533        comment: bool = True,
    534    ) -> str:
    535        if not expression:
    536            return ""
    537
    538        if isinstance(expression, str):
    539            return expression
    540
    541        if key:
    542            value = expression.args.get(key)
    543            if value:
    544                return self.sql(value)
    545            return ""
    546
    547        if self._cache is not None:
    548            expression_id = hash(expression)
    549
    550            if expression_id in self._cache:
    551                return self._cache[expression_id]
    552
    553        transform = self.TRANSFORMS.get(expression.__class__)
    554
    555        if callable(transform):
    556            sql = transform(self, expression)
    557        elif transform:
    558            sql = transform
    559        elif isinstance(expression, exp.Expression):
    560            exp_handler_name = f"{expression.key}_sql"
    561
    562            if hasattr(self, exp_handler_name):
    563                sql = getattr(self, exp_handler_name)(expression)
    564            elif isinstance(expression, exp.Func):
    565                sql = self.function_fallback_sql(expression)
    566            elif isinstance(expression, exp.Property):
    567                sql = self.property_sql(expression)
    568            else:
    569                raise ValueError(f"Unsupported expression type {expression.__class__.__name__}")
    570        else:
    571            raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}")
    572
    573        sql = self.maybe_comment(sql, expression) if self.comments and comment else sql
    574
    575        if self._cache is not None:
    576            self._cache[expression_id] = sql
    577        return sql

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

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

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

    584    def cache_sql(self, expression: exp.Cache) -> str:
    585        lazy = " LAZY" if expression.args.get("lazy") else ""
    586        table = self.sql(expression, "this")
    587        options = expression.args.get("options")
    588        options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else ""
    589        sql = self.sql(expression, "expression")
    590        sql = f" AS{self.sep()}{sql}" if sql else ""
    591        sql = f"CACHE{lazy} TABLE {table}{options}{sql}"
    592        return self.prepend_ctes(expression, sql)

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

    594    def characterset_sql(self, expression: exp.CharacterSet) -> str:
    595        if isinstance(expression.parent, exp.Cast):
    596            return f"CHAR CHARACTER SET {self.sql(expression, 'this')}"
    597        default = "DEFAULT " if expression.args.get("default") else ""
    598        return f"{default}CHARACTER SET={self.sql(expression, 'this')}"

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

    600    def column_sql(self, expression: exp.Column) -> str:
    601        join_mark = " (+)" if expression.args.get("join_mark") else ""
    602
    603        if join_mark and not self.COLUMN_JOIN_MARKS_SUPPORTED:
    604            join_mark = ""
    605            self.unsupported("Outer join syntax using the (+) operator is not supported.")
    606
    607        column = ".".join(
    608            self.sql(part)
    609            for part in (
    610                expression.args.get("catalog"),
    611                expression.args.get("db"),
    612                expression.args.get("table"),
    613                expression.args.get("this"),
    614            )
    615            if part
    616        )
    617
    618        return f"{column}{join_mark}"

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

    620    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
    621        this = self.sql(expression, "this")
    622        this = f" {this}" if this else ""
    623        position = self.sql(expression, "position")
    624        return f"{position}{this}"

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

    626    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
    627        column = self.sql(expression, "this")
    628        kind = self.sql(expression, "kind")
    629        constraints = self.expressions(expression, key="constraints", sep=" ", flat=True)
    630        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
    631        kind = f"{sep}{kind}" if kind else ""
    632        constraints = f" {constraints}" if constraints else ""
    633        position = self.sql(expression, "position")
    634        position = f" {position}" if position else ""
    635
    636        return f"{exists}{column}{kind}{constraints}{position}"

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

    638    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
    639        this = self.sql(expression, "this")
    640        kind_sql = self.sql(expression, "kind").strip()
    641        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql

def computedcolumnconstraint_sql(self, expression: sqlglot.expressions.ComputedColumnConstraint) -> str: View Source

    643    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
    644        this = self.sql(expression, "this")
    645        if expression.args.get("not_null"):
    646            persisted = " PERSISTED NOT NULL"
    647        elif expression.args.get("persisted"):
    648            persisted = " PERSISTED"
    649        else:
    650            persisted = ""
    651        return f"AS {this}{persisted}"

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

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

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

    656    def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str:
    657        if isinstance(expression.this, list):
    658            this = self.wrap(self.expressions(expression, key="this", flat=True))
    659        else:
    660            this = self.sql(expression, "this")
    661
    662        return f"COMPRESS {this}"

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

    664    def generatedasidentitycolumnconstraint_sql(
    665        self, expression: exp.GeneratedAsIdentityColumnConstraint
    666    ) -> str:
    667        this = ""
    668        if expression.this is not None:
    669            on_null = " ON NULL" if expression.args.get("on_null") else ""
    670            this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}"
    671
    672        start = expression.args.get("start")
    673        start = f"START WITH {start}" if start else ""
    674        increment = expression.args.get("increment")
    675        increment = f" INCREMENT BY {increment}" if increment else ""
    676        minvalue = expression.args.get("minvalue")
    677        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    678        maxvalue = expression.args.get("maxvalue")
    679        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    680        cycle = expression.args.get("cycle")
    681        cycle_sql = ""
    682
    683        if cycle is not None:
    684            cycle_sql = f"{' NO' if not cycle else ''} CYCLE"
    685            cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql
    686
    687        sequence_opts = ""
    688        if start or increment or cycle_sql:
    689            sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}"
    690            sequence_opts = f" ({sequence_opts.strip()})"
    691
    692        expr = self.sql(expression, "expression")
    693        expr = f"({expr})" if expr else "IDENTITY"
    694
    695        return f"GENERATED{this} AS {expr}{sequence_opts}"

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

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

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

    700    def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str:
    701        desc = expression.args.get("desc")
    702        if desc is not None:
    703            return f"PRIMARY KEY{' DESC' if desc else ' ASC'}"
    704        return f"PRIMARY KEY"

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

    706    def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str:
    707        this = self.sql(expression, "this")
    708        this = f" {this}" if this else ""
    709        return f"UNIQUE{this}"

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

    711    def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
    712        return self.sql(expression, "this")

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

    714    def create_sql(self, expression: exp.Create) -> str:
    715        kind = self.sql(expression, "kind").upper()
    716        properties = expression.args.get("properties")
    717        properties_locs = self.locate_properties(properties) if properties else defaultdict()
    718
    719        this = self.createable_sql(expression, properties_locs)
    720
    721        properties_sql = ""
    722        if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get(
    723            exp.Properties.Location.POST_WITH
    724        ):
    725            properties_sql = self.sql(
    726                exp.Properties(
    727                    expressions=[
    728                        *properties_locs[exp.Properties.Location.POST_SCHEMA],
    729                        *properties_locs[exp.Properties.Location.POST_WITH],
    730                    ]
    731                )
    732            )
    733
    734        begin = " BEGIN" if expression.args.get("begin") else ""
    735        expression_sql = self.sql(expression, "expression")
    736        if expression_sql:
    737            expression_sql = f"{begin}{self.sep()}{expression_sql}"
    738
    739            if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return):
    740                if properties_locs.get(exp.Properties.Location.POST_ALIAS):
    741                    postalias_props_sql = self.properties(
    742                        exp.Properties(
    743                            expressions=properties_locs[exp.Properties.Location.POST_ALIAS]
    744                        ),
    745                        wrapped=False,
    746                    )
    747                    expression_sql = f" AS {postalias_props_sql}{expression_sql}"
    748                else:
    749                    expression_sql = f" AS{expression_sql}"
    750
    751        postindex_props_sql = ""
    752        if properties_locs.get(exp.Properties.Location.POST_INDEX):
    753            postindex_props_sql = self.properties(
    754                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]),
    755                wrapped=False,
    756                prefix=" ",
    757            )
    758
    759        indexes = self.expressions(expression, key="indexes", indent=False, sep=" ")
    760        indexes = f" {indexes}" if indexes else ""
    761        index_sql = indexes + postindex_props_sql
    762
    763        replace = " OR REPLACE" if expression.args.get("replace") else ""
    764        unique = " UNIQUE" if expression.args.get("unique") else ""
    765
    766        postcreate_props_sql = ""
    767        if properties_locs.get(exp.Properties.Location.POST_CREATE):
    768            postcreate_props_sql = self.properties(
    769                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]),
    770                sep=" ",
    771                prefix=" ",
    772                wrapped=False,
    773            )
    774
    775        modifiers = "".join((replace, unique, postcreate_props_sql))
    776
    777        postexpression_props_sql = ""
    778        if properties_locs.get(exp.Properties.Location.POST_EXPRESSION):
    779            postexpression_props_sql = self.properties(
    780                exp.Properties(
    781                    expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION]
    782                ),
    783                sep=" ",
    784                prefix=" ",
    785                wrapped=False,
    786            )
    787
    788        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
    789        no_schema_binding = (
    790            " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else ""
    791        )
    792
    793        clone = self.sql(expression, "clone")
    794        clone = f" {clone}" if clone else ""
    795
    796        expression_sql = f"CREATE{modifiers} {kind}{exists_sql} {this}{properties_sql}{expression_sql}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}"
    797        return self.prepend_ctes(expression, expression_sql)

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

    799    def clone_sql(self, expression: exp.Clone) -> str:
    800        this = self.sql(expression, "this")
    801        shallow = "SHALLOW " if expression.args.get("shallow") else ""
    802        this = f"{shallow}CLONE {this}"
    803        when = self.sql(expression, "when")
    804
    805        if when:
    806            kind = self.sql(expression, "kind")
    807            expr = self.sql(expression, "expression")
    808            return f"{this} {when} ({kind} => {expr})"
    809
    810        return this

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

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

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

    815    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
    816        with_ = self.sql(expression, "with")
    817        if with_:
    818            sql = f"{with_}{self.sep()}{sql}"
    819        return sql

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

    821    def with_sql(self, expression: exp.With) -> str:
    822        sql = self.expressions(expression, flat=True)
    823        recursive = "RECURSIVE " if expression.args.get("recursive") else ""
    824
    825        return f"WITH {recursive}{sql}"

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

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

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

    831    def tablealias_sql(self, expression: exp.TableAlias) -> str:
    832        alias = self.sql(expression, "this")
    833        columns = self.expressions(expression, key="columns", flat=True)
    834        columns = f"({columns})" if columns else ""
    835        return f"{alias}{columns}"

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

    837    def bitstring_sql(self, expression: exp.BitString) -> str:
    838        this = self.sql(expression, "this")
    839        if self.BIT_START:
    840            return f"{self.BIT_START}{this}{self.BIT_END}"
    841        return f"{int(this, 2)}"

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

    843    def hexstring_sql(self, expression: exp.HexString) -> str:
    844        this = self.sql(expression, "this")
    845        if self.HEX_START:
    846            return f"{self.HEX_START}{this}{self.HEX_END}"
    847        return f"{int(this, 16)}"

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

    849    def bytestring_sql(self, expression: exp.ByteString) -> str:
    850        this = self.sql(expression, "this")
    851        if self.BYTE_START:
    852            return f"{self.BYTE_START}{this}{self.BYTE_END}"
    853        return this

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

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

def datatypeparam_sql(self, expression: sqlglot.expressions.DataTypeParam) -> str: View Source

    859    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
    860        this = self.sql(expression, "this")
    861        specifier = self.sql(expression, "expression")
    862        specifier = f" {specifier}" if specifier else ""
    863        return f"{this}{specifier}"

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

    865    def datatype_sql(self, expression: exp.DataType) -> str:
    866        type_value = expression.this
    867
    868        if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"):
    869            type_sql = self.sql(expression, "kind")
    870        else:
    871            type_sql = (
    872                self.TYPE_MAPPING.get(type_value, type_value.value)
    873                if isinstance(type_value, exp.DataType.Type)
    874                else type_value
    875            )
    876
    877        nested = ""
    878        interior = self.expressions(expression, flat=True)
    879        values = ""
    880
    881        if interior:
    882            if expression.args.get("nested"):
    883                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
    884                if expression.args.get("values") is not None:
    885                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
    886                    values = self.expressions(expression, key="values", flat=True)
    887                    values = f"{delimiters[0]}{values}{delimiters[1]}"
    888            elif type_value == exp.DataType.Type.INTERVAL:
    889                nested = f" {interior}"
    890            else:
    891                nested = f"({interior})"
    892
    893        type_sql = f"{type_sql}{nested}{values}"
    894        if self.TZ_TO_WITH_TIME_ZONE and type_value in (
    895            exp.DataType.Type.TIMETZ,
    896            exp.DataType.Type.TIMESTAMPTZ,
    897        ):
    898            type_sql = f"{type_sql} WITH TIME ZONE"
    899
    900        return type_sql

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

    902    def directory_sql(self, expression: exp.Directory) -> str:
    903        local = "LOCAL " if expression.args.get("local") else ""
    904        row_format = self.sql(expression, "row_format")
    905        row_format = f" {row_format}" if row_format else ""
    906        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"

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

    908    def delete_sql(self, expression: exp.Delete) -> str:
    909        this = self.sql(expression, "this")
    910        this = f" FROM {this}" if this else ""
    911        using = self.sql(expression, "using")
    912        using = f" USING {using}" if using else ""
    913        where = self.sql(expression, "where")
    914        returning = self.sql(expression, "returning")
    915        limit = self.sql(expression, "limit")
    916        tables = self.expressions(expression, key="tables")
    917        tables = f" {tables}" if tables else ""
    918        if self.RETURNING_END:
    919            expression_sql = f"{this}{using}{where}{returning}{limit}"
    920        else:
    921            expression_sql = f"{returning}{this}{using}{where}{limit}"
    922        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")

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

    924    def drop_sql(self, expression: exp.Drop) -> str:
    925        this = self.sql(expression, "this")
    926        kind = expression.args["kind"]
    927        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    928        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    929        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    930        cascade = " CASCADE" if expression.args.get("cascade") else ""
    931        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
    932        purge = " PURGE" if expression.args.get("purge") else ""
    933        return (
    934            f"DROP{temporary}{materialized} {kind}{exists_sql}{this}{cascade}{constraints}{purge}"
    935        )

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

    937    def except_sql(self, expression: exp.Except) -> str:
    938        return self.prepend_ctes(
    939            expression,
    940            self.set_operation(expression, self.except_op(expression)),
    941        )

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

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

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

    946    def fetch_sql(self, expression: exp.Fetch) -> str:
    947        direction = expression.args.get("direction")
    948        direction = f" {direction.upper()}" if direction else ""
    949        count = expression.args.get("count")
    950        count = f" {count}" if count else ""
    951        if expression.args.get("percent"):
    952            count = f"{count} PERCENT"
    953        with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY"
    954        return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}"

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

    956    def filter_sql(self, expression: exp.Filter) -> str:
    957        this = self.sql(expression, "this")
    958        where = self.sql(expression, "expression").strip()
    959        return f"{this} FILTER({where})"

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

    961    def hint_sql(self, expression: exp.Hint) -> str:
    962        if not self.QUERY_HINTS:
    963            self.unsupported("Hints are not supported")
    964            return ""
    965
    966        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"

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

    968    def index_sql(self, expression: exp.Index) -> str:
    969        unique = "UNIQUE " if expression.args.get("unique") else ""
    970        primary = "PRIMARY " if expression.args.get("primary") else ""
    971        amp = "AMP " if expression.args.get("amp") else ""
    972        name = self.sql(expression, "this")
    973        name = f"{name} " if name else ""
    974        table = self.sql(expression, "table")
    975        table = f"{self.INDEX_ON} {table}" if table else ""
    976        using = self.sql(expression, "using")
    977        using = f" USING {using} " if using else ""
    978        index = "INDEX " if not table else ""
    979        columns = self.expressions(expression, key="columns", flat=True)
    980        columns = f"({columns})" if columns else ""
    981        partition_by = self.expressions(expression, key="partition_by", flat=True)
    982        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
    983        return f"{unique}{primary}{amp}{index}{name}{table}{using}{columns}{partition_by}"

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

    985    def identifier_sql(self, expression: exp.Identifier) -> str:
    986        text = expression.name
    987        lower = text.lower()
    988        text = lower if self.normalize and not expression.quoted else text
    989        text = text.replace(self.IDENTIFIER_END, self._escaped_identifier_end)
    990        if (
    991            expression.quoted
    992            or self.can_identify(text, self.identify)
    993            or lower in self.RESERVED_KEYWORDS
    994            or (not self.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
    995        ):
    996            text = f"{self.IDENTIFIER_START}{text}{self.IDENTIFIER_END}"
    997        return text

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

     999    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    1000        input_format = self.sql(expression, "input_format")
    1001        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    1002        output_format = self.sql(expression, "output_format")
    1003        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    1004        return self.sep().join((input_format, output_format))

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

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

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

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

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

    1013    def properties_sql(self, expression: exp.Properties) -> str:
    1014        root_properties = []
    1015        with_properties = []
    1016
    1017        for p in expression.expressions:
    1018            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1019            if p_loc == exp.Properties.Location.POST_WITH:
    1020                with_properties.append(p.copy())
    1021            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    1022                root_properties.append(p.copy())
    1023
    1024        return self.root_properties(
    1025            exp.Properties(expressions=root_properties)
    1026        ) + self.with_properties(exp.Properties(expressions=with_properties))

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

    1028    def root_properties(self, properties: exp.Properties) -> str:
    1029        if properties.expressions:
    1030            return self.sep() + self.expressions(properties, indent=False, sep=" ")
    1031        return ""

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

    1033    def properties(
    1034        self,
    1035        properties: exp.Properties,
    1036        prefix: str = "",
    1037        sep: str = ", ",
    1038        suffix: str = "",
    1039        wrapped: bool = True,
    1040    ) -> str:
    1041        if properties.expressions:
    1042            expressions = self.expressions(properties, sep=sep, indent=False)
    1043            if expressions:
    1044                expressions = self.wrap(expressions) if wrapped else expressions
    1045                return f"{prefix}{' ' if prefix and prefix != ' ' else ''}{expressions}{suffix}"
    1046        return ""

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

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

def locate_properties(self, properties: sqlglot.expressions.Properties) -> DefaultDict: View Source

    1051    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
    1052        properties_locs = defaultdict(list)
    1053        for p in properties.expressions:
    1054            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1055            if p_loc != exp.Properties.Location.UNSUPPORTED:
    1056                properties_locs[p_loc].append(p.copy())
    1057            else:
    1058                self.unsupported(f"Unsupported property {p.key}")
    1059
    1060        return properties_locs

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

    1062    def property_sql(self, expression: exp.Property) -> str:
    1063        property_cls = expression.__class__
    1064        if property_cls == exp.Property:
    1065            return f"{expression.name}={self.sql(expression, 'value')}"
    1066
    1067        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    1068        if not property_name:
    1069            self.unsupported(f"Unsupported property {expression.key}")
    1070
    1071        return f"{property_name}={self.sql(expression, 'this')}"

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

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

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

    1078    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1079        no = "NO " if expression.args.get("no") else ""
    1080        protection = " PROTECTION" if expression.args.get("protection") else ""
    1081        return f"{no}FALLBACK{protection}"

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

    1083    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1084        no = "NO " if expression.args.get("no") else ""
    1085        local = expression.args.get("local")
    1086        local = f"{local} " if local else ""
    1087        dual = "DUAL " if expression.args.get("dual") else ""
    1088        before = "BEFORE " if expression.args.get("before") else ""
    1089        after = "AFTER " if expression.args.get("after") else ""
    1090        return f"{no}{local}{dual}{before}{after}JOURNAL"

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

    1092    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1093        freespace = self.sql(expression, "this")
    1094        percent = " PERCENT" if expression.args.get("percent") else ""
    1095        return f"FREESPACE={freespace}{percent}"

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

    1097    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1098        if expression.args.get("default"):
    1099            property = "DEFAULT"
    1100        elif expression.args.get("on"):
    1101            property = "ON"
    1102        else:
    1103            property = "OFF"
    1104        return f"CHECKSUM={property}"

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

    1106    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1107        if expression.args.get("no"):
    1108            return "NO MERGEBLOCKRATIO"
    1109        if expression.args.get("default"):
    1110            return "DEFAULT MERGEBLOCKRATIO"
    1111
    1112        percent = " PERCENT" if expression.args.get("percent") else ""
    1113        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"

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

    1115    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1116        default = expression.args.get("default")
    1117        minimum = expression.args.get("minimum")
    1118        maximum = expression.args.get("maximum")
    1119        if default or minimum or maximum:
    1120            if default:
    1121                prop = "DEFAULT"
    1122            elif minimum:
    1123                prop = "MINIMUM"
    1124            else:
    1125                prop = "MAXIMUM"
    1126            return f"{prop} DATABLOCKSIZE"
    1127        units = expression.args.get("units")
    1128        units = f" {units}" if units else ""
    1129        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"

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

    1131    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1132        autotemp = expression.args.get("autotemp")
    1133        always = expression.args.get("always")
    1134        default = expression.args.get("default")
    1135        manual = expression.args.get("manual")
    1136        never = expression.args.get("never")
    1137
    1138        if autotemp is not None:
    1139            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1140        elif always:
    1141            prop = "ALWAYS"
    1142        elif default:
    1143            prop = "DEFAULT"
    1144        elif manual:
    1145            prop = "MANUAL"
    1146        elif never:
    1147            prop = "NEVER"
    1148        return f"BLOCKCOMPRESSION={prop}"

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

    1150    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1151        no = expression.args.get("no")
    1152        no = " NO" if no else ""
    1153        concurrent = expression.args.get("concurrent")
    1154        concurrent = " CONCURRENT" if concurrent else ""
    1155
    1156        for_ = ""
    1157        if expression.args.get("for_all"):
    1158            for_ = " FOR ALL"
    1159        elif expression.args.get("for_insert"):
    1160            for_ = " FOR INSERT"
    1161        elif expression.args.get("for_none"):
    1162            for_ = " FOR NONE"
    1163        return f"WITH{no}{concurrent} ISOLATED LOADING{for_}"

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

    1165    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1166        kind = expression.args.get("kind")
    1167        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1168        for_or_in = expression.args.get("for_or_in")
    1169        lock_type = expression.args.get("lock_type")
    1170        override = " OVERRIDE" if expression.args.get("override") else ""
    1171        return f"LOCKING {kind}{this} {for_or_in} {lock_type}{override}"

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

    1173    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1174        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1175        statistics = expression.args.get("statistics")
    1176        statistics_sql = ""
    1177        if statistics is not None:
    1178            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1179        return f"{data_sql}{statistics_sql}"

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

    1181    def insert_sql(self, expression: exp.Insert) -> str:
    1182        overwrite = expression.args.get("overwrite")
    1183
    1184        if isinstance(expression.this, exp.Directory):
    1185            this = " OVERWRITE" if overwrite else " INTO"
    1186        else:
    1187            this = " OVERWRITE TABLE" if overwrite else " INTO"
    1188
    1189        alternative = expression.args.get("alternative")
    1190        alternative = f" OR {alternative}" if alternative else ""
    1191        ignore = " IGNORE" if expression.args.get("ignore") else ""
    1192
    1193        this = f"{this} {self.sql(expression, 'this')}"
    1194
    1195        exists = " IF EXISTS" if expression.args.get("exists") else ""
    1196        partition_sql = (
    1197            f" {self.sql(expression, 'partition')}" if expression.args.get("partition") else ""
    1198        )
    1199        where = self.sql(expression, "where")
    1200        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
    1201        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
    1202        conflict = self.sql(expression, "conflict")
    1203        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1204        returning = self.sql(expression, "returning")
    1205
    1206        if self.RETURNING_END:
    1207            expression_sql = f"{expression_sql}{conflict}{returning}"
    1208        else:
    1209            expression_sql = f"{returning}{expression_sql}{conflict}"
    1210
    1211        sql = f"INSERT{alternative}{ignore}{this}{by_name}{exists}{partition_sql}{where}{expression_sql}"
    1212        return self.prepend_ctes(expression, sql)

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

    1214    def intersect_sql(self, expression: exp.Intersect) -> str:
    1215        return self.prepend_ctes(
    1216            expression,
    1217            self.set_operation(expression, self.intersect_op(expression)),
    1218        )

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

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

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

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

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

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

def objectidentifier_sql(self, expression: sqlglot.expressions.ObjectIdentifier) -> str: View Source

    1229    def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str:
    1230        return expression.name.upper()

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

    1232    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1233        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1234        constraint = self.sql(expression, "constraint")
    1235        if constraint:
    1236            constraint = f"ON CONSTRAINT {constraint}"
    1237        key = self.expressions(expression, key="key", flat=True)
    1238        do = "" if expression.args.get("duplicate") else " DO "
    1239        nothing = "NOTHING" if expression.args.get("nothing") else ""
    1240        expressions = self.expressions(expression, flat=True)
    1241        set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
    1242        if expressions:
    1243            expressions = f"UPDATE {set_keyword}{expressions}"
    1244        return f"{self.seg(conflict)} {constraint}{key}{do}{nothing}{expressions}"

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

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

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

    1249    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1250        fields = expression.args.get("fields")
    1251        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1252        escaped = expression.args.get("escaped")
    1253        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1254        items = expression.args.get("collection_items")
    1255        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1256        keys = expression.args.get("map_keys")
    1257        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1258        lines = expression.args.get("lines")
    1259        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1260        null = expression.args.get("null")
    1261        null = f" NULL DEFINED AS {null}" if null else ""
    1262        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"

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

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

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

    1267    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1268        this = f"{self.sql(expression, 'this')} INDEX"
    1269        target = self.sql(expression, "target")
    1270        target = f" FOR {target}" if target else ""
    1271        return f"{this}{target} ({self.expressions(expression, flat=True)})"

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

    1273    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1274        table = ".".join(
    1275            part
    1276            for part in [
    1277                self.sql(expression, "catalog"),
    1278                self.sql(expression, "db"),
    1279                self.sql(expression, "this"),
    1280            ]
    1281            if part
    1282        )
    1283
    1284        version = self.sql(expression, "version")
    1285        version = f" {version}" if version else ""
    1286        alias = self.sql(expression, "alias")
    1287        alias = f"{sep}{alias}" if alias else ""
    1288        hints = self.expressions(expression, key="hints", sep=" ")
    1289        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
    1290        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    1291        pivots = f" {pivots}" if pivots else ""
    1292        joins = self.expressions(expression, key="joins", sep="", skip_first=True)
    1293        laterals = self.expressions(expression, key="laterals", sep="")
    1294
    1295        return f"{table}{version}{alias}{hints}{pivots}{joins}{laterals}"

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

    1297    def tablesample_sql(
    1298        self, expression: exp.TableSample, seed_prefix: str = "SEED", sep=" AS "
    1299    ) -> str:
    1300        if self.ALIAS_POST_TABLESAMPLE and expression.this.alias:
    1301            table = expression.this.copy()
    1302            table.set("alias", None)
    1303            this = self.sql(table)
    1304            alias = f"{sep}{self.sql(expression.this, 'alias')}"
    1305        else:
    1306            this = self.sql(expression, "this")
    1307            alias = ""
    1308        method = self.sql(expression, "method")
    1309        method = f"{method.upper()} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    1310        numerator = self.sql(expression, "bucket_numerator")
    1311        denominator = self.sql(expression, "bucket_denominator")
    1312        field = self.sql(expression, "bucket_field")
    1313        field = f" ON {field}" if field else ""
    1314        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    1315        percent = self.sql(expression, "percent")
    1316        percent = f"{percent} PERCENT" if percent else ""
    1317        rows = self.sql(expression, "rows")
    1318        rows = f"{rows} ROWS" if rows else ""
    1319        size = self.sql(expression, "size")
    1320        if size and self.TABLESAMPLE_SIZE_IS_PERCENT:
    1321            size = f"{size} PERCENT"
    1322        seed = self.sql(expression, "seed")
    1323        seed = f" {seed_prefix} ({seed})" if seed else ""
    1324        kind = expression.args.get("kind", "TABLESAMPLE")
    1325        return f"{this} {kind} {method}({bucket}{percent}{rows}{size}){seed}{alias}"

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

    1327    def pivot_sql(self, expression: exp.Pivot) -> str:
    1328        expressions = self.expressions(expression, flat=True)
    1329
    1330        if expression.this:
    1331            this = self.sql(expression, "this")
    1332            on = f"{self.seg('ON')} {expressions}"
    1333            using = self.expressions(expression, key="using", flat=True)
    1334            using = f"{self.seg('USING')} {using}" if using else ""
    1335            group = self.sql(expression, "group")
    1336            return f"PIVOT {this}{on}{using}{group}"
    1337
    1338        alias = self.sql(expression, "alias")
    1339        alias = f" AS {alias}" if alias else ""
    1340        unpivot = expression.args.get("unpivot")
    1341        direction = "UNPIVOT" if unpivot else "PIVOT"
    1342        field = self.sql(expression, "field")
    1343        include_nulls = expression.args.get("include_nulls")
    1344        if include_nulls is not None:
    1345            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
    1346        else:
    1347            nulls = ""
    1348        return f"{direction}{nulls}({expressions} FOR {field}){alias}"

def version_sql(self, expression: sqlglot.expressions.Version) -> str: View Source

    1350    def version_sql(self, expression: exp.Version) -> str:
    1351        this = f"FOR {expression.name}"
    1352        kind = expression.text("kind")
    1353        expr = self.sql(expression, "expression")
    1354        return f"{this} {kind} {expr}"

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

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

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

    1359    def update_sql(self, expression: exp.Update) -> str:
    1360        this = self.sql(expression, "this")
    1361        set_sql = self.expressions(expression, flat=True)
    1362        from_sql = self.sql(expression, "from")
    1363        where_sql = self.sql(expression, "where")
    1364        returning = self.sql(expression, "returning")
    1365        order = self.sql(expression, "order")
    1366        limit = self.sql(expression, "limit")
    1367        if self.RETURNING_END:
    1368            expression_sql = f"{from_sql}{where_sql}{returning}"
    1369        else:
    1370            expression_sql = f"{returning}{from_sql}{where_sql}"
    1371        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
    1372        return self.prepend_ctes(expression, sql)

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

    1374    def values_sql(self, expression: exp.Values) -> str:
    1375        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
    1376        if self.VALUES_AS_TABLE or not expression.find_ancestor(exp.From, exp.Join):
    1377            args = self.expressions(expression)
    1378            alias = self.sql(expression, "alias")
    1379            values = f"VALUES{self.seg('')}{args}"
    1380            values = (
    1381                f"({values})"
    1382                if self.WRAP_DERIVED_VALUES and (alias or isinstance(expression.parent, exp.From))
    1383                else values
    1384            )
    1385            return f"{values} AS {alias}" if alias else values
    1386
    1387        # Converts `VALUES...` expression into a series of select unions.
    1388        # Note: If you have a lot of unions then this will result in a large number of recursive statements to
    1389        # evaluate the expression. You may need to increase `sys.setrecursionlimit` to run and it can also be
    1390        # very slow.
    1391        expression = expression.copy()
    1392        column_names = expression.alias and expression.args["alias"].columns
    1393
    1394        selects = []
    1395
    1396        for i, tup in enumerate(expression.expressions):
    1397            row = tup.expressions
    1398
    1399            if i == 0 and column_names:
    1400                row = [
    1401                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
    1402                ]
    1403
    1404            selects.append(exp.Select(expressions=row))
    1405
    1406        subquery_expression: exp.Select | exp.Union = selects[0]
    1407        if len(selects) > 1:
    1408            for select in selects[1:]:
    1409                subquery_expression = exp.union(
    1410                    subquery_expression, select, distinct=False, copy=False
    1411                )
    1412
    1413        return self.subquery_sql(subquery_expression.subquery(expression.alias, copy=False))

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

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

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

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

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

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

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

    1426    def group_sql(self, expression: exp.Group) -> str:
    1427        group_by = self.op_expressions("GROUP BY", expression)
    1428
    1429        if expression.args.get("all"):
    1430            return f"{group_by} ALL"
    1431
    1432        grouping_sets = self.expressions(expression, key="grouping_sets", indent=False)
    1433        grouping_sets = (
    1434            f"{self.seg('GROUPING SETS')} {self.wrap(grouping_sets)}" if grouping_sets else ""
    1435        )
    1436
    1437        cube = expression.args.get("cube", [])
    1438        if seq_get(cube, 0) is True:
    1439            return f"{group_by}{self.seg('WITH CUBE')}"
    1440        else:
    1441            cube_sql = self.expressions(expression, key="cube", indent=False)
    1442            cube_sql = f"{self.seg('CUBE')} {self.wrap(cube_sql)}" if cube_sql else ""
    1443
    1444        rollup = expression.args.get("rollup", [])
    1445        if seq_get(rollup, 0) is True:
    1446            return f"{group_by}{self.seg('WITH ROLLUP')}"
    1447        else:
    1448            rollup_sql = self.expressions(expression, key="rollup", indent=False)
    1449            rollup_sql = f"{self.seg('ROLLUP')} {self.wrap(rollup_sql)}" if rollup_sql else ""
    1450
    1451        groupings = csv(
    1452            grouping_sets,
    1453            cube_sql,
    1454            rollup_sql,
    1455            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    1456            sep=self.GROUPINGS_SEP,
    1457        )
    1458
    1459        if expression.args.get("expressions") and groupings:
    1460            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    1461
    1462        return f"{group_by}{groupings}"

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

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

def connect_sql(self, expression: sqlglot.expressions.Connect) -> str: View Source

    1468    def connect_sql(self, expression: exp.Connect) -> str:
    1469        start = self.sql(expression, "start")
    1470        start = self.seg(f"START WITH {start}") if start else ""
    1471        connect = self.sql(expression, "connect")
    1472        connect = self.seg(f"CONNECT BY {connect}")
    1473        return start + connect

def prior_sql(self, expression: sqlglot.expressions.Prior) -> str: View Source

    1475    def prior_sql(self, expression: exp.Prior) -> str:
    1476        return f"PRIOR {self.sql(expression, 'this')}"

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

    1478    def join_sql(self, expression: exp.Join) -> str:
    1479        op_sql = " ".join(
    1480            op
    1481            for op in (
    1482                expression.method,
    1483                "GLOBAL" if expression.args.get("global") else None,
    1484                expression.side,
    1485                expression.kind,
    1486                expression.hint if self.JOIN_HINTS else None,
    1487            )
    1488            if op
    1489        )
    1490        on_sql = self.sql(expression, "on")
    1491        using = expression.args.get("using")
    1492
    1493        if not on_sql and using:
    1494            on_sql = csv(*(self.sql(column) for column in using))
    1495
    1496        this_sql = self.sql(expression, "this")
    1497
    1498        if on_sql:
    1499            on_sql = self.indent(on_sql, skip_first=True)
    1500            space = self.seg(" " * self.pad) if self.pretty else " "
    1501            if using:
    1502                on_sql = f"{space}USING ({on_sql})"
    1503            else:
    1504                on_sql = f"{space}ON {on_sql}"
    1505        elif not op_sql:
    1506            return f", {this_sql}"
    1507
    1508        op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    1509        return f"{self.seg(op_sql)} {this_sql}{on_sql}"

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

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

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

    1516    def lateral_sql(self, expression: exp.Lateral) -> str:
    1517        this = self.sql(expression, "this")
    1518
    1519        if isinstance(expression.this, exp.Subquery):
    1520            return f"LATERAL {this}"
    1521
    1522        if expression.args.get("view"):
    1523            alias = expression.args["alias"]
    1524            columns = self.expressions(alias, key="columns", flat=True)
    1525            table = f" {alias.name}" if alias.name else ""
    1526            columns = f" AS {columns}" if columns else ""
    1527            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    1528            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    1529
    1530        alias = self.sql(expression, "alias")
    1531        alias = f" AS {alias}" if alias else ""
    1532        return f"LATERAL {this}{alias}"

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

    1534    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    1535        this = self.sql(expression, "this")
    1536        args = ", ".join(
    1537            sql
    1538            for sql in (
    1539                self.sql(expression, "offset"),
    1540                self.sql(expression, "expression"),
    1541            )
    1542            if sql
    1543        )
    1544        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args}"

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

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

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

    1550    def setitem_sql(self, expression: exp.SetItem) -> str:
    1551        kind = self.sql(expression, "kind")
    1552        kind = f"{kind} " if kind else ""
    1553        this = self.sql(expression, "this")
    1554        expressions = self.expressions(expression)
    1555        collate = self.sql(expression, "collate")
    1556        collate = f" COLLATE {collate}" if collate else ""
    1557        global_ = "GLOBAL " if expression.args.get("global") else ""
    1558        return f"{global_}{kind}{this}{expressions}{collate}"

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

    1560    def set_sql(self, expression: exp.Set) -> str:
    1561        expressions = (
    1562            f" {self.expressions(expression, flat=True)}" if expression.expressions else ""
    1563        )
    1564        tag = " TAG" if expression.args.get("tag") else ""
    1565        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"

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

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

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

    1570    def lock_sql(self, expression: exp.Lock) -> str:
    1571        if not self.LOCKING_READS_SUPPORTED:
    1572            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    1573            return ""
    1574
    1575        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    1576        expressions = self.expressions(expression, flat=True)
    1577        expressions = f" OF {expressions}" if expressions else ""
    1578        wait = expression.args.get("wait")
    1579
    1580        if wait is not None:
    1581            if isinstance(wait, exp.Literal):
    1582                wait = f" WAIT {self.sql(wait)}"
    1583            else:
    1584                wait = " NOWAIT" if wait else " SKIP LOCKED"
    1585
    1586        return f"{lock_type}{expressions}{wait or ''}"

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

    1588    def literal_sql(self, expression: exp.Literal) -> str:
    1589        text = expression.this or ""
    1590        if expression.is_string:
    1591            text = f"{self.QUOTE_START}{self.escape_str(text)}{self.QUOTE_END}"
    1592        return text

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

    1594    def escape_str(self, text: str) -> str:
    1595        text = text.replace(self.QUOTE_END, self._escaped_quote_end)
    1596        if self.ESCAPE_LINE_BREAK:
    1597            text = text.replace("\n", "\\n")
    1598        elif self.pretty:
    1599            text = text.replace("\n", self.SENTINEL_LINE_BREAK)
    1600        return text

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

    1602    def loaddata_sql(self, expression: exp.LoadData) -> str:
    1603        local = " LOCAL" if expression.args.get("local") else ""
    1604        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    1605        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    1606        this = f" INTO TABLE {self.sql(expression, 'this')}"
    1607        partition = self.sql(expression, "partition")
    1608        partition = f" {partition}" if partition else ""
    1609        input_format = self.sql(expression, "input_format")
    1610        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    1611        serde = self.sql(expression, "serde")
    1612        serde = f" SERDE {serde}" if serde else ""
    1613        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"

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

    1615    def null_sql(self, *_) -> str:
    1616        return "NULL"

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

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

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

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

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

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

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

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

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

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

    1635    def ordered_sql(self, expression: exp.Ordered) -> str:
    1636        desc = expression.args.get("desc")
    1637        asc = not desc
    1638
    1639        nulls_first = expression.args.get("nulls_first")
    1640        nulls_last = not nulls_first
    1641        nulls_are_large = self.NULL_ORDERING == "nulls_are_large"
    1642        nulls_are_small = self.NULL_ORDERING == "nulls_are_small"
    1643        nulls_are_last = self.NULL_ORDERING == "nulls_are_last"
    1644
    1645        sort_order = " DESC" if desc else ""
    1646        nulls_sort_change = ""
    1647        if nulls_first and (
    1648            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
    1649        ):
    1650            nulls_sort_change = " NULLS FIRST"
    1651        elif (
    1652            nulls_last
    1653            and ((asc and nulls_are_small) or (desc and nulls_are_large))
    1654            and not nulls_are_last
    1655        ):
    1656            nulls_sort_change = " NULLS LAST"
    1657
    1658        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
    1659            self.unsupported(
    1660                "Sorting in an ORDER BY on NULLS FIRST/NULLS LAST is not supported by this dialect"
    1661            )
    1662            nulls_sort_change = ""
    1663
    1664        return f"{self.sql(expression, 'this')}{sort_order}{nulls_sort_change}"

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

    1666    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    1667        partition = self.partition_by_sql(expression)
    1668        order = self.sql(expression, "order")
    1669        measures = self.expressions(expression, key="measures")
    1670        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    1671        rows = self.sql(expression, "rows")
    1672        rows = self.seg(rows) if rows else ""
    1673        after = self.sql(expression, "after")
    1674        after = self.seg(after) if after else ""
    1675        pattern = self.sql(expression, "pattern")
    1676        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    1677        definition_sqls = [
    1678            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    1679            for definition in expression.args.get("define", [])
    1680        ]
    1681        definitions = self.expressions(sqls=definition_sqls)
    1682        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    1683        body = "".join(
    1684            (
    1685                partition,
    1686                order,
    1687                measures,
    1688                rows,
    1689                after,
    1690                pattern,
    1691                define,
    1692            )
    1693        )
    1694        alias = self.sql(expression, "alias")
    1695        alias = f" {alias}" if alias else ""
    1696        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"

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

    1698    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    1699        limit: t.Optional[exp.Fetch | exp.Limit] = expression.args.get("limit")
    1700
    1701        # If the limit is generated as TOP, we need to ensure it's not generated twice
    1702        with_offset_limit_modifiers = not isinstance(limit, exp.Limit) or not self.LIMIT_IS_TOP
    1703
    1704        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    1705            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
    1706        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    1707            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
    1708
    1709        fetch = isinstance(limit, exp.Fetch)
    1710
    1711        offset_limit_modifiers = (
    1712            self.offset_limit_modifiers(expression, fetch, limit)
    1713            if with_offset_limit_modifiers
    1714            else []
    1715        )
    1716
    1717        return csv(
    1718            *sqls,
    1719            *[self.sql(join) for join in expression.args.get("joins") or []],
    1720            self.sql(expression, "connect"),
    1721            self.sql(expression, "match"),
    1722            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    1723            self.sql(expression, "where"),
    1724            self.sql(expression, "group"),
    1725            self.sql(expression, "having"),
    1726            *self.after_having_modifiers(expression),
    1727            self.sql(expression, "order"),
    1728            *offset_limit_modifiers,
    1729            *self.after_limit_modifiers(expression),
    1730            sep="",
    1731        )

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

    1733    def offset_limit_modifiers(
    1734        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    1735    ) -> t.List[str]:
    1736        return [
    1737            self.sql(expression, "offset") if fetch else self.sql(limit),
    1738            self.sql(limit) if fetch else self.sql(expression, "offset"),
    1739        ]

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

    1741    def after_having_modifiers(self, expression: exp.Expression) -> t.List[str]:
    1742        return [
    1743            self.sql(expression, "qualify"),
    1744            self.seg("WINDOW ") + self.expressions(expression, key="windows", flat=True)
    1745            if expression.args.get("windows")
    1746            else "",
    1747            self.sql(expression, "distribute"),
    1748            self.sql(expression, "sort"),
    1749            self.sql(expression, "cluster"),
    1750        ]

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

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

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

    1757    def select_sql(self, expression: exp.Select) -> str:
    1758        hint = self.sql(expression, "hint")
    1759        distinct = self.sql(expression, "distinct")
    1760        distinct = f" {distinct}" if distinct else ""
    1761        kind = self.sql(expression, "kind").upper()
    1762        limit = expression.args.get("limit")
    1763        top = (
    1764            self.limit_sql(limit, top=True)
    1765            if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP
    1766            else ""
    1767        )
    1768
    1769        expressions = self.expressions(expression)
    1770
    1771        if kind:
    1772            if kind in self.SELECT_KINDS:
    1773                kind = f" AS {kind}"
    1774            else:
    1775                if kind == "STRUCT":
    1776                    expressions = self.expressions(
    1777                        sqls=[
    1778                            self.sql(
    1779                                exp.Struct(
    1780                                    expressions=[
    1781                                        exp.column(e.output_name).eq(
    1782                                            e.this if isinstance(e, exp.Alias) else e
    1783                                        )
    1784                                        for e in expression.expressions
    1785                                    ]
    1786                                )
    1787                            )
    1788                        ]
    1789                    )
    1790                kind = ""
    1791
    1792        expressions = f"{self.sep()}{expressions}" if expressions else expressions
    1793        sql = self.query_modifiers(
    1794            expression,
    1795            f"SELECT{top}{hint}{distinct}{kind}{expressions}",
    1796            self.sql(expression, "into", comment=False),
    1797            self.sql(expression, "from", comment=False),
    1798        )
    1799        return self.prepend_ctes(expression, sql)

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

    1801    def schema_sql(self, expression: exp.Schema) -> str:
    1802        this = self.sql(expression, "this")
    1803        this = f"{this} " if this else ""
    1804        sql = self.schema_columns_sql(expression)
    1805        return f"{this}{sql}"

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

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

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

    1810    def star_sql(self, expression: exp.Star) -> str:
    1811        except_ = self.expressions(expression, key="except", flat=True)
    1812        except_ = f"{self.seg(self.STAR_MAPPING['except'])} ({except_})" if except_ else ""
    1813        replace = self.expressions(expression, key="replace", flat=True)
    1814        replace = f"{self.seg(self.STAR_MAPPING['replace'])} ({replace})" if replace else ""
    1815        return f"*{except_}{replace}"

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

    1817    def parameter_sql(self, expression: exp.Parameter) -> str:
    1818        this = self.sql(expression, "this")
    1819        this = f"{{{this}}}" if expression.args.get("wrapped") else f"{this}"
    1820        return f"{self.PARAMETER_TOKEN}{this}"

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

    1822    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    1823        this = self.sql(expression, "this")
    1824        kind = expression.text("kind")
    1825        if kind:
    1826            kind = f"{kind}."
    1827        return f"@@{kind}{this}"

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

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

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

    1832    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    1833        alias = self.sql(expression, "alias")
    1834        alias = f"{sep}{alias}" if alias else ""
    1835
    1836        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    1837        pivots = f" {pivots}" if pivots else ""
    1838
    1839        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    1840        return self.prepend_ctes(expression, sql)

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

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

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

    1846    def union_sql(self, expression: exp.Union) -> str:
    1847        return self.prepend_ctes(
    1848            expression,
    1849            self.set_operation(expression, self.union_op(expression)),
    1850        )

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

    1852    def union_op(self, expression: exp.Union) -> str:
    1853        kind = " DISTINCT" if self.EXPLICIT_UNION else ""
    1854        kind = kind if expression.args.get("distinct") else " ALL"
    1855        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1856        return f"UNION{kind}{by_name}"

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

    1858    def unnest_sql(self, expression: exp.Unnest) -> str:
    1859        args = self.expressions(expression, flat=True)
    1860        alias = expression.args.get("alias")
    1861        if alias and self.UNNEST_COLUMN_ONLY:
    1862            columns = alias.columns
    1863            alias = self.sql(columns[0]) if columns else ""
    1864        else:
    1865            alias = self.sql(expression, "alias")
    1866        alias = f" AS {alias}" if alias else alias
    1867        ordinality = " WITH ORDINALITY" if expression.args.get("ordinality") else ""
    1868        offset = expression.args.get("offset")
    1869        offset = f" WITH OFFSET AS {self.sql(offset)}" if offset else ""
    1870        return f"UNNEST({args}){ordinality}{alias}{offset}"

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

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

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

    1876    def window_sql(self, expression: exp.Window) -> str:
    1877        this = self.sql(expression, "this")
    1878        partition = self.partition_by_sql(expression)
    1879        order = expression.args.get("order")
    1880        order = self.order_sql(order, flat=True) if order else ""
    1881        spec = self.sql(expression, "spec")
    1882        alias = self.sql(expression, "alias")
    1883        over = self.sql(expression, "over") or "OVER"
    1884
    1885        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    1886
    1887        first = expression.args.get("first")
    1888        if first is None:
    1889            first = ""
    1890        else:
    1891            first = "FIRST" if first else "LAST"
    1892
    1893        if not partition and not order and not spec and alias:
    1894            return f"{this} {alias}"
    1895
    1896        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
    1897        return f"{this} ({args})"

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

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

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

    1903    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    1904        kind = self.sql(expression, "kind")
    1905        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    1906        end = (
    1907            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    1908            or "CURRENT ROW"
    1909        )
    1910        return f"{kind} BETWEEN {start} AND {end}"

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

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

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

    1917    def between_sql(self, expression: exp.Between) -> str:
    1918        this = self.sql(expression, "this")
    1919        low = self.sql(expression, "low")
    1920        high = self.sql(expression, "high")
    1921        return f"{this} BETWEEN {low} AND {high}"

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

    1923    def bracket_sql(self, expression: exp.Bracket) -> str:
    1924        expressions = apply_index_offset(expression.this, expression.expressions, self.INDEX_OFFSET)
    1925        expressions_sql = ", ".join(self.sql(e) for e in expressions)
    1926
    1927        return f"{self.sql(expression, 'this')}[{expressions_sql}]"

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

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

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

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

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

    1935    def any_sql(self, expression: exp.Any) -> str:
    1936        this = self.sql(expression, "this")
    1937        if isinstance(expression.this, exp.Subqueryable):
    1938            this = self.wrap(this)
    1939        return f"ANY {this}"

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

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

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

    1944    def case_sql(self, expression: exp.Case) -> str:
    1945        this = self.sql(expression, "this")
    1946        statements = [f"CASE {this}" if this else "CASE"]
    1947
    1948        for e in expression.args["ifs"]:
    1949            statements.append(f"WHEN {self.sql(e, 'this')}")
    1950            statements.append(f"THEN {self.sql(e, 'true')}")
    1951
    1952        default = self.sql(expression, "default")
    1953
    1954        if default:
    1955            statements.append(f"ELSE {default}")
    1956
    1957        statements.append("END")
    1958
    1959        if self.pretty and self.text_width(statements) > self.max_text_width:
    1960            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    1961
    1962        return " ".join(statements)

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

    1964    def constraint_sql(self, expression: exp.Constraint) -> str:
    1965        this = self.sql(expression, "this")
    1966        expressions = self.expressions(expression, flat=True)
    1967        return f"CONSTRAINT {this} {expressions}"

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

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

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

    1974    def extract_sql(self, expression: exp.Extract) -> str:
    1975        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
    1976        expression_sql = self.sql(expression, "expression")
    1977        return f"EXTRACT({this} FROM {expression_sql})"

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

    1979    def trim_sql(self, expression: exp.Trim) -> str:
    1980        trim_type = self.sql(expression, "position")
    1981
    1982        if trim_type == "LEADING":
    1983            return self.func("LTRIM", expression.this)
    1984        elif trim_type == "TRAILING":
    1985            return self.func("RTRIM", expression.this)
    1986        else:
    1987            return self.func("TRIM", expression.this, expression.expression)

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

    1989    def safeconcat_sql(self, expression: exp.SafeConcat) -> str:
    1990        expressions = expression.expressions
    1991        if self.STRICT_STRING_CONCAT:
    1992            expressions = (exp.cast(e, "text") for e in expressions)
    1993        return self.func("CONCAT", *expressions)

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

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

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

    1999    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    2000        expressions = self.expressions(expression, flat=True)
    2001        reference = self.sql(expression, "reference")
    2002        reference = f" {reference}" if reference else ""
    2003        delete = self.sql(expression, "delete")
    2004        delete = f" ON DELETE {delete}" if delete else ""
    2005        update = self.sql(expression, "update")
    2006        update = f" ON UPDATE {update}" if update else ""
    2007        return f"FOREIGN KEY ({expressions}){reference}{delete}{update}"

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

    2009    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    2010        expressions = self.expressions(expression, flat=True)
    2011        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2012        options = f" {options}" if options else ""
    2013        return f"PRIMARY KEY ({expressions}){options}"

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

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

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

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

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

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

def formatjson_sql(self, expression: sqlglot.expressions.FormatJson) -> str: View Source

    2027    def formatjson_sql(self, expression: exp.FormatJson) -> str:
    2028        return f"{self.sql(expression, 'this')} FORMAT JSON"

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

    2030    def jsonobject_sql(self, expression: exp.JSONObject) -> str:
    2031        null_handling = expression.args.get("null_handling")
    2032        null_handling = f" {null_handling}" if null_handling else ""
    2033        unique_keys = expression.args.get("unique_keys")
    2034        if unique_keys is not None:
    2035            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    2036        else:
    2037            unique_keys = ""
    2038        return_type = self.sql(expression, "return_type")
    2039        return_type = f" RETURNING {return_type}" if return_type else ""
    2040        encoding = self.sql(expression, "encoding")
    2041        encoding = f" ENCODING {encoding}" if encoding else ""
    2042        return self.func(
    2043            "JSON_OBJECT",
    2044            *expression.expressions,
    2045            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
    2046        )

def jsonarray_sql(self, expression: sqlglot.expressions.JSONArray) -> str: View Source

    2048    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
    2049        null_handling = expression.args.get("null_handling")
    2050        null_handling = f" {null_handling}" if null_handling else ""
    2051        return_type = self.sql(expression, "return_type")
    2052        return_type = f" RETURNING {return_type}" if return_type else ""
    2053        strict = " STRICT" if expression.args.get("strict") else ""
    2054        return self.func(
    2055            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
    2056        )

def jsonarrayagg_sql(self, expression: sqlglot.expressions.JSONArrayAgg) -> str: View Source

    2058    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
    2059        this = self.sql(expression, "this")
    2060        order = self.sql(expression, "order")
    2061        null_handling = expression.args.get("null_handling")
    2062        null_handling = f" {null_handling}" if null_handling else ""
    2063        return_type = self.sql(expression, "return_type")
    2064        return_type = f" RETURNING {return_type}" if return_type else ""
    2065        strict = " STRICT" if expression.args.get("strict") else ""
    2066        return self.func(
    2067            "JSON_ARRAYAGG",
    2068            this,
    2069            suffix=f"{order}{null_handling}{return_type}{strict})",
    2070        )

def jsoncolumndef_sql(self, expression: sqlglot.expressions.JSONColumnDef) -> str: View Source

    2072    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
    2073        this = self.sql(expression, "this")
    2074        kind = self.sql(expression, "kind")
    2075        kind = f" {kind}" if kind else ""
    2076        path = self.sql(expression, "path")
    2077        path = f" PATH {path}" if path else ""
    2078        return f"{this}{kind}{path}"

def jsontable_sql(self, expression: sqlglot.expressions.JSONTable) -> str: View Source

    2080    def jsontable_sql(self, expression: exp.JSONTable) -> str:
    2081        this = self.sql(expression, "this")
    2082        path = self.sql(expression, "path")
    2083        path = f", {path}" if path else ""
    2084        error_handling = expression.args.get("error_handling")
    2085        error_handling = f" {error_handling}" if error_handling else ""
    2086        empty_handling = expression.args.get("empty_handling")
    2087        empty_handling = f" {empty_handling}" if empty_handling else ""
    2088        columns = f" COLUMNS ({self.expressions(expression, skip_first=True)})"
    2089        return self.func(
    2090            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling}{columns})"
    2091        )

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

    2093    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    2094        this = self.sql(expression, "this")
    2095        kind = self.sql(expression, "kind")
    2096        path = self.sql(expression, "path")
    2097        path = f" {path}" if path else ""
    2098        as_json = " AS JSON" if expression.args.get("as_json") else ""
    2099        return f"{this} {kind}{path}{as_json}"

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

    2101    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    2102        this = self.sql(expression, "this")
    2103        path = self.sql(expression, "path")
    2104        path = f", {path}" if path else ""
    2105        expressions = self.expressions(expression)
    2106        with_ = (
    2107            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    2108            if expressions
    2109            else ""
    2110        )
    2111        return f"OPENJSON({this}{path}){with_}"

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

    2113    def in_sql(self, expression: exp.In) -> str:
    2114        query = expression.args.get("query")
    2115        unnest = expression.args.get("unnest")
    2116        field = expression.args.get("field")
    2117        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    2118
    2119        if query:
    2120            in_sql = self.wrap(query)
    2121        elif unnest:
    2122            in_sql = self.in_unnest_op(unnest)
    2123        elif field:
    2124            in_sql = self.sql(field)
    2125        else:
    2126            in_sql = f"({self.expressions(expression, flat=True)})"
    2127
    2128        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"

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

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

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

    2133    def interval_sql(self, expression: exp.Interval) -> str:
    2134        unit = self.sql(expression, "unit")
    2135        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    2136            unit = self.TIME_PART_SINGULARS.get(unit.lower(), unit)
    2137        unit = f" {unit}" if unit else ""
    2138
    2139        if self.SINGLE_STRING_INTERVAL:
    2140            this = expression.this.name if expression.this else ""
    2141            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    2142
    2143        this = self.sql(expression, "this")
    2144        if this:
    2145            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    2146            this = f" {this}" if unwrapped else f" ({this})"
    2147
    2148        return f"INTERVAL{this}{unit}"

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

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

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

    2153    def reference_sql(self, expression: exp.Reference) -> str:
    2154        this = self.sql(expression, "this")
    2155        expressions = self.expressions(expression, flat=True)
    2156        expressions = f"({expressions})" if expressions else ""
    2157        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2158        options = f" {options}" if options else ""
    2159        return f"REFERENCES {this}{expressions}{options}"

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

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

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

    2164    def paren_sql(self, expression: exp.Paren) -> str:
    2165        if isinstance(expression.unnest(), exp.Select):
    2166            sql = self.wrap(expression)
    2167        else:
    2168            sql = self.seg(self.indent(self.sql(expression, "this")), sep="")
    2169            sql = f"({sql}{self.seg(')', sep='')}"
    2170
    2171        return self.prepend_ctes(expression, sql)

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

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

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

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

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

    2182    def alias_sql(self, expression: exp.Alias) -> str:
    2183        alias = self.sql(expression, "alias")
    2184        alias = f" AS {alias}" if alias else ""
    2185        return f"{self.sql(expression, 'this')}{alias}"

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

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

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

    2190    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    2191        this = self.sql(expression, "this")
    2192        zone = self.sql(expression, "zone")
    2193        return f"{this} AT TIME ZONE {zone}"

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

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

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

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

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

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

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

    2204    def connector_sql(self, expression: exp.Connector, op: str) -> str:
    2205        if not self.pretty:
    2206            return self.binary(expression, op)
    2207
    2208        sqls = tuple(
    2209            self.maybe_comment(self.sql(e), e, e.parent.comments or []) if i != 1 else self.sql(e)
    2210            for i, e in enumerate(expression.flatten(unnest=False))
    2211        )
    2212
    2213        sep = "\n" if self.text_width(sqls) > self.max_text_width else " "
    2214        return f"{sep}{op} ".join(sqls)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    2249    def comment_sql(self, expression: exp.Comment) -> str:
    2250        this = self.sql(expression, "this")
    2251        kind = expression.args["kind"]
    2252        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    2253        expression_sql = self.sql(expression, "expression")
    2254        return f"COMMENT{exists_sql}ON {kind} {this} IS {expression_sql}"

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

    2256    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    2257        this = self.sql(expression, "this")
    2258        delete = " DELETE" if expression.args.get("delete") else ""
    2259        recompress = self.sql(expression, "recompress")
    2260        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    2261        to_disk = self.sql(expression, "to_disk")
    2262        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    2263        to_volume = self.sql(expression, "to_volume")
    2264        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    2265        return f"{this}{delete}{recompress}{to_disk}{to_volume}"

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

    2267    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    2268        where = self.sql(expression, "where")
    2269        group = self.sql(expression, "group")
    2270        aggregates = self.expressions(expression, key="aggregates")
    2271        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    2272
    2273        if not (where or group or aggregates) and len(expression.expressions) == 1:
    2274            return f"TTL {self.expressions(expression, flat=True)}"
    2275
    2276        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"

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

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

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

    2281    def commit_sql(self, expression: exp.Commit) -> str:
    2282        chain = expression.args.get("chain")
    2283        if chain is not None:
    2284            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    2285
    2286        return f"COMMIT{chain or ''}"

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

    2288    def rollback_sql(self, expression: exp.Rollback) -> str:
    2289        savepoint = expression.args.get("savepoint")
    2290        savepoint = f" TO {savepoint}" if savepoint else ""
    2291        return f"ROLLBACK{savepoint}"

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

    2293    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    2294        this = self.sql(expression, "this")
    2295
    2296        dtype = self.sql(expression, "dtype")
    2297        if dtype:
    2298            collate = self.sql(expression, "collate")
    2299            collate = f" COLLATE {collate}" if collate else ""
    2300            using = self.sql(expression, "using")
    2301            using = f" USING {using}" if using else ""
    2302            return f"ALTER COLUMN {this} TYPE {dtype}{collate}{using}"
    2303
    2304        default = self.sql(expression, "default")
    2305        if default:
    2306            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    2307
    2308        if not expression.args.get("drop"):
    2309            self.unsupported("Unsupported ALTER COLUMN syntax")
    2310
    2311        return f"ALTER COLUMN {this} DROP DEFAULT"

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

    2313    def renametable_sql(self, expression: exp.RenameTable) -> str:
    2314        if not self.RENAME_TABLE_WITH_DB:
    2315            # Remove db from tables
    2316            expression = expression.transform(
    2317                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    2318            )
    2319        this = self.sql(expression, "this")
    2320        return f"RENAME TO {this}"

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

    2322    def altertable_sql(self, expression: exp.AlterTable) -> str:
    2323        actions = expression.args["actions"]
    2324
    2325        if isinstance(actions[0], exp.ColumnDef):
    2326            if self.ALTER_TABLE_ADD_COLUMN_KEYWORD:
    2327                actions = self.expressions(
    2328                    expression,
    2329                    key="actions",
    2330                    prefix="ADD COLUMN ",
    2331                )
    2332            else:
    2333                actions = f"ADD {self.expressions(expression, key='actions')}"
    2334        elif isinstance(actions[0], exp.Schema):
    2335            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    2336        elif isinstance(actions[0], exp.Delete):
    2337            actions = self.expressions(expression, key="actions", flat=True)
    2338        else:
    2339            actions = self.expressions(expression, key="actions")
    2340
    2341        exists = " IF EXISTS" if expression.args.get("exists") else ""
    2342        only = " ONLY" if expression.args.get("only") else ""
    2343        return f"ALTER TABLE{exists}{only} {self.sql(expression, 'this')} {actions}"

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

    2345    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    2346        expressions = self.expressions(expression)
    2347        exists = " IF EXISTS " if expression.args.get("exists") else " "
    2348        return f"DROP{exists}{expressions}"

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

    2350    def addconstraint_sql(self, expression: exp.AddConstraint) -> str:
    2351        this = self.sql(expression, "this")
    2352        expression_ = self.sql(expression, "expression")
    2353        add_constraint = f"ADD CONSTRAINT {this}" if this else "ADD"
    2354
    2355        enforced = expression.args.get("enforced")
    2356        if enforced is not None:
    2357            return f"{add_constraint} CHECK ({expression_}){' ENFORCED' if enforced else ''}"
    2358
    2359        return f"{add_constraint} {expression_}"

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

    2361    def distinct_sql(self, expression: exp.Distinct) -> str:
    2362        this = self.expressions(expression, flat=True)
    2363        this = f" {this}" if this else ""
    2364
    2365        on = self.sql(expression, "on")
    2366        on = f" ON {on}" if on else ""
    2367        return f"DISTINCT{this}{on}"

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

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

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

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

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

    2375    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    2376        return self.sql(
    2377            exp.Cast(
    2378                this=exp.Div(this=expression.this.copy(), expression=expression.expression.copy()),
    2379                to=exp.DataType(this=exp.DataType.Type.INT),
    2380            )
    2381        )

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

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

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

    2386    def safedpipe_sql(self, expression: exp.SafeDPipe) -> str:
    2387        if self.STRICT_STRING_CONCAT:
    2388            return self.func("CONCAT", *(exp.cast(e, "text") for e in expression.flatten()))
    2389        return self.dpipe_sql(expression)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    2424    def is_sql(self, expression: exp.Is) -> str:
    2425        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    2426            return self.sql(
    2427                expression.this if expression.expression.this else exp.not_(expression.this)
    2428            )
    2429        return self.binary(expression, "IS")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    2473    def use_sql(self, expression: exp.Use) -> str:
    2474        kind = self.sql(expression, "kind")
    2475        kind = f" {kind}" if kind else ""
    2476        this = self.sql(expression, "this")
    2477        this = f" {this}" if this else ""
    2478        return f"USE{kind}{this}"

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

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

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

    2484    def function_fallback_sql(self, expression: exp.Func) -> str:
    2485        args = []
    2486
    2487        for key in expression.arg_types:
    2488            arg_value = expression.args.get(key)
    2489
    2490            if isinstance(arg_value, list):
    2491                for value in arg_value:
    2492                    args.append(value)
    2493            elif arg_value is not None:
    2494                args.append(arg_value)
    2495
    2496        if self.normalize_functions:
    2497            name = expression.sql_name()
    2498        else:
    2499            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
    2500
    2501        return self.func(name, *args)

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

    2503    def func(
    2504        self,
    2505        name: str,
    2506        *args: t.Optional[exp.Expression | str],
    2507        prefix: str = "(",
    2508        suffix: str = ")",
    2509    ) -> str:
    2510        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

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

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

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

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

    2521    def format_time(self, expression: exp.Expression) -> t.Optional[str]:
    2522        return format_time(
    2523            self.sql(expression, "format"), self.INVERSE_TIME_MAPPING, self.INVERSE_TIME_TRIE
    2524        )

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

    2526    def expressions(
    2527        self,
    2528        expression: t.Optional[exp.Expression] = None,
    2529        key: t.Optional[str] = None,
    2530        sqls: t.Optional[t.List[str]] = None,
    2531        flat: bool = False,
    2532        indent: bool = True,
    2533        skip_first: bool = False,
    2534        sep: str = ", ",
    2535        prefix: str = "",
    2536    ) -> str:
    2537        expressions = expression.args.get(key or "expressions") if expression else sqls
    2538
    2539        if not expressions:
    2540            return ""
    2541
    2542        if flat:
    2543            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
    2544
    2545        num_sqls = len(expressions)
    2546
    2547        # These are calculated once in case we have the leading_comma / pretty option set, correspondingly
    2548        pad = " " * self.pad
    2549        stripped_sep = sep.strip()
    2550
    2551        result_sqls = []
    2552        for i, e in enumerate(expressions):
    2553            sql = self.sql(e, comment=False)
    2554            if not sql:
    2555                continue
    2556
    2557            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    2558
    2559            if self.pretty:
    2560                if self.leading_comma:
    2561                    result_sqls.append(f"{sep if i > 0 else pad}{prefix}{sql}{comments}")
    2562                else:
    2563                    result_sqls.append(
    2564                        f"{prefix}{sql}{stripped_sep if i + 1 < num_sqls else ''}{comments}"
    2565                    )
    2566            else:
    2567                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    2568
    2569        result_sql = "\n".join(result_sqls) if self.pretty else "".join(result_sqls)
    2570        return self.indent(result_sql, skip_first=skip_first) if indent else result_sql

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

    2572    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    2573        flat = flat or isinstance(expression.parent, exp.Properties)
    2574        expressions_sql = self.expressions(expression, flat=flat)
    2575        if flat:
    2576            return f"{op} {expressions_sql}"
    2577        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"

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

    2579    def naked_property(self, expression: exp.Property) -> str:
    2580        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    2581        if not property_name:
    2582            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    2583        return f"{property_name} {self.sql(expression, 'this')}"

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

    2585    def set_operation(self, expression: exp.Expression, op: str) -> str:
    2586        this = self.sql(expression, "this")
    2587        op = self.seg(op)
    2588        return self.query_modifiers(
    2589            expression, f"{this}{op}{self.sep()}{self.sql(expression, 'expression')}"
    2590        )

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

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

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

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

    2598    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    2599        this = self.sql(expression, "this")
    2600        expressions = self.no_identify(self.expressions, expression)
    2601        expressions = (
    2602            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    2603        )
    2604        return f"{this}{expressions}"

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

    2606    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    2607        this = self.sql(expression, "this")
    2608        expressions = self.expressions(expression, flat=True)
    2609        return f"{this}({expressions})"

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

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

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

    2614    def when_sql(self, expression: exp.When) -> str:
    2615        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    2616        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    2617        condition = self.sql(expression, "condition")
    2618        condition = f" AND {condition}" if condition else ""
    2619
    2620        then_expression = expression.args.get("then")
    2621        if isinstance(then_expression, exp.Insert):
    2622            then = f"INSERT {self.sql(then_expression, 'this')}"
    2623            if "expression" in then_expression.args:
    2624                then += f" VALUES {self.sql(then_expression, 'expression')}"
    2625        elif isinstance(then_expression, exp.Update):
    2626            if isinstance(then_expression.args.get("expressions"), exp.Star):
    2627                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    2628            else:
    2629                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    2630        else:
    2631            then = self.sql(then_expression)
    2632        return f"WHEN {matched}{source}{condition} THEN {then}"

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

    2634    def merge_sql(self, expression: exp.Merge) -> str:
    2635        table = expression.this
    2636        table_alias = ""
    2637
    2638        hints = table.args.get("hints")
    2639        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
    2640            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
    2641            table = table.copy()
    2642            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
    2643
    2644        this = self.sql(table)
    2645        using = f"USING {self.sql(expression, 'using')}"
    2646        on = f"ON {self.sql(expression, 'on')}"
    2647        expressions = self.expressions(expression, sep=" ")
    2648
    2649        return f"MERGE INTO {this}{table_alias} {using} {on} {expressions}"

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

    2651    def tochar_sql(self, expression: exp.ToChar) -> str:
    2652        if expression.args.get("format"):
    2653            self.unsupported("Format argument unsupported for TO_CHAR/TO_VARCHAR function")
    2654
    2655        return self.sql(exp.cast(expression.this, "text"))

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

    2657    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    2658        this = self.sql(expression, "this")
    2659        kind = self.sql(expression, "kind")
    2660        settings_sql = self.expressions(expression, key="settings", sep=" ")
    2661        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    2662        return f"{this}({kind}{args})"

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

    2664    def dictrange_sql(self, expression: exp.DictRange) -> str:
    2665        this = self.sql(expression, "this")
    2666        max = self.sql(expression, "max")
    2667        min = self.sql(expression, "min")
    2668        return f"{this}(MIN {min} MAX {max})"

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

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

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

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

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

    2676    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    2677        expressions = self.expressions(expression, key="expressions", flat=True)
    2678        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    2679        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    2680        buckets = self.sql(expression, "buckets")
    2681        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"

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

    2683    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    2684        this = self.sql(expression, "this")
    2685        having = self.sql(expression, "having")
    2686
    2687        if having:
    2688            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    2689
    2690        return self.func("ANY_VALUE", this)

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

    2692    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
    2693        transform = self.func("TRANSFORM", *expression.expressions)
    2694        row_format_before = self.sql(expression, "row_format_before")
    2695        row_format_before = f" {row_format_before}" if row_format_before else ""
    2696        record_writer = self.sql(expression, "record_writer")
    2697        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
    2698        using = f" USING {self.sql(expression, 'command_script')}"
    2699        schema = self.sql(expression, "schema")
    2700        schema = f" AS {schema}" if schema else ""
    2701        row_format_after = self.sql(expression, "row_format_after")
    2702        row_format_after = f" {row_format_after}" if row_format_after else ""
    2703        record_reader = self.sql(expression, "record_reader")
    2704        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
    2705        return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}"

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

    2707    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
    2708        key_block_size = self.sql(expression, "key_block_size")
    2709        if key_block_size:
    2710            return f"KEY_BLOCK_SIZE = {key_block_size}"
    2711
    2712        using = self.sql(expression, "using")
    2713        if using:
    2714            return f"USING {using}"
    2715
    2716        parser = self.sql(expression, "parser")
    2717        if parser:
    2718            return f"WITH PARSER {parser}"
    2719
    2720        comment = self.sql(expression, "comment")
    2721        if comment:
    2722            return f"COMMENT {comment}"
    2723
    2724        visible = expression.args.get("visible")
    2725        if visible is not None:
    2726            return "VISIBLE" if visible else "INVISIBLE"
    2727
    2728        engine_attr = self.sql(expression, "engine_attr")
    2729        if engine_attr:
    2730            return f"ENGINE_ATTRIBUTE = {engine_attr}"
    2731
    2732        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
    2733        if secondary_engine_attr:
    2734            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
    2735
    2736        self.unsupported("Unsupported index constraint option.")
    2737        return ""

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

    2739    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
    2740        kind = self.sql(expression, "kind")
    2741        kind = f"{kind} INDEX" if kind else "INDEX"
    2742        this = self.sql(expression, "this")
    2743        this = f" {this}" if this else ""
    2744        type_ = self.sql(expression, "type")
    2745        type_ = f" USING {type_}" if type_ else ""
    2746        schema = self.sql(expression, "schema")
    2747        schema = f" {schema}" if schema else ""
    2748        options = self.expressions(expression, key="options", sep=" ")
    2749        options = f" {options}" if options else ""
    2750        return f"{kind}{this}{type_}{schema}{options}"

def nvl2_sql(self, expression: sqlglot.expressions.Nvl2) -> str: View Source

    2752    def nvl2_sql(self, expression: exp.Nvl2) -> str:
    2753        if self.NVL2_SUPPORTED:
    2754            return self.function_fallback_sql(expression)
    2755
    2756        case = exp.Case().when(
    2757            expression.this.is_(exp.null()).not_(copy=False),
    2758            expression.args["true"].copy(),
    2759            copy=False,
    2760        )
    2761        else_cond = expression.args.get("false")
    2762        if else_cond:
    2763            case.else_(else_cond.copy(), copy=False)
    2764
    2765        return self.sql(case)

def comprehension_sql(self, expression: sqlglot.expressions.Comprehension) -> str: View Source

    2767    def comprehension_sql(self, expression: exp.Comprehension) -> str:
    2768        this = self.sql(expression, "this")
    2769        expr = self.sql(expression, "expression")
    2770        iterator = self.sql(expression, "iterator")
    2771        condition = self.sql(expression, "condition")
    2772        condition = f" IF {condition}" if condition else ""
    2773        return f"{this} FOR {expr} IN {iterator}{condition}"

def columnprefix_sql(self, expression: sqlglot.expressions.ColumnPrefix) -> str: View Source

    2775    def columnprefix_sql(self, expression: exp.ColumnPrefix) -> str:
    2776        return f"{self.sql(expression, 'this')}({self.sql(expression, 'expression')})"

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

    2779def cached_generator(
    2780    cache: t.Optional[t.Dict[int, str]] = None
    2781) -> t.Callable[[exp.Expression], str]:
    2782    """Returns a cached generator."""
    2783    cache = {} if cache is None else cache
    2784    generator = Generator(normalize=True, identify="safe")
    2785    return lambda e: generator.generate(e, cache)

Returns a cached generator.