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        index_type = expression.args.get("index_type")
     709        index_type = f" USING {index_type}" if index_type else ""
     710        return f"UNIQUE{this}{index_type}"
     711
     712    def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
     713        return self.sql(expression, "this")
     714
     715    def create_sql(self, expression: exp.Create) -> str:
     716        kind = self.sql(expression, "kind").upper()
     717        properties = expression.args.get("properties")
     718        properties_locs = self.locate_properties(properties) if properties else defaultdict()
     719
     720        this = self.createable_sql(expression, properties_locs)
     721
     722        properties_sql = ""
     723        if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get(
     724            exp.Properties.Location.POST_WITH
     725        ):
     726            properties_sql = self.sql(
     727                exp.Properties(
     728                    expressions=[
     729                        *properties_locs[exp.Properties.Location.POST_SCHEMA],
     730                        *properties_locs[exp.Properties.Location.POST_WITH],
     731                    ]
     732                )
     733            )
     734
     735        begin = " BEGIN" if expression.args.get("begin") else ""
     736        expression_sql = self.sql(expression, "expression")
     737        if expression_sql:
     738            expression_sql = f"{begin}{self.sep()}{expression_sql}"
     739
     740            if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return):
     741                if properties_locs.get(exp.Properties.Location.POST_ALIAS):
     742                    postalias_props_sql = self.properties(
     743                        exp.Properties(
     744                            expressions=properties_locs[exp.Properties.Location.POST_ALIAS]
     745                        ),
     746                        wrapped=False,
     747                    )
     748                    expression_sql = f" AS {postalias_props_sql}{expression_sql}"
     749                else:
     750                    expression_sql = f" AS{expression_sql}"
     751
     752        postindex_props_sql = ""
     753        if properties_locs.get(exp.Properties.Location.POST_INDEX):
     754            postindex_props_sql = self.properties(
     755                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]),
     756                wrapped=False,
     757                prefix=" ",
     758            )
     759
     760        indexes = self.expressions(expression, key="indexes", indent=False, sep=" ")
     761        indexes = f" {indexes}" if indexes else ""
     762        index_sql = indexes + postindex_props_sql
     763
     764        replace = " OR REPLACE" if expression.args.get("replace") else ""
     765        unique = " UNIQUE" if expression.args.get("unique") else ""
     766
     767        postcreate_props_sql = ""
     768        if properties_locs.get(exp.Properties.Location.POST_CREATE):
     769            postcreate_props_sql = self.properties(
     770                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]),
     771                sep=" ",
     772                prefix=" ",
     773                wrapped=False,
     774            )
     775
     776        modifiers = "".join((replace, unique, postcreate_props_sql))
     777
     778        postexpression_props_sql = ""
     779        if properties_locs.get(exp.Properties.Location.POST_EXPRESSION):
     780            postexpression_props_sql = self.properties(
     781                exp.Properties(
     782                    expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION]
     783                ),
     784                sep=" ",
     785                prefix=" ",
     786                wrapped=False,
     787            )
     788
     789        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
     790        no_schema_binding = (
     791            " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else ""
     792        )
     793
     794        clone = self.sql(expression, "clone")
     795        clone = f" {clone}" if clone else ""
     796
     797        expression_sql = f"CREATE{modifiers} {kind}{exists_sql} {this}{properties_sql}{expression_sql}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}"
     798        return self.prepend_ctes(expression, expression_sql)
     799
     800    def clone_sql(self, expression: exp.Clone) -> str:
     801        this = self.sql(expression, "this")
     802        shallow = "SHALLOW " if expression.args.get("shallow") else ""
     803        this = f"{shallow}CLONE {this}"
     804        when = self.sql(expression, "when")
     805
     806        if when:
     807            kind = self.sql(expression, "kind")
     808            expr = self.sql(expression, "expression")
     809            return f"{this} {when} ({kind} => {expr})"
     810
     811        return this
     812
     813    def describe_sql(self, expression: exp.Describe) -> str:
     814        return f"DESCRIBE {self.sql(expression, 'this')}"
     815
     816    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
     817        with_ = self.sql(expression, "with")
     818        if with_:
     819            sql = f"{with_}{self.sep()}{sql}"
     820        return sql
     821
     822    def with_sql(self, expression: exp.With) -> str:
     823        sql = self.expressions(expression, flat=True)
     824        recursive = "RECURSIVE " if expression.args.get("recursive") else ""
     825
     826        return f"WITH {recursive}{sql}"
     827
     828    def cte_sql(self, expression: exp.CTE) -> str:
     829        alias = self.sql(expression, "alias")
     830        return f"{alias} AS {self.wrap(expression)}"
     831
     832    def tablealias_sql(self, expression: exp.TableAlias) -> str:
     833        alias = self.sql(expression, "this")
     834        columns = self.expressions(expression, key="columns", flat=True)
     835        columns = f"({columns})" if columns else ""
     836        return f"{alias}{columns}"
     837
     838    def bitstring_sql(self, expression: exp.BitString) -> str:
     839        this = self.sql(expression, "this")
     840        if self.BIT_START:
     841            return f"{self.BIT_START}{this}{self.BIT_END}"
     842        return f"{int(this, 2)}"
     843
     844    def hexstring_sql(self, expression: exp.HexString) -> str:
     845        this = self.sql(expression, "this")
     846        if self.HEX_START:
     847            return f"{self.HEX_START}{this}{self.HEX_END}"
     848        return f"{int(this, 16)}"
     849
     850    def bytestring_sql(self, expression: exp.ByteString) -> str:
     851        this = self.sql(expression, "this")
     852        if self.BYTE_START:
     853            return f"{self.BYTE_START}{this}{self.BYTE_END}"
     854        return this
     855
     856    def rawstring_sql(self, expression: exp.RawString) -> str:
     857        string = self.escape_str(expression.this.replace("\\", "\\\\"))
     858        return f"{self.QUOTE_START}{string}{self.QUOTE_END}"
     859
     860    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
     861        this = self.sql(expression, "this")
     862        specifier = self.sql(expression, "expression")
     863        specifier = f" {specifier}" if specifier else ""
     864        return f"{this}{specifier}"
     865
     866    def datatype_sql(self, expression: exp.DataType) -> str:
     867        type_value = expression.this
     868
     869        if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"):
     870            type_sql = self.sql(expression, "kind")
     871        else:
     872            type_sql = (
     873                self.TYPE_MAPPING.get(type_value, type_value.value)
     874                if isinstance(type_value, exp.DataType.Type)
     875                else type_value
     876            )
     877
     878        nested = ""
     879        interior = self.expressions(expression, flat=True)
     880        values = ""
     881
     882        if interior:
     883            if expression.args.get("nested"):
     884                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
     885                if expression.args.get("values") is not None:
     886                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
     887                    values = self.expressions(expression, key="values", flat=True)
     888                    values = f"{delimiters[0]}{values}{delimiters[1]}"
     889            elif type_value == exp.DataType.Type.INTERVAL:
     890                nested = f" {interior}"
     891            else:
     892                nested = f"({interior})"
     893
     894        type_sql = f"{type_sql}{nested}{values}"
     895        if self.TZ_TO_WITH_TIME_ZONE and type_value in (
     896            exp.DataType.Type.TIMETZ,
     897            exp.DataType.Type.TIMESTAMPTZ,
     898        ):
     899            type_sql = f"{type_sql} WITH TIME ZONE"
     900
     901        return type_sql
     902
     903    def directory_sql(self, expression: exp.Directory) -> str:
     904        local = "LOCAL " if expression.args.get("local") else ""
     905        row_format = self.sql(expression, "row_format")
     906        row_format = f" {row_format}" if row_format else ""
     907        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"
     908
     909    def delete_sql(self, expression: exp.Delete) -> str:
     910        this = self.sql(expression, "this")
     911        this = f" FROM {this}" if this else ""
     912        using = self.sql(expression, "using")
     913        using = f" USING {using}" if using else ""
     914        where = self.sql(expression, "where")
     915        returning = self.sql(expression, "returning")
     916        limit = self.sql(expression, "limit")
     917        tables = self.expressions(expression, key="tables")
     918        tables = f" {tables}" if tables else ""
     919        if self.RETURNING_END:
     920            expression_sql = f"{this}{using}{where}{returning}{limit}"
     921        else:
     922            expression_sql = f"{returning}{this}{using}{where}{limit}"
     923        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")
     924
     925    def drop_sql(self, expression: exp.Drop) -> str:
     926        this = self.sql(expression, "this")
     927        kind = expression.args["kind"]
     928        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
     929        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
     930        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
     931        cascade = " CASCADE" if expression.args.get("cascade") else ""
     932        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
     933        purge = " PURGE" if expression.args.get("purge") else ""
     934        return (
     935            f"DROP{temporary}{materialized} {kind}{exists_sql}{this}{cascade}{constraints}{purge}"
     936        )
     937
     938    def except_sql(self, expression: exp.Except) -> str:
     939        return self.prepend_ctes(
     940            expression,
     941            self.set_operation(expression, self.except_op(expression)),
     942        )
     943
     944    def except_op(self, expression: exp.Except) -> str:
     945        return f"EXCEPT{'' if expression.args.get('distinct') else ' ALL'}"
     946
     947    def fetch_sql(self, expression: exp.Fetch) -> str:
     948        direction = expression.args.get("direction")
     949        direction = f" {direction.upper()}" if direction else ""
     950        count = expression.args.get("count")
     951        count = f" {count}" if count else ""
     952        if expression.args.get("percent"):
     953            count = f"{count} PERCENT"
     954        with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY"
     955        return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}"
     956
     957    def filter_sql(self, expression: exp.Filter) -> str:
     958        this = self.sql(expression, "this")
     959        where = self.sql(expression, "expression").strip()
     960        return f"{this} FILTER({where})"
     961
     962    def hint_sql(self, expression: exp.Hint) -> str:
     963        if not self.QUERY_HINTS:
     964            self.unsupported("Hints are not supported")
     965            return ""
     966
     967        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"
     968
     969    def index_sql(self, expression: exp.Index) -> str:
     970        unique = "UNIQUE " if expression.args.get("unique") else ""
     971        primary = "PRIMARY " if expression.args.get("primary") else ""
     972        amp = "AMP " if expression.args.get("amp") else ""
     973        name = self.sql(expression, "this")
     974        name = f"{name} " if name else ""
     975        table = self.sql(expression, "table")
     976        table = f"{self.INDEX_ON} {table}" if table else ""
     977        using = self.sql(expression, "using")
     978        using = f" USING {using} " if using else ""
     979        index = "INDEX " if not table else ""
     980        columns = self.expressions(expression, key="columns", flat=True)
     981        columns = f"({columns})" if columns else ""
     982        partition_by = self.expressions(expression, key="partition_by", flat=True)
     983        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
     984        return f"{unique}{primary}{amp}{index}{name}{table}{using}{columns}{partition_by}"
     985
     986    def identifier_sql(self, expression: exp.Identifier) -> str:
     987        text = expression.name
     988        lower = text.lower()
     989        text = lower if self.normalize and not expression.quoted else text
     990        text = text.replace(self.IDENTIFIER_END, self._escaped_identifier_end)
     991        if (
     992            expression.quoted
     993            or self.can_identify(text, self.identify)
     994            or lower in self.RESERVED_KEYWORDS
     995            or (not self.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
     996        ):
     997            text = f"{self.IDENTIFIER_START}{text}{self.IDENTIFIER_END}"
     998        return text
     999
    1000    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    1001        input_format = self.sql(expression, "input_format")
    1002        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    1003        output_format = self.sql(expression, "output_format")
    1004        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    1005        return self.sep().join((input_format, output_format))
    1006
    1007    def national_sql(self, expression: exp.National, prefix: str = "N") -> str:
    1008        string = self.sql(exp.Literal.string(expression.name))
    1009        return f"{prefix}{string}"
    1010
    1011    def partition_sql(self, expression: exp.Partition) -> str:
    1012        return f"PARTITION({self.expressions(expression, flat=True)})"
    1013
    1014    def properties_sql(self, expression: exp.Properties) -> str:
    1015        root_properties = []
    1016        with_properties = []
    1017
    1018        for p in expression.expressions:
    1019            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1020            if p_loc == exp.Properties.Location.POST_WITH:
    1021                with_properties.append(p.copy())
    1022            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    1023                root_properties.append(p.copy())
    1024
    1025        return self.root_properties(
    1026            exp.Properties(expressions=root_properties)
    1027        ) + self.with_properties(exp.Properties(expressions=with_properties))
    1028
    1029    def root_properties(self, properties: exp.Properties) -> str:
    1030        if properties.expressions:
    1031            return self.sep() + self.expressions(properties, indent=False, sep=" ")
    1032        return ""
    1033
    1034    def properties(
    1035        self,
    1036        properties: exp.Properties,
    1037        prefix: str = "",
    1038        sep: str = ", ",
    1039        suffix: str = "",
    1040        wrapped: bool = True,
    1041    ) -> str:
    1042        if properties.expressions:
    1043            expressions = self.expressions(properties, sep=sep, indent=False)
    1044            if expressions:
    1045                expressions = self.wrap(expressions) if wrapped else expressions
    1046                return f"{prefix}{' ' if prefix and prefix != ' ' else ''}{expressions}{suffix}"
    1047        return ""
    1048
    1049    def with_properties(self, properties: exp.Properties) -> str:
    1050        return self.properties(properties, prefix=self.seg("WITH"))
    1051
    1052    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
    1053        properties_locs = defaultdict(list)
    1054        for p in properties.expressions:
    1055            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1056            if p_loc != exp.Properties.Location.UNSUPPORTED:
    1057                properties_locs[p_loc].append(p.copy())
    1058            else:
    1059                self.unsupported(f"Unsupported property {p.key}")
    1060
    1061        return properties_locs
    1062
    1063    def property_sql(self, expression: exp.Property) -> str:
    1064        property_cls = expression.__class__
    1065        if property_cls == exp.Property:
    1066            return f"{expression.name}={self.sql(expression, 'value')}"
    1067
    1068        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    1069        if not property_name:
    1070            self.unsupported(f"Unsupported property {expression.key}")
    1071
    1072        return f"{property_name}={self.sql(expression, 'this')}"
    1073
    1074    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
    1075        options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
    1076        options = f" {options}" if options else ""
    1077        return f"LIKE {self.sql(expression, 'this')}{options}"
    1078
    1079    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1080        no = "NO " if expression.args.get("no") else ""
    1081        protection = " PROTECTION" if expression.args.get("protection") else ""
    1082        return f"{no}FALLBACK{protection}"
    1083
    1084    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1085        no = "NO " if expression.args.get("no") else ""
    1086        local = expression.args.get("local")
    1087        local = f"{local} " if local else ""
    1088        dual = "DUAL " if expression.args.get("dual") else ""
    1089        before = "BEFORE " if expression.args.get("before") else ""
    1090        after = "AFTER " if expression.args.get("after") else ""
    1091        return f"{no}{local}{dual}{before}{after}JOURNAL"
    1092
    1093    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1094        freespace = self.sql(expression, "this")
    1095        percent = " PERCENT" if expression.args.get("percent") else ""
    1096        return f"FREESPACE={freespace}{percent}"
    1097
    1098    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1099        if expression.args.get("default"):
    1100            property = "DEFAULT"
    1101        elif expression.args.get("on"):
    1102            property = "ON"
    1103        else:
    1104            property = "OFF"
    1105        return f"CHECKSUM={property}"
    1106
    1107    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1108        if expression.args.get("no"):
    1109            return "NO MERGEBLOCKRATIO"
    1110        if expression.args.get("default"):
    1111            return "DEFAULT MERGEBLOCKRATIO"
    1112
    1113        percent = " PERCENT" if expression.args.get("percent") else ""
    1114        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"
    1115
    1116    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1117        default = expression.args.get("default")
    1118        minimum = expression.args.get("minimum")
    1119        maximum = expression.args.get("maximum")
    1120        if default or minimum or maximum:
    1121            if default:
    1122                prop = "DEFAULT"
    1123            elif minimum:
    1124                prop = "MINIMUM"
    1125            else:
    1126                prop = "MAXIMUM"
    1127            return f"{prop} DATABLOCKSIZE"
    1128        units = expression.args.get("units")
    1129        units = f" {units}" if units else ""
    1130        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"
    1131
    1132    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1133        autotemp = expression.args.get("autotemp")
    1134        always = expression.args.get("always")
    1135        default = expression.args.get("default")
    1136        manual = expression.args.get("manual")
    1137        never = expression.args.get("never")
    1138
    1139        if autotemp is not None:
    1140            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1141        elif always:
    1142            prop = "ALWAYS"
    1143        elif default:
    1144            prop = "DEFAULT"
    1145        elif manual:
    1146            prop = "MANUAL"
    1147        elif never:
    1148            prop = "NEVER"
    1149        return f"BLOCKCOMPRESSION={prop}"
    1150
    1151    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1152        no = expression.args.get("no")
    1153        no = " NO" if no else ""
    1154        concurrent = expression.args.get("concurrent")
    1155        concurrent = " CONCURRENT" if concurrent else ""
    1156
    1157        for_ = ""
    1158        if expression.args.get("for_all"):
    1159            for_ = " FOR ALL"
    1160        elif expression.args.get("for_insert"):
    1161            for_ = " FOR INSERT"
    1162        elif expression.args.get("for_none"):
    1163            for_ = " FOR NONE"
    1164        return f"WITH{no}{concurrent} ISOLATED LOADING{for_}"
    1165
    1166    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1167        kind = expression.args.get("kind")
    1168        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1169        for_or_in = expression.args.get("for_or_in")
    1170        lock_type = expression.args.get("lock_type")
    1171        override = " OVERRIDE" if expression.args.get("override") else ""
    1172        return f"LOCKING {kind}{this} {for_or_in} {lock_type}{override}"
    1173
    1174    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1175        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1176        statistics = expression.args.get("statistics")
    1177        statistics_sql = ""
    1178        if statistics is not None:
    1179            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1180        return f"{data_sql}{statistics_sql}"
    1181
    1182    def insert_sql(self, expression: exp.Insert) -> str:
    1183        overwrite = expression.args.get("overwrite")
    1184
    1185        if isinstance(expression.this, exp.Directory):
    1186            this = " OVERWRITE" if overwrite else " INTO"
    1187        else:
    1188            this = " OVERWRITE TABLE" if overwrite else " INTO"
    1189
    1190        alternative = expression.args.get("alternative")
    1191        alternative = f" OR {alternative}" if alternative else ""
    1192        ignore = " IGNORE" if expression.args.get("ignore") else ""
    1193
    1194        this = f"{this} {self.sql(expression, 'this')}"
    1195
    1196        exists = " IF EXISTS" if expression.args.get("exists") else ""
    1197        partition_sql = (
    1198            f" {self.sql(expression, 'partition')}" if expression.args.get("partition") else ""
    1199        )
    1200        where = self.sql(expression, "where")
    1201        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
    1202        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
    1203        conflict = self.sql(expression, "conflict")
    1204        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1205        returning = self.sql(expression, "returning")
    1206
    1207        if self.RETURNING_END:
    1208            expression_sql = f"{expression_sql}{conflict}{returning}"
    1209        else:
    1210            expression_sql = f"{returning}{expression_sql}{conflict}"
    1211
    1212        sql = f"INSERT{alternative}{ignore}{this}{by_name}{exists}{partition_sql}{where}{expression_sql}"
    1213        return self.prepend_ctes(expression, sql)
    1214
    1215    def intersect_sql(self, expression: exp.Intersect) -> str:
    1216        return self.prepend_ctes(
    1217            expression,
    1218            self.set_operation(expression, self.intersect_op(expression)),
    1219        )
    1220
    1221    def intersect_op(self, expression: exp.Intersect) -> str:
    1222        return f"INTERSECT{'' if expression.args.get('distinct') else ' ALL'}"
    1223
    1224    def introducer_sql(self, expression: exp.Introducer) -> str:
    1225        return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}"
    1226
    1227    def pseudotype_sql(self, expression: exp.PseudoType) -> str:
    1228        return expression.name.upper()
    1229
    1230    def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str:
    1231        return expression.name.upper()
    1232
    1233    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1234        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1235        constraint = self.sql(expression, "constraint")
    1236        if constraint:
    1237            constraint = f"ON CONSTRAINT {constraint}"
    1238        key = self.expressions(expression, key="key", flat=True)
    1239        do = "" if expression.args.get("duplicate") else " DO "
    1240        nothing = "NOTHING" if expression.args.get("nothing") else ""
    1241        expressions = self.expressions(expression, flat=True)
    1242        set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
    1243        if expressions:
    1244            expressions = f"UPDATE {set_keyword}{expressions}"
    1245        return f"{self.seg(conflict)} {constraint}{key}{do}{nothing}{expressions}"
    1246
    1247    def returning_sql(self, expression: exp.Returning) -> str:
    1248        return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}"
    1249
    1250    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1251        fields = expression.args.get("fields")
    1252        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1253        escaped = expression.args.get("escaped")
    1254        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1255        items = expression.args.get("collection_items")
    1256        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1257        keys = expression.args.get("map_keys")
    1258        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1259        lines = expression.args.get("lines")
    1260        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1261        null = expression.args.get("null")
    1262        null = f" NULL DEFINED AS {null}" if null else ""
    1263        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"
    1264
    1265    def withtablehint_sql(self, expression: exp.WithTableHint) -> str:
    1266        return f"WITH ({self.expressions(expression, flat=True)})"
    1267
    1268    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1269        this = f"{self.sql(expression, 'this')} INDEX"
    1270        target = self.sql(expression, "target")
    1271        target = f" FOR {target}" if target else ""
    1272        return f"{this}{target} ({self.expressions(expression, flat=True)})"
    1273
    1274    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1275        table = ".".join(
    1276            part
    1277            for part in [
    1278                self.sql(expression, "catalog"),
    1279                self.sql(expression, "db"),
    1280                self.sql(expression, "this"),
    1281            ]
    1282            if part
    1283        )
    1284
    1285        version = self.sql(expression, "version")
    1286        version = f" {version}" if version else ""
    1287        alias = self.sql(expression, "alias")
    1288        alias = f"{sep}{alias}" if alias else ""
    1289        hints = self.expressions(expression, key="hints", sep=" ")
    1290        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
    1291        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    1292        pivots = f" {pivots}" if pivots else ""
    1293        joins = self.expressions(expression, key="joins", sep="", skip_first=True)
    1294        laterals = self.expressions(expression, key="laterals", sep="")
    1295
    1296        return f"{table}{version}{alias}{hints}{pivots}{joins}{laterals}"
    1297
    1298    def tablesample_sql(
    1299        self, expression: exp.TableSample, seed_prefix: str = "SEED", sep=" AS "
    1300    ) -> str:
    1301        if self.ALIAS_POST_TABLESAMPLE and expression.this.alias:
    1302            table = expression.this.copy()
    1303            table.set("alias", None)
    1304            this = self.sql(table)
    1305            alias = f"{sep}{self.sql(expression.this, 'alias')}"
    1306        else:
    1307            this = self.sql(expression, "this")
    1308            alias = ""
    1309        method = self.sql(expression, "method")
    1310        method = f"{method.upper()} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    1311        numerator = self.sql(expression, "bucket_numerator")
    1312        denominator = self.sql(expression, "bucket_denominator")
    1313        field = self.sql(expression, "bucket_field")
    1314        field = f" ON {field}" if field else ""
    1315        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    1316        percent = self.sql(expression, "percent")
    1317        percent = f"{percent} PERCENT" if percent else ""
    1318        rows = self.sql(expression, "rows")
    1319        rows = f"{rows} ROWS" if rows else ""
    1320        size = self.sql(expression, "size")
    1321        if size and self.TABLESAMPLE_SIZE_IS_PERCENT:
    1322            size = f"{size} PERCENT"
    1323        seed = self.sql(expression, "seed")
    1324        seed = f" {seed_prefix} ({seed})" if seed else ""
    1325        kind = expression.args.get("kind", "TABLESAMPLE")
    1326        return f"{this} {kind} {method}({bucket}{percent}{rows}{size}){seed}{alias}"
    1327
    1328    def pivot_sql(self, expression: exp.Pivot) -> str:
    1329        expressions = self.expressions(expression, flat=True)
    1330
    1331        if expression.this:
    1332            this = self.sql(expression, "this")
    1333            on = f"{self.seg('ON')} {expressions}"
    1334            using = self.expressions(expression, key="using", flat=True)
    1335            using = f"{self.seg('USING')} {using}" if using else ""
    1336            group = self.sql(expression, "group")
    1337            return f"PIVOT {this}{on}{using}{group}"
    1338
    1339        alias = self.sql(expression, "alias")
    1340        alias = f" AS {alias}" if alias else ""
    1341        unpivot = expression.args.get("unpivot")
    1342        direction = "UNPIVOT" if unpivot else "PIVOT"
    1343        field = self.sql(expression, "field")
    1344        include_nulls = expression.args.get("include_nulls")
    1345        if include_nulls is not None:
    1346            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
    1347        else:
    1348            nulls = ""
    1349        return f"{direction}{nulls}({expressions} FOR {field}){alias}"
    1350
    1351    def version_sql(self, expression: exp.Version) -> str:
    1352        this = f"FOR {expression.name}"
    1353        kind = expression.text("kind")
    1354        expr = self.sql(expression, "expression")
    1355        return f"{this} {kind} {expr}"
    1356
    1357    def tuple_sql(self, expression: exp.Tuple) -> str:
    1358        return f"({self.expressions(expression, flat=True)})"
    1359
    1360    def update_sql(self, expression: exp.Update) -> str:
    1361        this = self.sql(expression, "this")
    1362        set_sql = self.expressions(expression, flat=True)
    1363        from_sql = self.sql(expression, "from")
    1364        where_sql = self.sql(expression, "where")
    1365        returning = self.sql(expression, "returning")
    1366        order = self.sql(expression, "order")
    1367        limit = self.sql(expression, "limit")
    1368        if self.RETURNING_END:
    1369            expression_sql = f"{from_sql}{where_sql}{returning}"
    1370        else:
    1371            expression_sql = f"{returning}{from_sql}{where_sql}"
    1372        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
    1373        return self.prepend_ctes(expression, sql)
    1374
    1375    def values_sql(self, expression: exp.Values) -> str:
    1376        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
    1377        if self.VALUES_AS_TABLE or not expression.find_ancestor(exp.From, exp.Join):
    1378            args = self.expressions(expression)
    1379            alias = self.sql(expression, "alias")
    1380            values = f"VALUES{self.seg('')}{args}"
    1381            values = (
    1382                f"({values})"
    1383                if self.WRAP_DERIVED_VALUES and (alias or isinstance(expression.parent, exp.From))
    1384                else values
    1385            )
    1386            return f"{values} AS {alias}" if alias else values
    1387
    1388        # Converts `VALUES...` expression into a series of select unions.
    1389        # Note: If you have a lot of unions then this will result in a large number of recursive statements to
    1390        # evaluate the expression. You may need to increase `sys.setrecursionlimit` to run and it can also be
    1391        # very slow.
    1392        expression = expression.copy()
    1393        column_names = expression.alias and expression.args["alias"].columns
    1394
    1395        selects = []
    1396
    1397        for i, tup in enumerate(expression.expressions):
    1398            row = tup.expressions
    1399
    1400            if i == 0 and column_names:
    1401                row = [
    1402                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
    1403                ]
    1404
    1405            selects.append(exp.Select(expressions=row))
    1406
    1407        subquery_expression: exp.Select | exp.Union = selects[0]
    1408        if len(selects) > 1:
    1409            for select in selects[1:]:
    1410                subquery_expression = exp.union(
    1411                    subquery_expression, select, distinct=False, copy=False
    1412                )
    1413
    1414        return self.subquery_sql(subquery_expression.subquery(expression.alias, copy=False))
    1415
    1416    def var_sql(self, expression: exp.Var) -> str:
    1417        return self.sql(expression, "this")
    1418
    1419    def into_sql(self, expression: exp.Into) -> str:
    1420        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    1421        unlogged = " UNLOGGED" if expression.args.get("unlogged") else ""
    1422        return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"
    1423
    1424    def from_sql(self, expression: exp.From) -> str:
    1425        return f"{self.seg('FROM')} {self.sql(expression, 'this')}"
    1426
    1427    def group_sql(self, expression: exp.Group) -> str:
    1428        group_by = self.op_expressions("GROUP BY", expression)
    1429
    1430        if expression.args.get("all"):
    1431            return f"{group_by} ALL"
    1432
    1433        grouping_sets = self.expressions(expression, key="grouping_sets", indent=False)
    1434        grouping_sets = (
    1435            f"{self.seg('GROUPING SETS')} {self.wrap(grouping_sets)}" if grouping_sets else ""
    1436        )
    1437
    1438        cube = expression.args.get("cube", [])
    1439        if seq_get(cube, 0) is True:
    1440            return f"{group_by}{self.seg('WITH CUBE')}"
    1441        else:
    1442            cube_sql = self.expressions(expression, key="cube", indent=False)
    1443            cube_sql = f"{self.seg('CUBE')} {self.wrap(cube_sql)}" if cube_sql else ""
    1444
    1445        rollup = expression.args.get("rollup", [])
    1446        if seq_get(rollup, 0) is True:
    1447            return f"{group_by}{self.seg('WITH ROLLUP')}"
    1448        else:
    1449            rollup_sql = self.expressions(expression, key="rollup", indent=False)
    1450            rollup_sql = f"{self.seg('ROLLUP')} {self.wrap(rollup_sql)}" if rollup_sql else ""
    1451
    1452        groupings = csv(
    1453            grouping_sets,
    1454            cube_sql,
    1455            rollup_sql,
    1456            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    1457            sep=self.GROUPINGS_SEP,
    1458        )
    1459
    1460        if expression.args.get("expressions") and groupings:
    1461            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    1462
    1463        return f"{group_by}{groupings}"
    1464
    1465    def having_sql(self, expression: exp.Having) -> str:
    1466        this = self.indent(self.sql(expression, "this"))
    1467        return f"{self.seg('HAVING')}{self.sep()}{this}"
    1468
    1469    def connect_sql(self, expression: exp.Connect) -> str:
    1470        start = self.sql(expression, "start")
    1471        start = self.seg(f"START WITH {start}") if start else ""
    1472        connect = self.sql(expression, "connect")
    1473        connect = self.seg(f"CONNECT BY {connect}")
    1474        return start + connect
    1475
    1476    def prior_sql(self, expression: exp.Prior) -> str:
    1477        return f"PRIOR {self.sql(expression, 'this')}"
    1478
    1479    def join_sql(self, expression: exp.Join) -> str:
    1480        op_sql = " ".join(
    1481            op
    1482            for op in (
    1483                expression.method,
    1484                "GLOBAL" if expression.args.get("global") else None,
    1485                expression.side,
    1486                expression.kind,
    1487                expression.hint if self.JOIN_HINTS else None,
    1488            )
    1489            if op
    1490        )
    1491        on_sql = self.sql(expression, "on")
    1492        using = expression.args.get("using")
    1493
    1494        if not on_sql and using:
    1495            on_sql = csv(*(self.sql(column) for column in using))
    1496
    1497        this_sql = self.sql(expression, "this")
    1498
    1499        if on_sql:
    1500            on_sql = self.indent(on_sql, skip_first=True)
    1501            space = self.seg(" " * self.pad) if self.pretty else " "
    1502            if using:
    1503                on_sql = f"{space}USING ({on_sql})"
    1504            else:
    1505                on_sql = f"{space}ON {on_sql}"
    1506        elif not op_sql:
    1507            return f", {this_sql}"
    1508
    1509        op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    1510        return f"{self.seg(op_sql)} {this_sql}{on_sql}"
    1511
    1512    def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->") -> str:
    1513        args = self.expressions(expression, flat=True)
    1514        args = f"({args})" if len(args.split(",")) > 1 else args
    1515        return f"{args} {arrow_sep} {self.sql(expression, 'this')}"
    1516
    1517    def lateral_sql(self, expression: exp.Lateral) -> str:
    1518        this = self.sql(expression, "this")
    1519
    1520        if isinstance(expression.this, exp.Subquery):
    1521            return f"LATERAL {this}"
    1522
    1523        if expression.args.get("view"):
    1524            alias = expression.args["alias"]
    1525            columns = self.expressions(alias, key="columns", flat=True)
    1526            table = f" {alias.name}" if alias.name else ""
    1527            columns = f" AS {columns}" if columns else ""
    1528            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    1529            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    1530
    1531        alias = self.sql(expression, "alias")
    1532        alias = f" AS {alias}" if alias else ""
    1533        return f"LATERAL {this}{alias}"
    1534
    1535    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    1536        this = self.sql(expression, "this")
    1537        args = ", ".join(
    1538            sql
    1539            for sql in (
    1540                self.sql(expression, "offset"),
    1541                self.sql(expression, "expression"),
    1542            )
    1543            if sql
    1544        )
    1545        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args}"
    1546
    1547    def offset_sql(self, expression: exp.Offset) -> str:
    1548        this = self.sql(expression, "this")
    1549        return f"{this}{self.seg('OFFSET')} {self.sql(expression, 'expression')}"
    1550
    1551    def setitem_sql(self, expression: exp.SetItem) -> str:
    1552        kind = self.sql(expression, "kind")
    1553        kind = f"{kind} " if kind else ""
    1554        this = self.sql(expression, "this")
    1555        expressions = self.expressions(expression)
    1556        collate = self.sql(expression, "collate")
    1557        collate = f" COLLATE {collate}" if collate else ""
    1558        global_ = "GLOBAL " if expression.args.get("global") else ""
    1559        return f"{global_}{kind}{this}{expressions}{collate}"
    1560
    1561    def set_sql(self, expression: exp.Set) -> str:
    1562        expressions = (
    1563            f" {self.expressions(expression, flat=True)}" if expression.expressions else ""
    1564        )
    1565        tag = " TAG" if expression.args.get("tag") else ""
    1566        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"
    1567
    1568    def pragma_sql(self, expression: exp.Pragma) -> str:
    1569        return f"PRAGMA {self.sql(expression, 'this')}"
    1570
    1571    def lock_sql(self, expression: exp.Lock) -> str:
    1572        if not self.LOCKING_READS_SUPPORTED:
    1573            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    1574            return ""
    1575
    1576        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    1577        expressions = self.expressions(expression, flat=True)
    1578        expressions = f" OF {expressions}" if expressions else ""
    1579        wait = expression.args.get("wait")
    1580
    1581        if wait is not None:
    1582            if isinstance(wait, exp.Literal):
    1583                wait = f" WAIT {self.sql(wait)}"
    1584            else:
    1585                wait = " NOWAIT" if wait else " SKIP LOCKED"
    1586
    1587        return f"{lock_type}{expressions}{wait or ''}"
    1588
    1589    def literal_sql(self, expression: exp.Literal) -> str:
    1590        text = expression.this or ""
    1591        if expression.is_string:
    1592            text = f"{self.QUOTE_START}{self.escape_str(text)}{self.QUOTE_END}"
    1593        return text
    1594
    1595    def escape_str(self, text: str) -> str:
    1596        text = text.replace(self.QUOTE_END, self._escaped_quote_end)
    1597        if self.ESCAPE_LINE_BREAK:
    1598            text = text.replace("\n", "\\n")
    1599        elif self.pretty:
    1600            text = text.replace("\n", self.SENTINEL_LINE_BREAK)
    1601        return text
    1602
    1603    def loaddata_sql(self, expression: exp.LoadData) -> str:
    1604        local = " LOCAL" if expression.args.get("local") else ""
    1605        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    1606        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    1607        this = f" INTO TABLE {self.sql(expression, 'this')}"
    1608        partition = self.sql(expression, "partition")
    1609        partition = f" {partition}" if partition else ""
    1610        input_format = self.sql(expression, "input_format")
    1611        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    1612        serde = self.sql(expression, "serde")
    1613        serde = f" SERDE {serde}" if serde else ""
    1614        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"
    1615
    1616    def null_sql(self, *_) -> str:
    1617        return "NULL"
    1618
    1619    def boolean_sql(self, expression: exp.Boolean) -> str:
    1620        return "TRUE" if expression.this else "FALSE"
    1621
    1622    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    1623        this = self.sql(expression, "this")
    1624        this = f"{this} " if this else this
    1625        return self.op_expressions(f"{this}ORDER BY", expression, flat=this or flat)  # type: ignore
    1626
    1627    def cluster_sql(self, expression: exp.Cluster) -> str:
    1628        return self.op_expressions("CLUSTER BY", expression)
    1629
    1630    def distribute_sql(self, expression: exp.Distribute) -> str:
    1631        return self.op_expressions("DISTRIBUTE BY", expression)
    1632
    1633    def sort_sql(self, expression: exp.Sort) -> str:
    1634        return self.op_expressions("SORT BY", expression)
    1635
    1636    def ordered_sql(self, expression: exp.Ordered) -> str:
    1637        desc = expression.args.get("desc")
    1638        asc = not desc
    1639
    1640        nulls_first = expression.args.get("nulls_first")
    1641        nulls_last = not nulls_first
    1642        nulls_are_large = self.NULL_ORDERING == "nulls_are_large"
    1643        nulls_are_small = self.NULL_ORDERING == "nulls_are_small"
    1644        nulls_are_last = self.NULL_ORDERING == "nulls_are_last"
    1645
    1646        sort_order = " DESC" if desc else ""
    1647        nulls_sort_change = ""
    1648        if nulls_first and (
    1649            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
    1650        ):
    1651            nulls_sort_change = " NULLS FIRST"
    1652        elif (
    1653            nulls_last
    1654            and ((asc and nulls_are_small) or (desc and nulls_are_large))
    1655            and not nulls_are_last
    1656        ):
    1657            nulls_sort_change = " NULLS LAST"
    1658
    1659        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
    1660            self.unsupported(
    1661                "Sorting in an ORDER BY on NULLS FIRST/NULLS LAST is not supported by this dialect"
    1662            )
    1663            nulls_sort_change = ""
    1664
    1665        return f"{self.sql(expression, 'this')}{sort_order}{nulls_sort_change}"
    1666
    1667    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    1668        partition = self.partition_by_sql(expression)
    1669        order = self.sql(expression, "order")
    1670        measures = self.expressions(expression, key="measures")
    1671        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    1672        rows = self.sql(expression, "rows")
    1673        rows = self.seg(rows) if rows else ""
    1674        after = self.sql(expression, "after")
    1675        after = self.seg(after) if after else ""
    1676        pattern = self.sql(expression, "pattern")
    1677        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    1678        definition_sqls = [
    1679            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    1680            for definition in expression.args.get("define", [])
    1681        ]
    1682        definitions = self.expressions(sqls=definition_sqls)
    1683        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    1684        body = "".join(
    1685            (
    1686                partition,
    1687                order,
    1688                measures,
    1689                rows,
    1690                after,
    1691                pattern,
    1692                define,
    1693            )
    1694        )
    1695        alias = self.sql(expression, "alias")
    1696        alias = f" {alias}" if alias else ""
    1697        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"
    1698
    1699    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    1700        limit: t.Optional[exp.Fetch | exp.Limit] = expression.args.get("limit")
    1701
    1702        # If the limit is generated as TOP, we need to ensure it's not generated twice
    1703        with_offset_limit_modifiers = not isinstance(limit, exp.Limit) or not self.LIMIT_IS_TOP
    1704
    1705        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    1706            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
    1707        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    1708            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
    1709
    1710        fetch = isinstance(limit, exp.Fetch)
    1711
    1712        offset_limit_modifiers = (
    1713            self.offset_limit_modifiers(expression, fetch, limit)
    1714            if with_offset_limit_modifiers
    1715            else []
    1716        )
    1717
    1718        return csv(
    1719            *sqls,
    1720            *[self.sql(join) for join in expression.args.get("joins") or []],
    1721            self.sql(expression, "connect"),
    1722            self.sql(expression, "match"),
    1723            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    1724            self.sql(expression, "where"),
    1725            self.sql(expression, "group"),
    1726            self.sql(expression, "having"),
    1727            *self.after_having_modifiers(expression),
    1728            self.sql(expression, "order"),
    1729            *offset_limit_modifiers,
    1730            *self.after_limit_modifiers(expression),
    1731            sep="",
    1732        )
    1733
    1734    def offset_limit_modifiers(
    1735        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    1736    ) -> t.List[str]:
    1737        return [
    1738            self.sql(expression, "offset") if fetch else self.sql(limit),
    1739            self.sql(limit) if fetch else self.sql(expression, "offset"),
    1740        ]
    1741
    1742    def after_having_modifiers(self, expression: exp.Expression) -> t.List[str]:
    1743        return [
    1744            self.sql(expression, "qualify"),
    1745            self.seg("WINDOW ") + self.expressions(expression, key="windows", flat=True)
    1746            if expression.args.get("windows")
    1747            else "",
    1748            self.sql(expression, "distribute"),
    1749            self.sql(expression, "sort"),
    1750            self.sql(expression, "cluster"),
    1751        ]
    1752
    1753    def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]:
    1754        locks = self.expressions(expression, key="locks", sep=" ")
    1755        locks = f" {locks}" if locks else ""
    1756        return [locks, self.sql(expression, "sample")]
    1757
    1758    def select_sql(self, expression: exp.Select) -> str:
    1759        hint = self.sql(expression, "hint")
    1760        distinct = self.sql(expression, "distinct")
    1761        distinct = f" {distinct}" if distinct else ""
    1762        kind = self.sql(expression, "kind").upper()
    1763        limit = expression.args.get("limit")
    1764        top = (
    1765            self.limit_sql(limit, top=True)
    1766            if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP
    1767            else ""
    1768        )
    1769
    1770        expressions = self.expressions(expression)
    1771
    1772        if kind:
    1773            if kind in self.SELECT_KINDS:
    1774                kind = f" AS {kind}"
    1775            else:
    1776                if kind == "STRUCT":
    1777                    expressions = self.expressions(
    1778                        sqls=[
    1779                            self.sql(
    1780                                exp.Struct(
    1781                                    expressions=[
    1782                                        exp.column(e.output_name).eq(
    1783                                            e.this if isinstance(e, exp.Alias) else e
    1784                                        )
    1785                                        for e in expression.expressions
    1786                                    ]
    1787                                )
    1788                            )
    1789                        ]
    1790                    )
    1791                kind = ""
    1792
    1793        expressions = f"{self.sep()}{expressions}" if expressions else expressions
    1794        sql = self.query_modifiers(
    1795            expression,
    1796            f"SELECT{top}{hint}{distinct}{kind}{expressions}",
    1797            self.sql(expression, "into", comment=False),
    1798            self.sql(expression, "from", comment=False),
    1799        )
    1800        return self.prepend_ctes(expression, sql)
    1801
    1802    def schema_sql(self, expression: exp.Schema) -> str:
    1803        this = self.sql(expression, "this")
    1804        this = f"{this} " if this else ""
    1805        sql = self.schema_columns_sql(expression)
    1806        return f"{this}{sql}"
    1807
    1808    def schema_columns_sql(self, expression: exp.Schema) -> str:
    1809        return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
    1810
    1811    def star_sql(self, expression: exp.Star) -> str:
    1812        except_ = self.expressions(expression, key="except", flat=True)
    1813        except_ = f"{self.seg(self.STAR_MAPPING['except'])} ({except_})" if except_ else ""
    1814        replace = self.expressions(expression, key="replace", flat=True)
    1815        replace = f"{self.seg(self.STAR_MAPPING['replace'])} ({replace})" if replace else ""
    1816        return f"*{except_}{replace}"
    1817
    1818    def parameter_sql(self, expression: exp.Parameter) -> str:
    1819        this = self.sql(expression, "this")
    1820        this = f"{{{this}}}" if expression.args.get("wrapped") else f"{this}"
    1821        return f"{self.PARAMETER_TOKEN}{this}"
    1822
    1823    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    1824        this = self.sql(expression, "this")
    1825        kind = expression.text("kind")
    1826        if kind:
    1827            kind = f"{kind}."
    1828        return f"@@{kind}{this}"
    1829
    1830    def placeholder_sql(self, expression: exp.Placeholder) -> str:
    1831        return f":{expression.name}" if expression.name else "?"
    1832
    1833    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    1834        alias = self.sql(expression, "alias")
    1835        alias = f"{sep}{alias}" if alias else ""
    1836
    1837        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    1838        pivots = f" {pivots}" if pivots else ""
    1839
    1840        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    1841        return self.prepend_ctes(expression, sql)
    1842
    1843    def qualify_sql(self, expression: exp.Qualify) -> str:
    1844        this = self.indent(self.sql(expression, "this"))
    1845        return f"{self.seg('QUALIFY')}{self.sep()}{this}"
    1846
    1847    def union_sql(self, expression: exp.Union) -> str:
    1848        return self.prepend_ctes(
    1849            expression,
    1850            self.set_operation(expression, self.union_op(expression)),
    1851        )
    1852
    1853    def union_op(self, expression: exp.Union) -> str:
    1854        kind = " DISTINCT" if self.EXPLICIT_UNION else ""
    1855        kind = kind if expression.args.get("distinct") else " ALL"
    1856        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1857        return f"UNION{kind}{by_name}"
    1858
    1859    def unnest_sql(self, expression: exp.Unnest) -> str:
    1860        args = self.expressions(expression, flat=True)
    1861        alias = expression.args.get("alias")
    1862        if alias and self.UNNEST_COLUMN_ONLY:
    1863            columns = alias.columns
    1864            alias = self.sql(columns[0]) if columns else ""
    1865        else:
    1866            alias = self.sql(expression, "alias")
    1867        alias = f" AS {alias}" if alias else alias
    1868        ordinality = " WITH ORDINALITY" if expression.args.get("ordinality") else ""
    1869        offset = expression.args.get("offset")
    1870        offset = f" WITH OFFSET AS {self.sql(offset)}" if offset else ""
    1871        return f"UNNEST({args}){ordinality}{alias}{offset}"
    1872
    1873    def where_sql(self, expression: exp.Where) -> str:
    1874        this = self.indent(self.sql(expression, "this"))
    1875        return f"{self.seg('WHERE')}{self.sep()}{this}"
    1876
    1877    def window_sql(self, expression: exp.Window) -> str:
    1878        this = self.sql(expression, "this")
    1879        partition = self.partition_by_sql(expression)
    1880        order = expression.args.get("order")
    1881        order = self.order_sql(order, flat=True) if order else ""
    1882        spec = self.sql(expression, "spec")
    1883        alias = self.sql(expression, "alias")
    1884        over = self.sql(expression, "over") or "OVER"
    1885
    1886        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    1887
    1888        first = expression.args.get("first")
    1889        if first is None:
    1890            first = ""
    1891        else:
    1892            first = "FIRST" if first else "LAST"
    1893
    1894        if not partition and not order and not spec and alias:
    1895            return f"{this} {alias}"
    1896
    1897        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
    1898        return f"{this} ({args})"
    1899
    1900    def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str:
    1901        partition = self.expressions(expression, key="partition_by", flat=True)
    1902        return f"PARTITION BY {partition}" if partition else ""
    1903
    1904    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    1905        kind = self.sql(expression, "kind")
    1906        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    1907        end = (
    1908            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    1909            or "CURRENT ROW"
    1910        )
    1911        return f"{kind} BETWEEN {start} AND {end}"
    1912
    1913    def withingroup_sql(self, expression: exp.WithinGroup) -> str:
    1914        this = self.sql(expression, "this")
    1915        expression_sql = self.sql(expression, "expression")[1:]  # order has a leading space
    1916        return f"{this} WITHIN GROUP ({expression_sql})"
    1917
    1918    def between_sql(self, expression: exp.Between) -> str:
    1919        this = self.sql(expression, "this")
    1920        low = self.sql(expression, "low")
    1921        high = self.sql(expression, "high")
    1922        return f"{this} BETWEEN {low} AND {high}"
    1923
    1924    def bracket_sql(self, expression: exp.Bracket) -> str:
    1925        expressions = apply_index_offset(expression.this, expression.expressions, self.INDEX_OFFSET)
    1926        expressions_sql = ", ".join(self.sql(e) for e in expressions)
    1927
    1928        return f"{self.sql(expression, 'this')}[{expressions_sql}]"
    1929
    1930    def safebracket_sql(self, expression: exp.SafeBracket) -> str:
    1931        return self.bracket_sql(expression)
    1932
    1933    def all_sql(self, expression: exp.All) -> str:
    1934        return f"ALL {self.wrap(expression)}"
    1935
    1936    def any_sql(self, expression: exp.Any) -> str:
    1937        this = self.sql(expression, "this")
    1938        if isinstance(expression.this, exp.Subqueryable):
    1939            this = self.wrap(this)
    1940        return f"ANY {this}"
    1941
    1942    def exists_sql(self, expression: exp.Exists) -> str:
    1943        return f"EXISTS{self.wrap(expression)}"
    1944
    1945    def case_sql(self, expression: exp.Case) -> str:
    1946        this = self.sql(expression, "this")
    1947        statements = [f"CASE {this}" if this else "CASE"]
    1948
    1949        for e in expression.args["ifs"]:
    1950            statements.append(f"WHEN {self.sql(e, 'this')}")
    1951            statements.append(f"THEN {self.sql(e, 'true')}")
    1952
    1953        default = self.sql(expression, "default")
    1954
    1955        if default:
    1956            statements.append(f"ELSE {default}")
    1957
    1958        statements.append("END")
    1959
    1960        if self.pretty and self.text_width(statements) > self.max_text_width:
    1961            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    1962
    1963        return " ".join(statements)
    1964
    1965    def constraint_sql(self, expression: exp.Constraint) -> str:
    1966        this = self.sql(expression, "this")
    1967        expressions = self.expressions(expression, flat=True)
    1968        return f"CONSTRAINT {this} {expressions}"
    1969
    1970    def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str:
    1971        order = expression.args.get("order")
    1972        order = f" OVER ({self.order_sql(order, flat=True)})" if order else ""
    1973        return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}"
    1974
    1975    def extract_sql(self, expression: exp.Extract) -> str:
    1976        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
    1977        expression_sql = self.sql(expression, "expression")
    1978        return f"EXTRACT({this} FROM {expression_sql})"
    1979
    1980    def trim_sql(self, expression: exp.Trim) -> str:
    1981        trim_type = self.sql(expression, "position")
    1982
    1983        if trim_type == "LEADING":
    1984            return self.func("LTRIM", expression.this)
    1985        elif trim_type == "TRAILING":
    1986            return self.func("RTRIM", expression.this)
    1987        else:
    1988            return self.func("TRIM", expression.this, expression.expression)
    1989
    1990    def safeconcat_sql(self, expression: exp.SafeConcat) -> str:
    1991        expressions = expression.expressions
    1992        if self.STRICT_STRING_CONCAT:
    1993            expressions = (exp.cast(e, "text") for e in expressions)
    1994        return self.func("CONCAT", *expressions)
    1995
    1996    def check_sql(self, expression: exp.Check) -> str:
    1997        this = self.sql(expression, key="this")
    1998        return f"CHECK ({this})"
    1999
    2000    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    2001        expressions = self.expressions(expression, flat=True)
    2002        reference = self.sql(expression, "reference")
    2003        reference = f" {reference}" if reference else ""
    2004        delete = self.sql(expression, "delete")
    2005        delete = f" ON DELETE {delete}" if delete else ""
    2006        update = self.sql(expression, "update")
    2007        update = f" ON UPDATE {update}" if update else ""
    2008        return f"FOREIGN KEY ({expressions}){reference}{delete}{update}"
    2009
    2010    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    2011        expressions = self.expressions(expression, flat=True)
    2012        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2013        options = f" {options}" if options else ""
    2014        return f"PRIMARY KEY ({expressions}){options}"
    2015
    2016    def if_sql(self, expression: exp.If) -> str:
    2017        expression = expression.copy()
    2018        return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false")))
    2019
    2020    def matchagainst_sql(self, expression: exp.MatchAgainst) -> str:
    2021        modifier = expression.args.get("modifier")
    2022        modifier = f" {modifier}" if modifier else ""
    2023        return f"{self.func('MATCH', *expression.expressions)} AGAINST({self.sql(expression, 'this')}{modifier})"
    2024
    2025    def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str:
    2026        return f"{self.sql(expression, 'this')}: {self.sql(expression, 'expression')}"
    2027
    2028    def formatjson_sql(self, expression: exp.FormatJson) -> str:
    2029        return f"{self.sql(expression, 'this')} FORMAT JSON"
    2030
    2031    def jsonobject_sql(self, expression: exp.JSONObject) -> str:
    2032        null_handling = expression.args.get("null_handling")
    2033        null_handling = f" {null_handling}" if null_handling else ""
    2034        unique_keys = expression.args.get("unique_keys")
    2035        if unique_keys is not None:
    2036            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    2037        else:
    2038            unique_keys = ""
    2039        return_type = self.sql(expression, "return_type")
    2040        return_type = f" RETURNING {return_type}" if return_type else ""
    2041        encoding = self.sql(expression, "encoding")
    2042        encoding = f" ENCODING {encoding}" if encoding else ""
    2043        return self.func(
    2044            "JSON_OBJECT",
    2045            *expression.expressions,
    2046            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
    2047        )
    2048
    2049    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
    2050        null_handling = expression.args.get("null_handling")
    2051        null_handling = f" {null_handling}" if null_handling else ""
    2052        return_type = self.sql(expression, "return_type")
    2053        return_type = f" RETURNING {return_type}" if return_type else ""
    2054        strict = " STRICT" if expression.args.get("strict") else ""
    2055        return self.func(
    2056            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
    2057        )
    2058
    2059    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
    2060        this = self.sql(expression, "this")
    2061        order = self.sql(expression, "order")
    2062        null_handling = expression.args.get("null_handling")
    2063        null_handling = f" {null_handling}" if null_handling else ""
    2064        return_type = self.sql(expression, "return_type")
    2065        return_type = f" RETURNING {return_type}" if return_type else ""
    2066        strict = " STRICT" if expression.args.get("strict") else ""
    2067        return self.func(
    2068            "JSON_ARRAYAGG",
    2069            this,
    2070            suffix=f"{order}{null_handling}{return_type}{strict})",
    2071        )
    2072
    2073    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
    2074        this = self.sql(expression, "this")
    2075        kind = self.sql(expression, "kind")
    2076        kind = f" {kind}" if kind else ""
    2077        path = self.sql(expression, "path")
    2078        path = f" PATH {path}" if path else ""
    2079        return f"{this}{kind}{path}"
    2080
    2081    def jsontable_sql(self, expression: exp.JSONTable) -> str:
    2082        this = self.sql(expression, "this")
    2083        path = self.sql(expression, "path")
    2084        path = f", {path}" if path else ""
    2085        error_handling = expression.args.get("error_handling")
    2086        error_handling = f" {error_handling}" if error_handling else ""
    2087        empty_handling = expression.args.get("empty_handling")
    2088        empty_handling = f" {empty_handling}" if empty_handling else ""
    2089        columns = f" COLUMNS ({self.expressions(expression, skip_first=True)})"
    2090        return self.func(
    2091            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling}{columns})"
    2092        )
    2093
    2094    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    2095        this = self.sql(expression, "this")
    2096        kind = self.sql(expression, "kind")
    2097        path = self.sql(expression, "path")
    2098        path = f" {path}" if path else ""
    2099        as_json = " AS JSON" if expression.args.get("as_json") else ""
    2100        return f"{this} {kind}{path}{as_json}"
    2101
    2102    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    2103        this = self.sql(expression, "this")
    2104        path = self.sql(expression, "path")
    2105        path = f", {path}" if path else ""
    2106        expressions = self.expressions(expression)
    2107        with_ = (
    2108            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    2109            if expressions
    2110            else ""
    2111        )
    2112        return f"OPENJSON({this}{path}){with_}"
    2113
    2114    def in_sql(self, expression: exp.In) -> str:
    2115        query = expression.args.get("query")
    2116        unnest = expression.args.get("unnest")
    2117        field = expression.args.get("field")
    2118        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    2119
    2120        if query:
    2121            in_sql = self.wrap(query)
    2122        elif unnest:
    2123            in_sql = self.in_unnest_op(unnest)
    2124        elif field:
    2125            in_sql = self.sql(field)
    2126        else:
    2127            in_sql = f"({self.expressions(expression, flat=True)})"
    2128
    2129        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"
    2130
    2131    def in_unnest_op(self, unnest: exp.Unnest) -> str:
    2132        return f"(SELECT {self.sql(unnest)})"
    2133
    2134    def interval_sql(self, expression: exp.Interval) -> str:
    2135        unit = self.sql(expression, "unit")
    2136        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    2137            unit = self.TIME_PART_SINGULARS.get(unit.lower(), unit)
    2138        unit = f" {unit}" if unit else ""
    2139
    2140        if self.SINGLE_STRING_INTERVAL:
    2141            this = expression.this.name if expression.this else ""
    2142            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    2143
    2144        this = self.sql(expression, "this")
    2145        if this:
    2146            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    2147            this = f" {this}" if unwrapped else f" ({this})"
    2148
    2149        return f"INTERVAL{this}{unit}"
    2150
    2151    def return_sql(self, expression: exp.Return) -> str:
    2152        return f"RETURN {self.sql(expression, 'this')}"
    2153
    2154    def reference_sql(self, expression: exp.Reference) -> str:
    2155        this = self.sql(expression, "this")
    2156        expressions = self.expressions(expression, flat=True)
    2157        expressions = f"({expressions})" if expressions else ""
    2158        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2159        options = f" {options}" if options else ""
    2160        return f"REFERENCES {this}{expressions}{options}"
    2161
    2162    def anonymous_sql(self, expression: exp.Anonymous) -> str:
    2163        return self.func(expression.name, *expression.expressions)
    2164
    2165    def paren_sql(self, expression: exp.Paren) -> str:
    2166        if isinstance(expression.unnest(), exp.Select):
    2167            sql = self.wrap(expression)
    2168        else:
    2169            sql = self.seg(self.indent(self.sql(expression, "this")), sep="")
    2170            sql = f"({sql}{self.seg(')', sep='')}"
    2171
    2172        return self.prepend_ctes(expression, sql)
    2173
    2174    def neg_sql(self, expression: exp.Neg) -> str:
    2175        # This makes sure we don't convert "- - 5" to "--5", which is a comment
    2176        this_sql = self.sql(expression, "this")
    2177        sep = " " if this_sql[0] == "-" else ""
    2178        return f"-{sep}{this_sql}"
    2179
    2180    def not_sql(self, expression: exp.Not) -> str:
    2181        return f"NOT {self.sql(expression, 'this')}"
    2182
    2183    def alias_sql(self, expression: exp.Alias) -> str:
    2184        alias = self.sql(expression, "alias")
    2185        alias = f" AS {alias}" if alias else ""
    2186        return f"{self.sql(expression, 'this')}{alias}"
    2187
    2188    def aliases_sql(self, expression: exp.Aliases) -> str:
    2189        return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})"
    2190
    2191    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    2192        this = self.sql(expression, "this")
    2193        zone = self.sql(expression, "zone")
    2194        return f"{this} AT TIME ZONE {zone}"
    2195
    2196    def add_sql(self, expression: exp.Add) -> str:
    2197        return self.binary(expression, "+")
    2198
    2199    def and_sql(self, expression: exp.And) -> str:
    2200        return self.connector_sql(expression, "AND")
    2201
    2202    def xor_sql(self, expression: exp.Xor) -> str:
    2203        return self.connector_sql(expression, "XOR")
    2204
    2205    def connector_sql(self, expression: exp.Connector, op: str) -> str:
    2206        if not self.pretty:
    2207            return self.binary(expression, op)
    2208
    2209        sqls = tuple(
    2210            self.maybe_comment(self.sql(e), e, e.parent.comments or []) if i != 1 else self.sql(e)
    2211            for i, e in enumerate(expression.flatten(unnest=False))
    2212        )
    2213
    2214        sep = "\n" if self.text_width(sqls) > self.max_text_width else " "
    2215        return f"{sep}{op} ".join(sqls)
    2216
    2217    def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str:
    2218        return self.binary(expression, "&")
    2219
    2220    def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str:
    2221        return self.binary(expression, "<<")
    2222
    2223    def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str:
    2224        return f"~{self.sql(expression, 'this')}"
    2225
    2226    def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str:
    2227        return self.binary(expression, "|")
    2228
    2229    def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str:
    2230        return self.binary(expression, ">>")
    2231
    2232    def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str:
    2233        return self.binary(expression, "^")
    2234
    2235    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    2236        format_sql = self.sql(expression, "format")
    2237        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    2238        return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS {self.sql(expression, 'to')}{format_sql})"
    2239
    2240    def currentdate_sql(self, expression: exp.CurrentDate) -> str:
    2241        zone = self.sql(expression, "this")
    2242        return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE"
    2243
    2244    def collate_sql(self, expression: exp.Collate) -> str:
    2245        return self.binary(expression, "COLLATE")
    2246
    2247    def command_sql(self, expression: exp.Command) -> str:
    2248        return f"{self.sql(expression, 'this').upper()} {expression.text('expression').strip()}"
    2249
    2250    def comment_sql(self, expression: exp.Comment) -> str:
    2251        this = self.sql(expression, "this")
    2252        kind = expression.args["kind"]
    2253        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    2254        expression_sql = self.sql(expression, "expression")
    2255        return f"COMMENT{exists_sql}ON {kind} {this} IS {expression_sql}"
    2256
    2257    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    2258        this = self.sql(expression, "this")
    2259        delete = " DELETE" if expression.args.get("delete") else ""
    2260        recompress = self.sql(expression, "recompress")
    2261        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    2262        to_disk = self.sql(expression, "to_disk")
    2263        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    2264        to_volume = self.sql(expression, "to_volume")
    2265        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    2266        return f"{this}{delete}{recompress}{to_disk}{to_volume}"
    2267
    2268    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    2269        where = self.sql(expression, "where")
    2270        group = self.sql(expression, "group")
    2271        aggregates = self.expressions(expression, key="aggregates")
    2272        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    2273
    2274        if not (where or group or aggregates) and len(expression.expressions) == 1:
    2275            return f"TTL {self.expressions(expression, flat=True)}"
    2276
    2277        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"
    2278
    2279    def transaction_sql(self, expression: exp.Transaction) -> str:
    2280        return "BEGIN"
    2281
    2282    def commit_sql(self, expression: exp.Commit) -> str:
    2283        chain = expression.args.get("chain")
    2284        if chain is not None:
    2285            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    2286
    2287        return f"COMMIT{chain or ''}"
    2288
    2289    def rollback_sql(self, expression: exp.Rollback) -> str:
    2290        savepoint = expression.args.get("savepoint")
    2291        savepoint = f" TO {savepoint}" if savepoint else ""
    2292        return f"ROLLBACK{savepoint}"
    2293
    2294    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    2295        this = self.sql(expression, "this")
    2296
    2297        dtype = self.sql(expression, "dtype")
    2298        if dtype:
    2299            collate = self.sql(expression, "collate")
    2300            collate = f" COLLATE {collate}" if collate else ""
    2301            using = self.sql(expression, "using")
    2302            using = f" USING {using}" if using else ""
    2303            return f"ALTER COLUMN {this} TYPE {dtype}{collate}{using}"
    2304
    2305        default = self.sql(expression, "default")
    2306        if default:
    2307            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    2308
    2309        if not expression.args.get("drop"):
    2310            self.unsupported("Unsupported ALTER COLUMN syntax")
    2311
    2312        return f"ALTER COLUMN {this} DROP DEFAULT"
    2313
    2314    def renametable_sql(self, expression: exp.RenameTable) -> str:
    2315        if not self.RENAME_TABLE_WITH_DB:
    2316            # Remove db from tables
    2317            expression = expression.transform(
    2318                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    2319            )
    2320        this = self.sql(expression, "this")
    2321        return f"RENAME TO {this}"
    2322
    2323    def altertable_sql(self, expression: exp.AlterTable) -> str:
    2324        actions = expression.args["actions"]
    2325
    2326        if isinstance(actions[0], exp.ColumnDef):
    2327            if self.ALTER_TABLE_ADD_COLUMN_KEYWORD:
    2328                actions = self.expressions(
    2329                    expression,
    2330                    key="actions",
    2331                    prefix="ADD COLUMN ",
    2332                )
    2333            else:
    2334                actions = f"ADD {self.expressions(expression, key='actions')}"
    2335        elif isinstance(actions[0], exp.Schema):
    2336            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    2337        elif isinstance(actions[0], exp.Delete):
    2338            actions = self.expressions(expression, key="actions", flat=True)
    2339        else:
    2340            actions = self.expressions(expression, key="actions")
    2341
    2342        exists = " IF EXISTS" if expression.args.get("exists") else ""
    2343        only = " ONLY" if expression.args.get("only") else ""
    2344        return f"ALTER TABLE{exists}{only} {self.sql(expression, 'this')} {actions}"
    2345
    2346    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    2347        expressions = self.expressions(expression)
    2348        exists = " IF EXISTS " if expression.args.get("exists") else " "
    2349        return f"DROP{exists}{expressions}"
    2350
    2351    def addconstraint_sql(self, expression: exp.AddConstraint) -> str:
    2352        this = self.sql(expression, "this")
    2353        expression_ = self.sql(expression, "expression")
    2354        add_constraint = f"ADD CONSTRAINT {this}" if this else "ADD"
    2355
    2356        enforced = expression.args.get("enforced")
    2357        if enforced is not None:
    2358            return f"{add_constraint} CHECK ({expression_}){' ENFORCED' if enforced else ''}"
    2359
    2360        return f"{add_constraint} {expression_}"
    2361
    2362    def distinct_sql(self, expression: exp.Distinct) -> str:
    2363        this = self.expressions(expression, flat=True)
    2364        this = f" {this}" if this else ""
    2365
    2366        on = self.sql(expression, "on")
    2367        on = f" ON {on}" if on else ""
    2368        return f"DISTINCT{this}{on}"
    2369
    2370    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
    2371        return f"{self.sql(expression, 'this')} IGNORE NULLS"
    2372
    2373    def respectnulls_sql(self, expression: exp.RespectNulls) -> str:
    2374        return f"{self.sql(expression, 'this')} RESPECT NULLS"
    2375
    2376    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    2377        return self.sql(
    2378            exp.Cast(
    2379                this=exp.Div(this=expression.this.copy(), expression=expression.expression.copy()),
    2380                to=exp.DataType(this=exp.DataType.Type.INT),
    2381            )
    2382        )
    2383
    2384    def dpipe_sql(self, expression: exp.DPipe) -> str:
    2385        return self.binary(expression, "||")
    2386
    2387    def safedpipe_sql(self, expression: exp.SafeDPipe) -> str:
    2388        if self.STRICT_STRING_CONCAT:
    2389            return self.func("CONCAT", *(exp.cast(e, "text") for e in expression.flatten()))
    2390        return self.dpipe_sql(expression)
    2391
    2392    def div_sql(self, expression: exp.Div) -> str:
    2393        return self.binary(expression, "/")
    2394
    2395    def overlaps_sql(self, expression: exp.Overlaps) -> str:
    2396        return self.binary(expression, "OVERLAPS")
    2397
    2398    def distance_sql(self, expression: exp.Distance) -> str:
    2399        return self.binary(expression, "<->")
    2400
    2401    def dot_sql(self, expression: exp.Dot) -> str:
    2402        return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}"
    2403
    2404    def eq_sql(self, expression: exp.EQ) -> str:
    2405        return self.binary(expression, "=")
    2406
    2407    def escape_sql(self, expression: exp.Escape) -> str:
    2408        return self.binary(expression, "ESCAPE")
    2409
    2410    def glob_sql(self, expression: exp.Glob) -> str:
    2411        return self.binary(expression, "GLOB")
    2412
    2413    def gt_sql(self, expression: exp.GT) -> str:
    2414        return self.binary(expression, ">")
    2415
    2416    def gte_sql(self, expression: exp.GTE) -> str:
    2417        return self.binary(expression, ">=")
    2418
    2419    def ilike_sql(self, expression: exp.ILike) -> str:
    2420        return self.binary(expression, "ILIKE")
    2421
    2422    def ilikeany_sql(self, expression: exp.ILikeAny) -> str:
    2423        return self.binary(expression, "ILIKE ANY")
    2424
    2425    def is_sql(self, expression: exp.Is) -> str:
    2426        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    2427            return self.sql(
    2428                expression.this if expression.expression.this else exp.not_(expression.this)
    2429            )
    2430        return self.binary(expression, "IS")
    2431
    2432    def like_sql(self, expression: exp.Like) -> str:
    2433        return self.binary(expression, "LIKE")
    2434
    2435    def likeany_sql(self, expression: exp.LikeAny) -> str:
    2436        return self.binary(expression, "LIKE ANY")
    2437
    2438    def similarto_sql(self, expression: exp.SimilarTo) -> str:
    2439        return self.binary(expression, "SIMILAR TO")
    2440
    2441    def lt_sql(self, expression: exp.LT) -> str:
    2442        return self.binary(expression, "<")
    2443
    2444    def lte_sql(self, expression: exp.LTE) -> str:
    2445        return self.binary(expression, "<=")
    2446
    2447    def mod_sql(self, expression: exp.Mod) -> str:
    2448        return self.binary(expression, "%")
    2449
    2450    def mul_sql(self, expression: exp.Mul) -> str:
    2451        return self.binary(expression, "*")
    2452
    2453    def neq_sql(self, expression: exp.NEQ) -> str:
    2454        return self.binary(expression, "<>")
    2455
    2456    def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str:
    2457        return self.binary(expression, "IS NOT DISTINCT FROM")
    2458
    2459    def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str:
    2460        return self.binary(expression, "IS DISTINCT FROM")
    2461
    2462    def or_sql(self, expression: exp.Or) -> str:
    2463        return self.connector_sql(expression, "OR")
    2464
    2465    def slice_sql(self, expression: exp.Slice) -> str:
    2466        return self.binary(expression, ":")
    2467
    2468    def sub_sql(self, expression: exp.Sub) -> str:
    2469        return self.binary(expression, "-")
    2470
    2471    def trycast_sql(self, expression: exp.TryCast) -> str:
    2472        return self.cast_sql(expression, safe_prefix="TRY_")
    2473
    2474    def use_sql(self, expression: exp.Use) -> str:
    2475        kind = self.sql(expression, "kind")
    2476        kind = f" {kind}" if kind else ""
    2477        this = self.sql(expression, "this")
    2478        this = f" {this}" if this else ""
    2479        return f"USE{kind}{this}"
    2480
    2481    def binary(self, expression: exp.Binary, op: str) -> str:
    2482        op = self.maybe_comment(op, comments=expression.comments)
    2483        return f"{self.sql(expression, 'this')} {op} {self.sql(expression, 'expression')}"
    2484
    2485    def function_fallback_sql(self, expression: exp.Func) -> str:
    2486        args = []
    2487
    2488        for key in expression.arg_types:
    2489            arg_value = expression.args.get(key)
    2490
    2491            if isinstance(arg_value, list):
    2492                for value in arg_value:
    2493                    args.append(value)
    2494            elif arg_value is not None:
    2495                args.append(arg_value)
    2496
    2497        if self.normalize_functions:
    2498            name = expression.sql_name()
    2499        else:
    2500            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
    2501
    2502        return self.func(name, *args)
    2503
    2504    def func(
    2505        self,
    2506        name: str,
    2507        *args: t.Optional[exp.Expression | str],
    2508        prefix: str = "(",
    2509        suffix: str = ")",
    2510    ) -> str:
    2511        return f"{self.normalize_func(name)}{prefix}{self.format_args(*args)}{suffix}"
    2512
    2513    def format_args(self, *args: t.Optional[str | exp.Expression]) -> str:
    2514        arg_sqls = tuple(self.sql(arg) for arg in args if arg is not None)
    2515        if self.pretty and self.text_width(arg_sqls) > self.max_text_width:
    2516            return self.indent("\n" + f",\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True)
    2517        return ", ".join(arg_sqls)
    2518
    2519    def text_width(self, args: t.Iterable) -> int:
    2520        return sum(len(arg) for arg in args)
    2521
    2522    def format_time(self, expression: exp.Expression) -> t.Optional[str]:
    2523        return format_time(
    2524            self.sql(expression, "format"), self.INVERSE_TIME_MAPPING, self.INVERSE_TIME_TRIE
    2525        )
    2526
    2527    def expressions(
    2528        self,
    2529        expression: t.Optional[exp.Expression] = None,
    2530        key: t.Optional[str] = None,
    2531        sqls: t.Optional[t.List[str]] = None,
    2532        flat: bool = False,
    2533        indent: bool = True,
    2534        skip_first: bool = False,
    2535        sep: str = ", ",
    2536        prefix: str = "",
    2537    ) -> str:
    2538        expressions = expression.args.get(key or "expressions") if expression else sqls
    2539
    2540        if not expressions:
    2541            return ""
    2542
    2543        if flat:
    2544            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
    2545
    2546        num_sqls = len(expressions)
    2547
    2548        # These are calculated once in case we have the leading_comma / pretty option set, correspondingly
    2549        pad = " " * self.pad
    2550        stripped_sep = sep.strip()
    2551
    2552        result_sqls = []
    2553        for i, e in enumerate(expressions):
    2554            sql = self.sql(e, comment=False)
    2555            if not sql:
    2556                continue
    2557
    2558            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    2559
    2560            if self.pretty:
    2561                if self.leading_comma:
    2562                    result_sqls.append(f"{sep if i > 0 else pad}{prefix}{sql}{comments}")
    2563                else:
    2564                    result_sqls.append(
    2565                        f"{prefix}{sql}{stripped_sep if i + 1 < num_sqls else ''}{comments}"
    2566                    )
    2567            else:
    2568                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    2569
    2570        result_sql = "\n".join(result_sqls) if self.pretty else "".join(result_sqls)
    2571        return self.indent(result_sql, skip_first=skip_first) if indent else result_sql
    2572
    2573    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    2574        flat = flat or isinstance(expression.parent, exp.Properties)
    2575        expressions_sql = self.expressions(expression, flat=flat)
    2576        if flat:
    2577            return f"{op} {expressions_sql}"
    2578        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"
    2579
    2580    def naked_property(self, expression: exp.Property) -> str:
    2581        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    2582        if not property_name:
    2583            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    2584        return f"{property_name} {self.sql(expression, 'this')}"
    2585
    2586    def set_operation(self, expression: exp.Expression, op: str) -> str:
    2587        this = self.sql(expression, "this")
    2588        op = self.seg(op)
    2589        return self.query_modifiers(
    2590            expression, f"{this}{op}{self.sep()}{self.sql(expression, 'expression')}"
    2591        )
    2592
    2593    def tag_sql(self, expression: exp.Tag) -> str:
    2594        return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}"
    2595
    2596    def token_sql(self, token_type: TokenType) -> str:
    2597        return self.TOKEN_MAPPING.get(token_type, token_type.name)
    2598
    2599    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    2600        this = self.sql(expression, "this")
    2601        expressions = self.no_identify(self.expressions, expression)
    2602        expressions = (
    2603            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    2604        )
    2605        return f"{this}{expressions}"
    2606
    2607    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    2608        this = self.sql(expression, "this")
    2609        expressions = self.expressions(expression, flat=True)
    2610        return f"{this}({expressions})"
    2611
    2612    def kwarg_sql(self, expression: exp.Kwarg) -> str:
    2613        return self.binary(expression, "=>")
    2614
    2615    def when_sql(self, expression: exp.When) -> str:
    2616        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    2617        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    2618        condition = self.sql(expression, "condition")
    2619        condition = f" AND {condition}" if condition else ""
    2620
    2621        then_expression = expression.args.get("then")
    2622        if isinstance(then_expression, exp.Insert):
    2623            then = f"INSERT {self.sql(then_expression, 'this')}"
    2624            if "expression" in then_expression.args:
    2625                then += f" VALUES {self.sql(then_expression, 'expression')}"
    2626        elif isinstance(then_expression, exp.Update):
    2627            if isinstance(then_expression.args.get("expressions"), exp.Star):
    2628                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    2629            else:
    2630                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    2631        else:
    2632            then = self.sql(then_expression)
    2633        return f"WHEN {matched}{source}{condition} THEN {then}"
    2634
    2635    def merge_sql(self, expression: exp.Merge) -> str:
    2636        table = expression.this
    2637        table_alias = ""
    2638
    2639        hints = table.args.get("hints")
    2640        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
    2641            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
    2642            table = table.copy()
    2643            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
    2644
    2645        this = self.sql(table)
    2646        using = f"USING {self.sql(expression, 'using')}"
    2647        on = f"ON {self.sql(expression, 'on')}"
    2648        expressions = self.expressions(expression, sep=" ")
    2649
    2650        return f"MERGE INTO {this}{table_alias} {using} {on} {expressions}"
    2651
    2652    def tochar_sql(self, expression: exp.ToChar) -> str:
    2653        if expression.args.get("format"):
    2654            self.unsupported("Format argument unsupported for TO_CHAR/TO_VARCHAR function")
    2655
    2656        return self.sql(exp.cast(expression.this, "text"))
    2657
    2658    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    2659        this = self.sql(expression, "this")
    2660        kind = self.sql(expression, "kind")
    2661        settings_sql = self.expressions(expression, key="settings", sep=" ")
    2662        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    2663        return f"{this}({kind}{args})"
    2664
    2665    def dictrange_sql(self, expression: exp.DictRange) -> str:
    2666        this = self.sql(expression, "this")
    2667        max = self.sql(expression, "max")
    2668        min = self.sql(expression, "min")
    2669        return f"{this}(MIN {min} MAX {max})"
    2670
    2671    def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str:
    2672        return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}"
    2673
    2674    def oncluster_sql(self, expression: exp.OnCluster) -> str:
    2675        return ""
    2676
    2677    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    2678        expressions = self.expressions(expression, key="expressions", flat=True)
    2679        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    2680        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    2681        buckets = self.sql(expression, "buckets")
    2682        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"
    2683
    2684    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    2685        this = self.sql(expression, "this")
    2686        having = self.sql(expression, "having")
    2687
    2688        if having:
    2689            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    2690
    2691        return self.func("ANY_VALUE", this)
    2692
    2693    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
    2694        transform = self.func("TRANSFORM", *expression.expressions)
    2695        row_format_before = self.sql(expression, "row_format_before")
    2696        row_format_before = f" {row_format_before}" if row_format_before else ""
    2697        record_writer = self.sql(expression, "record_writer")
    2698        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
    2699        using = f" USING {self.sql(expression, 'command_script')}"
    2700        schema = self.sql(expression, "schema")
    2701        schema = f" AS {schema}" if schema else ""
    2702        row_format_after = self.sql(expression, "row_format_after")
    2703        row_format_after = f" {row_format_after}" if row_format_after else ""
    2704        record_reader = self.sql(expression, "record_reader")
    2705        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
    2706        return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}"
    2707
    2708    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
    2709        key_block_size = self.sql(expression, "key_block_size")
    2710        if key_block_size:
    2711            return f"KEY_BLOCK_SIZE = {key_block_size}"
    2712
    2713        using = self.sql(expression, "using")
    2714        if using:
    2715            return f"USING {using}"
    2716
    2717        parser = self.sql(expression, "parser")
    2718        if parser:
    2719            return f"WITH PARSER {parser}"
    2720
    2721        comment = self.sql(expression, "comment")
    2722        if comment:
    2723            return f"COMMENT {comment}"
    2724
    2725        visible = expression.args.get("visible")
    2726        if visible is not None:
    2727            return "VISIBLE" if visible else "INVISIBLE"
    2728
    2729        engine_attr = self.sql(expression, "engine_attr")
    2730        if engine_attr:
    2731            return f"ENGINE_ATTRIBUTE = {engine_attr}"
    2732
    2733        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
    2734        if secondary_engine_attr:
    2735            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
    2736
    2737        self.unsupported("Unsupported index constraint option.")
    2738        return ""
    2739
    2740    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
    2741        kind = self.sql(expression, "kind")
    2742        kind = f"{kind} INDEX" if kind else "INDEX"
    2743        this = self.sql(expression, "this")
    2744        this = f" {this}" if this else ""
    2745        index_type = self.sql(expression, "index_type")
    2746        index_type = f" USING {index_type}" if index_type else ""
    2747        schema = self.sql(expression, "schema")
    2748        schema = f" {schema}" if schema else ""
    2749        options = self.expressions(expression, key="options", sep=" ")
    2750        options = f" {options}" if options else ""
    2751        return f"{kind}{this}{index_type}{schema}{options}"
    2752
    2753    def nvl2_sql(self, expression: exp.Nvl2) -> str:
    2754        if self.NVL2_SUPPORTED:
    2755            return self.function_fallback_sql(expression)
    2756
    2757        case = exp.Case().when(
    2758            expression.this.is_(exp.null()).not_(copy=False),
    2759            expression.args["true"].copy(),
    2760            copy=False,
    2761        )
    2762        else_cond = expression.args.get("false")
    2763        if else_cond:
    2764            case.else_(else_cond.copy(), copy=False)
    2765
    2766        return self.sql(case)
    2767
    2768    def comprehension_sql(self, expression: exp.Comprehension) -> str:
    2769        this = self.sql(expression, "this")
    2770        expr = self.sql(expression, "expression")
    2771        iterator = self.sql(expression, "iterator")
    2772        condition = self.sql(expression, "condition")
    2773        condition = f" IF {condition}" if condition else ""
    2774        return f"{this} FOR {expr} IN {iterator}{condition}"
    2775
    2776    def columnprefix_sql(self, expression: exp.ColumnPrefix) -> str:
    2777        return f"{self.sql(expression, 'this')}({self.sql(expression, 'expression')})"
    2778
    2779
    2780def cached_generator(
    2781    cache: t.Optional[t.Dict[int, str]] = None
    2782) -> t.Callable[[exp.Expression], str]:
    2783    """Returns a cached generator."""
    2784    cache = {} if cache is None else cache
    2785    generator = Generator(normalize=True, identify="safe")
    2786    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        index_type = expression.args.get("index_type")
     710        index_type = f" USING {index_type}" if index_type else ""
     711        return f"UNIQUE{this}{index_type}"
     712
     713    def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
     714        return self.sql(expression, "this")
     715
     716    def create_sql(self, expression: exp.Create) -> str:
     717        kind = self.sql(expression, "kind").upper()
     718        properties = expression.args.get("properties")
     719        properties_locs = self.locate_properties(properties) if properties else defaultdict()
     720
     721        this = self.createable_sql(expression, properties_locs)
     722
     723        properties_sql = ""
     724        if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get(
     725            exp.Properties.Location.POST_WITH
     726        ):
     727            properties_sql = self.sql(
     728                exp.Properties(
     729                    expressions=[
     730                        *properties_locs[exp.Properties.Location.POST_SCHEMA],
     731                        *properties_locs[exp.Properties.Location.POST_WITH],
     732                    ]
     733                )
     734            )
     735
     736        begin = " BEGIN" if expression.args.get("begin") else ""
     737        expression_sql = self.sql(expression, "expression")
     738        if expression_sql:
     739            expression_sql = f"{begin}{self.sep()}{expression_sql}"
     740
     741            if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return):
     742                if properties_locs.get(exp.Properties.Location.POST_ALIAS):
     743                    postalias_props_sql = self.properties(
     744                        exp.Properties(
     745                            expressions=properties_locs[exp.Properties.Location.POST_ALIAS]
     746                        ),
     747                        wrapped=False,
     748                    )
     749                    expression_sql = f" AS {postalias_props_sql}{expression_sql}"
     750                else:
     751                    expression_sql = f" AS{expression_sql}"
     752
     753        postindex_props_sql = ""
     754        if properties_locs.get(exp.Properties.Location.POST_INDEX):
     755            postindex_props_sql = self.properties(
     756                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]),
     757                wrapped=False,
     758                prefix=" ",
     759            )
     760
     761        indexes = self.expressions(expression, key="indexes", indent=False, sep=" ")
     762        indexes = f" {indexes}" if indexes else ""
     763        index_sql = indexes + postindex_props_sql
     764
     765        replace = " OR REPLACE" if expression.args.get("replace") else ""
     766        unique = " UNIQUE" if expression.args.get("unique") else ""
     767
     768        postcreate_props_sql = ""
     769        if properties_locs.get(exp.Properties.Location.POST_CREATE):
     770            postcreate_props_sql = self.properties(
     771                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]),
     772                sep=" ",
     773                prefix=" ",
     774                wrapped=False,
     775            )
     776
     777        modifiers = "".join((replace, unique, postcreate_props_sql))
     778
     779        postexpression_props_sql = ""
     780        if properties_locs.get(exp.Properties.Location.POST_EXPRESSION):
     781            postexpression_props_sql = self.properties(
     782                exp.Properties(
     783                    expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION]
     784                ),
     785                sep=" ",
     786                prefix=" ",
     787                wrapped=False,
     788            )
     789
     790        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
     791        no_schema_binding = (
     792            " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else ""
     793        )
     794
     795        clone = self.sql(expression, "clone")
     796        clone = f" {clone}" if clone else ""
     797
     798        expression_sql = f"CREATE{modifiers} {kind}{exists_sql} {this}{properties_sql}{expression_sql}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}"
     799        return self.prepend_ctes(expression, expression_sql)
     800
     801    def clone_sql(self, expression: exp.Clone) -> str:
     802        this = self.sql(expression, "this")
     803        shallow = "SHALLOW " if expression.args.get("shallow") else ""
     804        this = f"{shallow}CLONE {this}"
     805        when = self.sql(expression, "when")
     806
     807        if when:
     808            kind = self.sql(expression, "kind")
     809            expr = self.sql(expression, "expression")
     810            return f"{this} {when} ({kind} => {expr})"
     811
     812        return this
     813
     814    def describe_sql(self, expression: exp.Describe) -> str:
     815        return f"DESCRIBE {self.sql(expression, 'this')}"
     816
     817    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
     818        with_ = self.sql(expression, "with")
     819        if with_:
     820            sql = f"{with_}{self.sep()}{sql}"
     821        return sql
     822
     823    def with_sql(self, expression: exp.With) -> str:
     824        sql = self.expressions(expression, flat=True)
     825        recursive = "RECURSIVE " if expression.args.get("recursive") else ""
     826
     827        return f"WITH {recursive}{sql}"
     828
     829    def cte_sql(self, expression: exp.CTE) -> str:
     830        alias = self.sql(expression, "alias")
     831        return f"{alias} AS {self.wrap(expression)}"
     832
     833    def tablealias_sql(self, expression: exp.TableAlias) -> str:
     834        alias = self.sql(expression, "this")
     835        columns = self.expressions(expression, key="columns", flat=True)
     836        columns = f"({columns})" if columns else ""
     837        return f"{alias}{columns}"
     838
     839    def bitstring_sql(self, expression: exp.BitString) -> str:
     840        this = self.sql(expression, "this")
     841        if self.BIT_START:
     842            return f"{self.BIT_START}{this}{self.BIT_END}"
     843        return f"{int(this, 2)}"
     844
     845    def hexstring_sql(self, expression: exp.HexString) -> str:
     846        this = self.sql(expression, "this")
     847        if self.HEX_START:
     848            return f"{self.HEX_START}{this}{self.HEX_END}"
     849        return f"{int(this, 16)}"
     850
     851    def bytestring_sql(self, expression: exp.ByteString) -> str:
     852        this = self.sql(expression, "this")
     853        if self.BYTE_START:
     854            return f"{self.BYTE_START}{this}{self.BYTE_END}"
     855        return this
     856
     857    def rawstring_sql(self, expression: exp.RawString) -> str:
     858        string = self.escape_str(expression.this.replace("\\", "\\\\"))
     859        return f"{self.QUOTE_START}{string}{self.QUOTE_END}"
     860
     861    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
     862        this = self.sql(expression, "this")
     863        specifier = self.sql(expression, "expression")
     864        specifier = f" {specifier}" if specifier else ""
     865        return f"{this}{specifier}"
     866
     867    def datatype_sql(self, expression: exp.DataType) -> str:
     868        type_value = expression.this
     869
     870        if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"):
     871            type_sql = self.sql(expression, "kind")
     872        else:
     873            type_sql = (
     874                self.TYPE_MAPPING.get(type_value, type_value.value)
     875                if isinstance(type_value, exp.DataType.Type)
     876                else type_value
     877            )
     878
     879        nested = ""
     880        interior = self.expressions(expression, flat=True)
     881        values = ""
     882
     883        if interior:
     884            if expression.args.get("nested"):
     885                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
     886                if expression.args.get("values") is not None:
     887                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
     888                    values = self.expressions(expression, key="values", flat=True)
     889                    values = f"{delimiters[0]}{values}{delimiters[1]}"
     890            elif type_value == exp.DataType.Type.INTERVAL:
     891                nested = f" {interior}"
     892            else:
     893                nested = f"({interior})"
     894
     895        type_sql = f"{type_sql}{nested}{values}"
     896        if self.TZ_TO_WITH_TIME_ZONE and type_value in (
     897            exp.DataType.Type.TIMETZ,
     898            exp.DataType.Type.TIMESTAMPTZ,
     899        ):
     900            type_sql = f"{type_sql} WITH TIME ZONE"
     901
     902        return type_sql
     903
     904    def directory_sql(self, expression: exp.Directory) -> str:
     905        local = "LOCAL " if expression.args.get("local") else ""
     906        row_format = self.sql(expression, "row_format")
     907        row_format = f" {row_format}" if row_format else ""
     908        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"
     909
     910    def delete_sql(self, expression: exp.Delete) -> str:
     911        this = self.sql(expression, "this")
     912        this = f" FROM {this}" if this else ""
     913        using = self.sql(expression, "using")
     914        using = f" USING {using}" if using else ""
     915        where = self.sql(expression, "where")
     916        returning = self.sql(expression, "returning")
     917        limit = self.sql(expression, "limit")
     918        tables = self.expressions(expression, key="tables")
     919        tables = f" {tables}" if tables else ""
     920        if self.RETURNING_END:
     921            expression_sql = f"{this}{using}{where}{returning}{limit}"
     922        else:
     923            expression_sql = f"{returning}{this}{using}{where}{limit}"
     924        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")
     925
     926    def drop_sql(self, expression: exp.Drop) -> str:
     927        this = self.sql(expression, "this")
     928        kind = expression.args["kind"]
     929        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
     930        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
     931        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
     932        cascade = " CASCADE" if expression.args.get("cascade") else ""
     933        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
     934        purge = " PURGE" if expression.args.get("purge") else ""
     935        return (
     936            f"DROP{temporary}{materialized} {kind}{exists_sql}{this}{cascade}{constraints}{purge}"
     937        )
     938
     939    def except_sql(self, expression: exp.Except) -> str:
     940        return self.prepend_ctes(
     941            expression,
     942            self.set_operation(expression, self.except_op(expression)),
     943        )
     944
     945    def except_op(self, expression: exp.Except) -> str:
     946        return f"EXCEPT{'' if expression.args.get('distinct') else ' ALL'}"
     947
     948    def fetch_sql(self, expression: exp.Fetch) -> str:
     949        direction = expression.args.get("direction")
     950        direction = f" {direction.upper()}" if direction else ""
     951        count = expression.args.get("count")
     952        count = f" {count}" if count else ""
     953        if expression.args.get("percent"):
     954            count = f"{count} PERCENT"
     955        with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY"
     956        return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}"
     957
     958    def filter_sql(self, expression: exp.Filter) -> str:
     959        this = self.sql(expression, "this")
     960        where = self.sql(expression, "expression").strip()
     961        return f"{this} FILTER({where})"
     962
     963    def hint_sql(self, expression: exp.Hint) -> str:
     964        if not self.QUERY_HINTS:
     965            self.unsupported("Hints are not supported")
     966            return ""
     967
     968        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"
     969
     970    def index_sql(self, expression: exp.Index) -> str:
     971        unique = "UNIQUE " if expression.args.get("unique") else ""
     972        primary = "PRIMARY " if expression.args.get("primary") else ""
     973        amp = "AMP " if expression.args.get("amp") else ""
     974        name = self.sql(expression, "this")
     975        name = f"{name} " if name else ""
     976        table = self.sql(expression, "table")
     977        table = f"{self.INDEX_ON} {table}" if table else ""
     978        using = self.sql(expression, "using")
     979        using = f" USING {using} " if using else ""
     980        index = "INDEX " if not table else ""
     981        columns = self.expressions(expression, key="columns", flat=True)
     982        columns = f"({columns})" if columns else ""
     983        partition_by = self.expressions(expression, key="partition_by", flat=True)
     984        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
     985        return f"{unique}{primary}{amp}{index}{name}{table}{using}{columns}{partition_by}"
     986
     987    def identifier_sql(self, expression: exp.Identifier) -> str:
     988        text = expression.name
     989        lower = text.lower()
     990        text = lower if self.normalize and not expression.quoted else text
     991        text = text.replace(self.IDENTIFIER_END, self._escaped_identifier_end)
     992        if (
     993            expression.quoted
     994            or self.can_identify(text, self.identify)
     995            or lower in self.RESERVED_KEYWORDS
     996            or (not self.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
     997        ):
     998            text = f"{self.IDENTIFIER_START}{text}{self.IDENTIFIER_END}"
     999        return text
    1000
    1001    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    1002        input_format = self.sql(expression, "input_format")
    1003        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    1004        output_format = self.sql(expression, "output_format")
    1005        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    1006        return self.sep().join((input_format, output_format))
    1007
    1008    def national_sql(self, expression: exp.National, prefix: str = "N") -> str:
    1009        string = self.sql(exp.Literal.string(expression.name))
    1010        return f"{prefix}{string}"
    1011
    1012    def partition_sql(self, expression: exp.Partition) -> str:
    1013        return f"PARTITION({self.expressions(expression, flat=True)})"
    1014
    1015    def properties_sql(self, expression: exp.Properties) -> str:
    1016        root_properties = []
    1017        with_properties = []
    1018
    1019        for p in expression.expressions:
    1020            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1021            if p_loc == exp.Properties.Location.POST_WITH:
    1022                with_properties.append(p.copy())
    1023            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    1024                root_properties.append(p.copy())
    1025
    1026        return self.root_properties(
    1027            exp.Properties(expressions=root_properties)
    1028        ) + self.with_properties(exp.Properties(expressions=with_properties))
    1029
    1030    def root_properties(self, properties: exp.Properties) -> str:
    1031        if properties.expressions:
    1032            return self.sep() + self.expressions(properties, indent=False, sep=" ")
    1033        return ""
    1034
    1035    def properties(
    1036        self,
    1037        properties: exp.Properties,
    1038        prefix: str = "",
    1039        sep: str = ", ",
    1040        suffix: str = "",
    1041        wrapped: bool = True,
    1042    ) -> str:
    1043        if properties.expressions:
    1044            expressions = self.expressions(properties, sep=sep, indent=False)
    1045            if expressions:
    1046                expressions = self.wrap(expressions) if wrapped else expressions
    1047                return f"{prefix}{' ' if prefix and prefix != ' ' else ''}{expressions}{suffix}"
    1048        return ""
    1049
    1050    def with_properties(self, properties: exp.Properties) -> str:
    1051        return self.properties(properties, prefix=self.seg("WITH"))
    1052
    1053    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
    1054        properties_locs = defaultdict(list)
    1055        for p in properties.expressions:
    1056            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1057            if p_loc != exp.Properties.Location.UNSUPPORTED:
    1058                properties_locs[p_loc].append(p.copy())
    1059            else:
    1060                self.unsupported(f"Unsupported property {p.key}")
    1061
    1062        return properties_locs
    1063
    1064    def property_sql(self, expression: exp.Property) -> str:
    1065        property_cls = expression.__class__
    1066        if property_cls == exp.Property:
    1067            return f"{expression.name}={self.sql(expression, 'value')}"
    1068
    1069        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    1070        if not property_name:
    1071            self.unsupported(f"Unsupported property {expression.key}")
    1072
    1073        return f"{property_name}={self.sql(expression, 'this')}"
    1074
    1075    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
    1076        options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
    1077        options = f" {options}" if options else ""
    1078        return f"LIKE {self.sql(expression, 'this')}{options}"
    1079
    1080    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1081        no = "NO " if expression.args.get("no") else ""
    1082        protection = " PROTECTION" if expression.args.get("protection") else ""
    1083        return f"{no}FALLBACK{protection}"
    1084
    1085    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1086        no = "NO " if expression.args.get("no") else ""
    1087        local = expression.args.get("local")
    1088        local = f"{local} " if local else ""
    1089        dual = "DUAL " if expression.args.get("dual") else ""
    1090        before = "BEFORE " if expression.args.get("before") else ""
    1091        after = "AFTER " if expression.args.get("after") else ""
    1092        return f"{no}{local}{dual}{before}{after}JOURNAL"
    1093
    1094    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1095        freespace = self.sql(expression, "this")
    1096        percent = " PERCENT" if expression.args.get("percent") else ""
    1097        return f"FREESPACE={freespace}{percent}"
    1098
    1099    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1100        if expression.args.get("default"):
    1101            property = "DEFAULT"
    1102        elif expression.args.get("on"):
    1103            property = "ON"
    1104        else:
    1105            property = "OFF"
    1106        return f"CHECKSUM={property}"
    1107
    1108    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1109        if expression.args.get("no"):
    1110            return "NO MERGEBLOCKRATIO"
    1111        if expression.args.get("default"):
    1112            return "DEFAULT MERGEBLOCKRATIO"
    1113
    1114        percent = " PERCENT" if expression.args.get("percent") else ""
    1115        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"
    1116
    1117    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1118        default = expression.args.get("default")
    1119        minimum = expression.args.get("minimum")
    1120        maximum = expression.args.get("maximum")
    1121        if default or minimum or maximum:
    1122            if default:
    1123                prop = "DEFAULT"
    1124            elif minimum:
    1125                prop = "MINIMUM"
    1126            else:
    1127                prop = "MAXIMUM"
    1128            return f"{prop} DATABLOCKSIZE"
    1129        units = expression.args.get("units")
    1130        units = f" {units}" if units else ""
    1131        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"
    1132
    1133    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1134        autotemp = expression.args.get("autotemp")
    1135        always = expression.args.get("always")
    1136        default = expression.args.get("default")
    1137        manual = expression.args.get("manual")
    1138        never = expression.args.get("never")
    1139
    1140        if autotemp is not None:
    1141            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1142        elif always:
    1143            prop = "ALWAYS"
    1144        elif default:
    1145            prop = "DEFAULT"
    1146        elif manual:
    1147            prop = "MANUAL"
    1148        elif never:
    1149            prop = "NEVER"
    1150        return f"BLOCKCOMPRESSION={prop}"
    1151
    1152    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1153        no = expression.args.get("no")
    1154        no = " NO" if no else ""
    1155        concurrent = expression.args.get("concurrent")
    1156        concurrent = " CONCURRENT" if concurrent else ""
    1157
    1158        for_ = ""
    1159        if expression.args.get("for_all"):
    1160            for_ = " FOR ALL"
    1161        elif expression.args.get("for_insert"):
    1162            for_ = " FOR INSERT"
    1163        elif expression.args.get("for_none"):
    1164            for_ = " FOR NONE"
    1165        return f"WITH{no}{concurrent} ISOLATED LOADING{for_}"
    1166
    1167    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1168        kind = expression.args.get("kind")
    1169        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1170        for_or_in = expression.args.get("for_or_in")
    1171        lock_type = expression.args.get("lock_type")
    1172        override = " OVERRIDE" if expression.args.get("override") else ""
    1173        return f"LOCKING {kind}{this} {for_or_in} {lock_type}{override}"
    1174
    1175    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1176        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1177        statistics = expression.args.get("statistics")
    1178        statistics_sql = ""
    1179        if statistics is not None:
    1180            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1181        return f"{data_sql}{statistics_sql}"
    1182
    1183    def insert_sql(self, expression: exp.Insert) -> str:
    1184        overwrite = expression.args.get("overwrite")
    1185
    1186        if isinstance(expression.this, exp.Directory):
    1187            this = " OVERWRITE" if overwrite else " INTO"
    1188        else:
    1189            this = " OVERWRITE TABLE" if overwrite else " INTO"
    1190
    1191        alternative = expression.args.get("alternative")
    1192        alternative = f" OR {alternative}" if alternative else ""
    1193        ignore = " IGNORE" if expression.args.get("ignore") else ""
    1194
    1195        this = f"{this} {self.sql(expression, 'this')}"
    1196
    1197        exists = " IF EXISTS" if expression.args.get("exists") else ""
    1198        partition_sql = (
    1199            f" {self.sql(expression, 'partition')}" if expression.args.get("partition") else ""
    1200        )
    1201        where = self.sql(expression, "where")
    1202        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
    1203        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
    1204        conflict = self.sql(expression, "conflict")
    1205        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1206        returning = self.sql(expression, "returning")
    1207
    1208        if self.RETURNING_END:
    1209            expression_sql = f"{expression_sql}{conflict}{returning}"
    1210        else:
    1211            expression_sql = f"{returning}{expression_sql}{conflict}"
    1212
    1213        sql = f"INSERT{alternative}{ignore}{this}{by_name}{exists}{partition_sql}{where}{expression_sql}"
    1214        return self.prepend_ctes(expression, sql)
    1215
    1216    def intersect_sql(self, expression: exp.Intersect) -> str:
    1217        return self.prepend_ctes(
    1218            expression,
    1219            self.set_operation(expression, self.intersect_op(expression)),
    1220        )
    1221
    1222    def intersect_op(self, expression: exp.Intersect) -> str:
    1223        return f"INTERSECT{'' if expression.args.get('distinct') else ' ALL'}"
    1224
    1225    def introducer_sql(self, expression: exp.Introducer) -> str:
    1226        return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}"
    1227
    1228    def pseudotype_sql(self, expression: exp.PseudoType) -> str:
    1229        return expression.name.upper()
    1230
    1231    def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str:
    1232        return expression.name.upper()
    1233
    1234    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1235        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1236        constraint = self.sql(expression, "constraint")
    1237        if constraint:
    1238            constraint = f"ON CONSTRAINT {constraint}"
    1239        key = self.expressions(expression, key="key", flat=True)
    1240        do = "" if expression.args.get("duplicate") else " DO "
    1241        nothing = "NOTHING" if expression.args.get("nothing") else ""
    1242        expressions = self.expressions(expression, flat=True)
    1243        set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
    1244        if expressions:
    1245            expressions = f"UPDATE {set_keyword}{expressions}"
    1246        return f"{self.seg(conflict)} {constraint}{key}{do}{nothing}{expressions}"
    1247
    1248    def returning_sql(self, expression: exp.Returning) -> str:
    1249        return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}"
    1250
    1251    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1252        fields = expression.args.get("fields")
    1253        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1254        escaped = expression.args.get("escaped")
    1255        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1256        items = expression.args.get("collection_items")
    1257        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1258        keys = expression.args.get("map_keys")
    1259        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1260        lines = expression.args.get("lines")
    1261        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1262        null = expression.args.get("null")
    1263        null = f" NULL DEFINED AS {null}" if null else ""
    1264        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"
    1265
    1266    def withtablehint_sql(self, expression: exp.WithTableHint) -> str:
    1267        return f"WITH ({self.expressions(expression, flat=True)})"
    1268
    1269    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1270        this = f"{self.sql(expression, 'this')} INDEX"
    1271        target = self.sql(expression, "target")
    1272        target = f" FOR {target}" if target else ""
    1273        return f"{this}{target} ({self.expressions(expression, flat=True)})"
    1274
    1275    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1276        table = ".".join(
    1277            part
    1278            for part in [
    1279                self.sql(expression, "catalog"),
    1280                self.sql(expression, "db"),
    1281                self.sql(expression, "this"),
    1282            ]
    1283            if part
    1284        )
    1285
    1286        version = self.sql(expression, "version")
    1287        version = f" {version}" if version else ""
    1288        alias = self.sql(expression, "alias")
    1289        alias = f"{sep}{alias}" if alias else ""
    1290        hints = self.expressions(expression, key="hints", sep=" ")
    1291        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
    1292        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    1293        pivots = f" {pivots}" if pivots else ""
    1294        joins = self.expressions(expression, key="joins", sep="", skip_first=True)
    1295        laterals = self.expressions(expression, key="laterals", sep="")
    1296
    1297        return f"{table}{version}{alias}{hints}{pivots}{joins}{laterals}"
    1298
    1299    def tablesample_sql(
    1300        self, expression: exp.TableSample, seed_prefix: str = "SEED", sep=" AS "
    1301    ) -> str:
    1302        if self.ALIAS_POST_TABLESAMPLE and expression.this.alias:
    1303            table = expression.this.copy()
    1304            table.set("alias", None)
    1305            this = self.sql(table)
    1306            alias = f"{sep}{self.sql(expression.this, 'alias')}"
    1307        else:
    1308            this = self.sql(expression, "this")
    1309            alias = ""
    1310        method = self.sql(expression, "method")
    1311        method = f"{method.upper()} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    1312        numerator = self.sql(expression, "bucket_numerator")
    1313        denominator = self.sql(expression, "bucket_denominator")
    1314        field = self.sql(expression, "bucket_field")
    1315        field = f" ON {field}" if field else ""
    1316        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    1317        percent = self.sql(expression, "percent")
    1318        percent = f"{percent} PERCENT" if percent else ""
    1319        rows = self.sql(expression, "rows")
    1320        rows = f"{rows} ROWS" if rows else ""
    1321        size = self.sql(expression, "size")
    1322        if size and self.TABLESAMPLE_SIZE_IS_PERCENT:
    1323            size = f"{size} PERCENT"
    1324        seed = self.sql(expression, "seed")
    1325        seed = f" {seed_prefix} ({seed})" if seed else ""
    1326        kind = expression.args.get("kind", "TABLESAMPLE")
    1327        return f"{this} {kind} {method}({bucket}{percent}{rows}{size}){seed}{alias}"
    1328
    1329    def pivot_sql(self, expression: exp.Pivot) -> str:
    1330        expressions = self.expressions(expression, flat=True)
    1331
    1332        if expression.this:
    1333            this = self.sql(expression, "this")
    1334            on = f"{self.seg('ON')} {expressions}"
    1335            using = self.expressions(expression, key="using", flat=True)
    1336            using = f"{self.seg('USING')} {using}" if using else ""
    1337            group = self.sql(expression, "group")
    1338            return f"PIVOT {this}{on}{using}{group}"
    1339
    1340        alias = self.sql(expression, "alias")
    1341        alias = f" AS {alias}" if alias else ""
    1342        unpivot = expression.args.get("unpivot")
    1343        direction = "UNPIVOT" if unpivot else "PIVOT"
    1344        field = self.sql(expression, "field")
    1345        include_nulls = expression.args.get("include_nulls")
    1346        if include_nulls is not None:
    1347            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
    1348        else:
    1349            nulls = ""
    1350        return f"{direction}{nulls}({expressions} FOR {field}){alias}"
    1351
    1352    def version_sql(self, expression: exp.Version) -> str:
    1353        this = f"FOR {expression.name}"
    1354        kind = expression.text("kind")
    1355        expr = self.sql(expression, "expression")
    1356        return f"{this} {kind} {expr}"
    1357
    1358    def tuple_sql(self, expression: exp.Tuple) -> str:
    1359        return f"({self.expressions(expression, flat=True)})"
    1360
    1361    def update_sql(self, expression: exp.Update) -> str:
    1362        this = self.sql(expression, "this")
    1363        set_sql = self.expressions(expression, flat=True)
    1364        from_sql = self.sql(expression, "from")
    1365        where_sql = self.sql(expression, "where")
    1366        returning = self.sql(expression, "returning")
    1367        order = self.sql(expression, "order")
    1368        limit = self.sql(expression, "limit")
    1369        if self.RETURNING_END:
    1370            expression_sql = f"{from_sql}{where_sql}{returning}"
    1371        else:
    1372            expression_sql = f"{returning}{from_sql}{where_sql}"
    1373        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
    1374        return self.prepend_ctes(expression, sql)
    1375
    1376    def values_sql(self, expression: exp.Values) -> str:
    1377        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
    1378        if self.VALUES_AS_TABLE or not expression.find_ancestor(exp.From, exp.Join):
    1379            args = self.expressions(expression)
    1380            alias = self.sql(expression, "alias")
    1381            values = f"VALUES{self.seg('')}{args}"
    1382            values = (
    1383                f"({values})"
    1384                if self.WRAP_DERIVED_VALUES and (alias or isinstance(expression.parent, exp.From))
    1385                else values
    1386            )
    1387            return f"{values} AS {alias}" if alias else values
    1388
    1389        # Converts `VALUES...` expression into a series of select unions.
    1390        # Note: If you have a lot of unions then this will result in a large number of recursive statements to
    1391        # evaluate the expression. You may need to increase `sys.setrecursionlimit` to run and it can also be
    1392        # very slow.
    1393        expression = expression.copy()
    1394        column_names = expression.alias and expression.args["alias"].columns
    1395
    1396        selects = []
    1397
    1398        for i, tup in enumerate(expression.expressions):
    1399            row = tup.expressions
    1400
    1401            if i == 0 and column_names:
    1402                row = [
    1403                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
    1404                ]
    1405
    1406            selects.append(exp.Select(expressions=row))
    1407
    1408        subquery_expression: exp.Select | exp.Union = selects[0]
    1409        if len(selects) > 1:
    1410            for select in selects[1:]:
    1411                subquery_expression = exp.union(
    1412                    subquery_expression, select, distinct=False, copy=False
    1413                )
    1414
    1415        return self.subquery_sql(subquery_expression.subquery(expression.alias, copy=False))
    1416
    1417    def var_sql(self, expression: exp.Var) -> str:
    1418        return self.sql(expression, "this")
    1419
    1420    def into_sql(self, expression: exp.Into) -> str:
    1421        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    1422        unlogged = " UNLOGGED" if expression.args.get("unlogged") else ""
    1423        return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"
    1424
    1425    def from_sql(self, expression: exp.From) -> str:
    1426        return f"{self.seg('FROM')} {self.sql(expression, 'this')}"
    1427
    1428    def group_sql(self, expression: exp.Group) -> str:
    1429        group_by = self.op_expressions("GROUP BY", expression)
    1430
    1431        if expression.args.get("all"):
    1432            return f"{group_by} ALL"
    1433
    1434        grouping_sets = self.expressions(expression, key="grouping_sets", indent=False)
    1435        grouping_sets = (
    1436            f"{self.seg('GROUPING SETS')} {self.wrap(grouping_sets)}" if grouping_sets else ""
    1437        )
    1438
    1439        cube = expression.args.get("cube", [])
    1440        if seq_get(cube, 0) is True:
    1441            return f"{group_by}{self.seg('WITH CUBE')}"
    1442        else:
    1443            cube_sql = self.expressions(expression, key="cube", indent=False)
    1444            cube_sql = f"{self.seg('CUBE')} {self.wrap(cube_sql)}" if cube_sql else ""
    1445
    1446        rollup = expression.args.get("rollup", [])
    1447        if seq_get(rollup, 0) is True:
    1448            return f"{group_by}{self.seg('WITH ROLLUP')}"
    1449        else:
    1450            rollup_sql = self.expressions(expression, key="rollup", indent=False)
    1451            rollup_sql = f"{self.seg('ROLLUP')} {self.wrap(rollup_sql)}" if rollup_sql else ""
    1452
    1453        groupings = csv(
    1454            grouping_sets,
    1455            cube_sql,
    1456            rollup_sql,
    1457            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    1458            sep=self.GROUPINGS_SEP,
    1459        )
    1460
    1461        if expression.args.get("expressions") and groupings:
    1462            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    1463
    1464        return f"{group_by}{groupings}"
    1465
    1466    def having_sql(self, expression: exp.Having) -> str:
    1467        this = self.indent(self.sql(expression, "this"))
    1468        return f"{self.seg('HAVING')}{self.sep()}{this}"
    1469
    1470    def connect_sql(self, expression: exp.Connect) -> str:
    1471        start = self.sql(expression, "start")
    1472        start = self.seg(f"START WITH {start}") if start else ""
    1473        connect = self.sql(expression, "connect")
    1474        connect = self.seg(f"CONNECT BY {connect}")
    1475        return start + connect
    1476
    1477    def prior_sql(self, expression: exp.Prior) -> str:
    1478        return f"PRIOR {self.sql(expression, 'this')}"
    1479
    1480    def join_sql(self, expression: exp.Join) -> str:
    1481        op_sql = " ".join(
    1482            op
    1483            for op in (
    1484                expression.method,
    1485                "GLOBAL" if expression.args.get("global") else None,
    1486                expression.side,
    1487                expression.kind,
    1488                expression.hint if self.JOIN_HINTS else None,
    1489            )
    1490            if op
    1491        )
    1492        on_sql = self.sql(expression, "on")
    1493        using = expression.args.get("using")
    1494
    1495        if not on_sql and using:
    1496            on_sql = csv(*(self.sql(column) for column in using))
    1497
    1498        this_sql = self.sql(expression, "this")
    1499
    1500        if on_sql:
    1501            on_sql = self.indent(on_sql, skip_first=True)
    1502            space = self.seg(" " * self.pad) if self.pretty else " "
    1503            if using:
    1504                on_sql = f"{space}USING ({on_sql})"
    1505            else:
    1506                on_sql = f"{space}ON {on_sql}"
    1507        elif not op_sql:
    1508            return f", {this_sql}"
    1509
    1510        op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    1511        return f"{self.seg(op_sql)} {this_sql}{on_sql}"
    1512
    1513    def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->") -> str:
    1514        args = self.expressions(expression, flat=True)
    1515        args = f"({args})" if len(args.split(",")) > 1 else args
    1516        return f"{args} {arrow_sep} {self.sql(expression, 'this')}"
    1517
    1518    def lateral_sql(self, expression: exp.Lateral) -> str:
    1519        this = self.sql(expression, "this")
    1520
    1521        if isinstance(expression.this, exp.Subquery):
    1522            return f"LATERAL {this}"
    1523
    1524        if expression.args.get("view"):
    1525            alias = expression.args["alias"]
    1526            columns = self.expressions(alias, key="columns", flat=True)
    1527            table = f" {alias.name}" if alias.name else ""
    1528            columns = f" AS {columns}" if columns else ""
    1529            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    1530            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    1531
    1532        alias = self.sql(expression, "alias")
    1533        alias = f" AS {alias}" if alias else ""
    1534        return f"LATERAL {this}{alias}"
    1535
    1536    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    1537        this = self.sql(expression, "this")
    1538        args = ", ".join(
    1539            sql
    1540            for sql in (
    1541                self.sql(expression, "offset"),
    1542                self.sql(expression, "expression"),
    1543            )
    1544            if sql
    1545        )
    1546        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args}"
    1547
    1548    def offset_sql(self, expression: exp.Offset) -> str:
    1549        this = self.sql(expression, "this")
    1550        return f"{this}{self.seg('OFFSET')} {self.sql(expression, 'expression')}"
    1551
    1552    def setitem_sql(self, expression: exp.SetItem) -> str:
    1553        kind = self.sql(expression, "kind")
    1554        kind = f"{kind} " if kind else ""
    1555        this = self.sql(expression, "this")
    1556        expressions = self.expressions(expression)
    1557        collate = self.sql(expression, "collate")
    1558        collate = f" COLLATE {collate}" if collate else ""
    1559        global_ = "GLOBAL " if expression.args.get("global") else ""
    1560        return f"{global_}{kind}{this}{expressions}{collate}"
    1561
    1562    def set_sql(self, expression: exp.Set) -> str:
    1563        expressions = (
    1564            f" {self.expressions(expression, flat=True)}" if expression.expressions else ""
    1565        )
    1566        tag = " TAG" if expression.args.get("tag") else ""
    1567        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"
    1568
    1569    def pragma_sql(self, expression: exp.Pragma) -> str:
    1570        return f"PRAGMA {self.sql(expression, 'this')}"
    1571
    1572    def lock_sql(self, expression: exp.Lock) -> str:
    1573        if not self.LOCKING_READS_SUPPORTED:
    1574            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    1575            return ""
    1576
    1577        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    1578        expressions = self.expressions(expression, flat=True)
    1579        expressions = f" OF {expressions}" if expressions else ""
    1580        wait = expression.args.get("wait")
    1581
    1582        if wait is not None:
    1583            if isinstance(wait, exp.Literal):
    1584                wait = f" WAIT {self.sql(wait)}"
    1585            else:
    1586                wait = " NOWAIT" if wait else " SKIP LOCKED"
    1587
    1588        return f"{lock_type}{expressions}{wait or ''}"
    1589
    1590    def literal_sql(self, expression: exp.Literal) -> str:
    1591        text = expression.this or ""
    1592        if expression.is_string:
    1593            text = f"{self.QUOTE_START}{self.escape_str(text)}{self.QUOTE_END}"
    1594        return text
    1595
    1596    def escape_str(self, text: str) -> str:
    1597        text = text.replace(self.QUOTE_END, self._escaped_quote_end)
    1598        if self.ESCAPE_LINE_BREAK:
    1599            text = text.replace("\n", "\\n")
    1600        elif self.pretty:
    1601            text = text.replace("\n", self.SENTINEL_LINE_BREAK)
    1602        return text
    1603
    1604    def loaddata_sql(self, expression: exp.LoadData) -> str:
    1605        local = " LOCAL" if expression.args.get("local") else ""
    1606        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    1607        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    1608        this = f" INTO TABLE {self.sql(expression, 'this')}"
    1609        partition = self.sql(expression, "partition")
    1610        partition = f" {partition}" if partition else ""
    1611        input_format = self.sql(expression, "input_format")
    1612        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    1613        serde = self.sql(expression, "serde")
    1614        serde = f" SERDE {serde}" if serde else ""
    1615        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"
    1616
    1617    def null_sql(self, *_) -> str:
    1618        return "NULL"
    1619
    1620    def boolean_sql(self, expression: exp.Boolean) -> str:
    1621        return "TRUE" if expression.this else "FALSE"
    1622
    1623    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    1624        this = self.sql(expression, "this")
    1625        this = f"{this} " if this else this
    1626        return self.op_expressions(f"{this}ORDER BY", expression, flat=this or flat)  # type: ignore
    1627
    1628    def cluster_sql(self, expression: exp.Cluster) -> str:
    1629        return self.op_expressions("CLUSTER BY", expression)
    1630
    1631    def distribute_sql(self, expression: exp.Distribute) -> str:
    1632        return self.op_expressions("DISTRIBUTE BY", expression)
    1633
    1634    def sort_sql(self, expression: exp.Sort) -> str:
    1635        return self.op_expressions("SORT BY", expression)
    1636
    1637    def ordered_sql(self, expression: exp.Ordered) -> str:
    1638        desc = expression.args.get("desc")
    1639        asc = not desc
    1640
    1641        nulls_first = expression.args.get("nulls_first")
    1642        nulls_last = not nulls_first
    1643        nulls_are_large = self.NULL_ORDERING == "nulls_are_large"
    1644        nulls_are_small = self.NULL_ORDERING == "nulls_are_small"
    1645        nulls_are_last = self.NULL_ORDERING == "nulls_are_last"
    1646
    1647        sort_order = " DESC" if desc else ""
    1648        nulls_sort_change = ""
    1649        if nulls_first and (
    1650            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
    1651        ):
    1652            nulls_sort_change = " NULLS FIRST"
    1653        elif (
    1654            nulls_last
    1655            and ((asc and nulls_are_small) or (desc and nulls_are_large))
    1656            and not nulls_are_last
    1657        ):
    1658            nulls_sort_change = " NULLS LAST"
    1659
    1660        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
    1661            self.unsupported(
    1662                "Sorting in an ORDER BY on NULLS FIRST/NULLS LAST is not supported by this dialect"
    1663            )
    1664            nulls_sort_change = ""
    1665
    1666        return f"{self.sql(expression, 'this')}{sort_order}{nulls_sort_change}"
    1667
    1668    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    1669        partition = self.partition_by_sql(expression)
    1670        order = self.sql(expression, "order")
    1671        measures = self.expressions(expression, key="measures")
    1672        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    1673        rows = self.sql(expression, "rows")
    1674        rows = self.seg(rows) if rows else ""
    1675        after = self.sql(expression, "after")
    1676        after = self.seg(after) if after else ""
    1677        pattern = self.sql(expression, "pattern")
    1678        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    1679        definition_sqls = [
    1680            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    1681            for definition in expression.args.get("define", [])
    1682        ]
    1683        definitions = self.expressions(sqls=definition_sqls)
    1684        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    1685        body = "".join(
    1686            (
    1687                partition,
    1688                order,
    1689                measures,
    1690                rows,
    1691                after,
    1692                pattern,
    1693                define,
    1694            )
    1695        )
    1696        alias = self.sql(expression, "alias")
    1697        alias = f" {alias}" if alias else ""
    1698        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"
    1699
    1700    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    1701        limit: t.Optional[exp.Fetch | exp.Limit] = expression.args.get("limit")
    1702
    1703        # If the limit is generated as TOP, we need to ensure it's not generated twice
    1704        with_offset_limit_modifiers = not isinstance(limit, exp.Limit) or not self.LIMIT_IS_TOP
    1705
    1706        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    1707            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
    1708        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    1709            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
    1710
    1711        fetch = isinstance(limit, exp.Fetch)
    1712
    1713        offset_limit_modifiers = (
    1714            self.offset_limit_modifiers(expression, fetch, limit)
    1715            if with_offset_limit_modifiers
    1716            else []
    1717        )
    1718
    1719        return csv(
    1720            *sqls,
    1721            *[self.sql(join) for join in expression.args.get("joins") or []],
    1722            self.sql(expression, "connect"),
    1723            self.sql(expression, "match"),
    1724            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    1725            self.sql(expression, "where"),
    1726            self.sql(expression, "group"),
    1727            self.sql(expression, "having"),
    1728            *self.after_having_modifiers(expression),
    1729            self.sql(expression, "order"),
    1730            *offset_limit_modifiers,
    1731            *self.after_limit_modifiers(expression),
    1732            sep="",
    1733        )
    1734
    1735    def offset_limit_modifiers(
    1736        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    1737    ) -> t.List[str]:
    1738        return [
    1739            self.sql(expression, "offset") if fetch else self.sql(limit),
    1740            self.sql(limit) if fetch else self.sql(expression, "offset"),
    1741        ]
    1742
    1743    def after_having_modifiers(self, expression: exp.Expression) -> t.List[str]:
    1744        return [
    1745            self.sql(expression, "qualify"),
    1746            self.seg("WINDOW ") + self.expressions(expression, key="windows", flat=True)
    1747            if expression.args.get("windows")
    1748            else "",
    1749            self.sql(expression, "distribute"),
    1750            self.sql(expression, "sort"),
    1751            self.sql(expression, "cluster"),
    1752        ]
    1753
    1754    def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]:
    1755        locks = self.expressions(expression, key="locks", sep=" ")
    1756        locks = f" {locks}" if locks else ""
    1757        return [locks, self.sql(expression, "sample")]
    1758
    1759    def select_sql(self, expression: exp.Select) -> str:
    1760        hint = self.sql(expression, "hint")
    1761        distinct = self.sql(expression, "distinct")
    1762        distinct = f" {distinct}" if distinct else ""
    1763        kind = self.sql(expression, "kind").upper()
    1764        limit = expression.args.get("limit")
    1765        top = (
    1766            self.limit_sql(limit, top=True)
    1767            if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP
    1768            else ""
    1769        )
    1770
    1771        expressions = self.expressions(expression)
    1772
    1773        if kind:
    1774            if kind in self.SELECT_KINDS:
    1775                kind = f" AS {kind}"
    1776            else:
    1777                if kind == "STRUCT":
    1778                    expressions = self.expressions(
    1779                        sqls=[
    1780                            self.sql(
    1781                                exp.Struct(
    1782                                    expressions=[
    1783                                        exp.column(e.output_name).eq(
    1784                                            e.this if isinstance(e, exp.Alias) else e
    1785                                        )
    1786                                        for e in expression.expressions
    1787                                    ]
    1788                                )
    1789                            )
    1790                        ]
    1791                    )
    1792                kind = ""
    1793
    1794        expressions = f"{self.sep()}{expressions}" if expressions else expressions
    1795        sql = self.query_modifiers(
    1796            expression,
    1797            f"SELECT{top}{hint}{distinct}{kind}{expressions}",
    1798            self.sql(expression, "into", comment=False),
    1799            self.sql(expression, "from", comment=False),
    1800        )
    1801        return self.prepend_ctes(expression, sql)
    1802
    1803    def schema_sql(self, expression: exp.Schema) -> str:
    1804        this = self.sql(expression, "this")
    1805        this = f"{this} " if this else ""
    1806        sql = self.schema_columns_sql(expression)
    1807        return f"{this}{sql}"
    1808
    1809    def schema_columns_sql(self, expression: exp.Schema) -> str:
    1810        return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
    1811
    1812    def star_sql(self, expression: exp.Star) -> str:
    1813        except_ = self.expressions(expression, key="except", flat=True)
    1814        except_ = f"{self.seg(self.STAR_MAPPING['except'])} ({except_})" if except_ else ""
    1815        replace = self.expressions(expression, key="replace", flat=True)
    1816        replace = f"{self.seg(self.STAR_MAPPING['replace'])} ({replace})" if replace else ""
    1817        return f"*{except_}{replace}"
    1818
    1819    def parameter_sql(self, expression: exp.Parameter) -> str:
    1820        this = self.sql(expression, "this")
    1821        this = f"{{{this}}}" if expression.args.get("wrapped") else f"{this}"
    1822        return f"{self.PARAMETER_TOKEN}{this}"
    1823
    1824    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    1825        this = self.sql(expression, "this")
    1826        kind = expression.text("kind")
    1827        if kind:
    1828            kind = f"{kind}."
    1829        return f"@@{kind}{this}"
    1830
    1831    def placeholder_sql(self, expression: exp.Placeholder) -> str:
    1832        return f":{expression.name}" if expression.name else "?"
    1833
    1834    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    1835        alias = self.sql(expression, "alias")
    1836        alias = f"{sep}{alias}" if alias else ""
    1837
    1838        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    1839        pivots = f" {pivots}" if pivots else ""
    1840
    1841        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    1842        return self.prepend_ctes(expression, sql)
    1843
    1844    def qualify_sql(self, expression: exp.Qualify) -> str:
    1845        this = self.indent(self.sql(expression, "this"))
    1846        return f"{self.seg('QUALIFY')}{self.sep()}{this}"
    1847
    1848    def union_sql(self, expression: exp.Union) -> str:
    1849        return self.prepend_ctes(
    1850            expression,
    1851            self.set_operation(expression, self.union_op(expression)),
    1852        )
    1853
    1854    def union_op(self, expression: exp.Union) -> str:
    1855        kind = " DISTINCT" if self.EXPLICIT_UNION else ""
    1856        kind = kind if expression.args.get("distinct") else " ALL"
    1857        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1858        return f"UNION{kind}{by_name}"
    1859
    1860    def unnest_sql(self, expression: exp.Unnest) -> str:
    1861        args = self.expressions(expression, flat=True)
    1862        alias = expression.args.get("alias")
    1863        if alias and self.UNNEST_COLUMN_ONLY:
    1864            columns = alias.columns
    1865            alias = self.sql(columns[0]) if columns else ""
    1866        else:
    1867            alias = self.sql(expression, "alias")
    1868        alias = f" AS {alias}" if alias else alias
    1869        ordinality = " WITH ORDINALITY" if expression.args.get("ordinality") else ""
    1870        offset = expression.args.get("offset")
    1871        offset = f" WITH OFFSET AS {self.sql(offset)}" if offset else ""
    1872        return f"UNNEST({args}){ordinality}{alias}{offset}"
    1873
    1874    def where_sql(self, expression: exp.Where) -> str:
    1875        this = self.indent(self.sql(expression, "this"))
    1876        return f"{self.seg('WHERE')}{self.sep()}{this}"
    1877
    1878    def window_sql(self, expression: exp.Window) -> str:
    1879        this = self.sql(expression, "this")
    1880        partition = self.partition_by_sql(expression)
    1881        order = expression.args.get("order")
    1882        order = self.order_sql(order, flat=True) if order else ""
    1883        spec = self.sql(expression, "spec")
    1884        alias = self.sql(expression, "alias")
    1885        over = self.sql(expression, "over") or "OVER"
    1886
    1887        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    1888
    1889        first = expression.args.get("first")
    1890        if first is None:
    1891            first = ""
    1892        else:
    1893            first = "FIRST" if first else "LAST"
    1894
    1895        if not partition and not order and not spec and alias:
    1896            return f"{this} {alias}"
    1897
    1898        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
    1899        return f"{this} ({args})"
    1900
    1901    def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str:
    1902        partition = self.expressions(expression, key="partition_by", flat=True)
    1903        return f"PARTITION BY {partition}" if partition else ""
    1904
    1905    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    1906        kind = self.sql(expression, "kind")
    1907        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    1908        end = (
    1909            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    1910            or "CURRENT ROW"
    1911        )
    1912        return f"{kind} BETWEEN {start} AND {end}"
    1913
    1914    def withingroup_sql(self, expression: exp.WithinGroup) -> str:
    1915        this = self.sql(expression, "this")
    1916        expression_sql = self.sql(expression, "expression")[1:]  # order has a leading space
    1917        return f"{this} WITHIN GROUP ({expression_sql})"
    1918
    1919    def between_sql(self, expression: exp.Between) -> str:
    1920        this = self.sql(expression, "this")
    1921        low = self.sql(expression, "low")
    1922        high = self.sql(expression, "high")
    1923        return f"{this} BETWEEN {low} AND {high}"
    1924
    1925    def bracket_sql(self, expression: exp.Bracket) -> str:
    1926        expressions = apply_index_offset(expression.this, expression.expressions, self.INDEX_OFFSET)
    1927        expressions_sql = ", ".join(self.sql(e) for e in expressions)
    1928
    1929        return f"{self.sql(expression, 'this')}[{expressions_sql}]"
    1930
    1931    def safebracket_sql(self, expression: exp.SafeBracket) -> str:
    1932        return self.bracket_sql(expression)
    1933
    1934    def all_sql(self, expression: exp.All) -> str:
    1935        return f"ALL {self.wrap(expression)}"
    1936
    1937    def any_sql(self, expression: exp.Any) -> str:
    1938        this = self.sql(expression, "this")
    1939        if isinstance(expression.this, exp.Subqueryable):
    1940            this = self.wrap(this)
    1941        return f"ANY {this}"
    1942
    1943    def exists_sql(self, expression: exp.Exists) -> str:
    1944        return f"EXISTS{self.wrap(expression)}"
    1945
    1946    def case_sql(self, expression: exp.Case) -> str:
    1947        this = self.sql(expression, "this")
    1948        statements = [f"CASE {this}" if this else "CASE"]
    1949
    1950        for e in expression.args["ifs"]:
    1951            statements.append(f"WHEN {self.sql(e, 'this')}")
    1952            statements.append(f"THEN {self.sql(e, 'true')}")
    1953
    1954        default = self.sql(expression, "default")
    1955
    1956        if default:
    1957            statements.append(f"ELSE {default}")
    1958
    1959        statements.append("END")
    1960
    1961        if self.pretty and self.text_width(statements) > self.max_text_width:
    1962            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    1963
    1964        return " ".join(statements)
    1965
    1966    def constraint_sql(self, expression: exp.Constraint) -> str:
    1967        this = self.sql(expression, "this")
    1968        expressions = self.expressions(expression, flat=True)
    1969        return f"CONSTRAINT {this} {expressions}"
    1970
    1971    def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str:
    1972        order = expression.args.get("order")
    1973        order = f" OVER ({self.order_sql(order, flat=True)})" if order else ""
    1974        return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}"
    1975
    1976    def extract_sql(self, expression: exp.Extract) -> str:
    1977        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
    1978        expression_sql = self.sql(expression, "expression")
    1979        return f"EXTRACT({this} FROM {expression_sql})"
    1980
    1981    def trim_sql(self, expression: exp.Trim) -> str:
    1982        trim_type = self.sql(expression, "position")
    1983
    1984        if trim_type == "LEADING":
    1985            return self.func("LTRIM", expression.this)
    1986        elif trim_type == "TRAILING":
    1987            return self.func("RTRIM", expression.this)
    1988        else:
    1989            return self.func("TRIM", expression.this, expression.expression)
    1990
    1991    def safeconcat_sql(self, expression: exp.SafeConcat) -> str:
    1992        expressions = expression.expressions
    1993        if self.STRICT_STRING_CONCAT:
    1994            expressions = (exp.cast(e, "text") for e in expressions)
    1995        return self.func("CONCAT", *expressions)
    1996
    1997    def check_sql(self, expression: exp.Check) -> str:
    1998        this = self.sql(expression, key="this")
    1999        return f"CHECK ({this})"
    2000
    2001    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    2002        expressions = self.expressions(expression, flat=True)
    2003        reference = self.sql(expression, "reference")
    2004        reference = f" {reference}" if reference else ""
    2005        delete = self.sql(expression, "delete")
    2006        delete = f" ON DELETE {delete}" if delete else ""
    2007        update = self.sql(expression, "update")
    2008        update = f" ON UPDATE {update}" if update else ""
    2009        return f"FOREIGN KEY ({expressions}){reference}{delete}{update}"
    2010
    2011    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    2012        expressions = self.expressions(expression, flat=True)
    2013        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2014        options = f" {options}" if options else ""
    2015        return f"PRIMARY KEY ({expressions}){options}"
    2016
    2017    def if_sql(self, expression: exp.If) -> str:
    2018        expression = expression.copy()
    2019        return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false")))
    2020
    2021    def matchagainst_sql(self, expression: exp.MatchAgainst) -> str:
    2022        modifier = expression.args.get("modifier")
    2023        modifier = f" {modifier}" if modifier else ""
    2024        return f"{self.func('MATCH', *expression.expressions)} AGAINST({self.sql(expression, 'this')}{modifier})"
    2025
    2026    def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str:
    2027        return f"{self.sql(expression, 'this')}: {self.sql(expression, 'expression')}"
    2028
    2029    def formatjson_sql(self, expression: exp.FormatJson) -> str:
    2030        return f"{self.sql(expression, 'this')} FORMAT JSON"
    2031
    2032    def jsonobject_sql(self, expression: exp.JSONObject) -> str:
    2033        null_handling = expression.args.get("null_handling")
    2034        null_handling = f" {null_handling}" if null_handling else ""
    2035        unique_keys = expression.args.get("unique_keys")
    2036        if unique_keys is not None:
    2037            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    2038        else:
    2039            unique_keys = ""
    2040        return_type = self.sql(expression, "return_type")
    2041        return_type = f" RETURNING {return_type}" if return_type else ""
    2042        encoding = self.sql(expression, "encoding")
    2043        encoding = f" ENCODING {encoding}" if encoding else ""
    2044        return self.func(
    2045            "JSON_OBJECT",
    2046            *expression.expressions,
    2047            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
    2048        )
    2049
    2050    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
    2051        null_handling = expression.args.get("null_handling")
    2052        null_handling = f" {null_handling}" if null_handling else ""
    2053        return_type = self.sql(expression, "return_type")
    2054        return_type = f" RETURNING {return_type}" if return_type else ""
    2055        strict = " STRICT" if expression.args.get("strict") else ""
    2056        return self.func(
    2057            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
    2058        )
    2059
    2060    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
    2061        this = self.sql(expression, "this")
    2062        order = self.sql(expression, "order")
    2063        null_handling = expression.args.get("null_handling")
    2064        null_handling = f" {null_handling}" if null_handling else ""
    2065        return_type = self.sql(expression, "return_type")
    2066        return_type = f" RETURNING {return_type}" if return_type else ""
    2067        strict = " STRICT" if expression.args.get("strict") else ""
    2068        return self.func(
    2069            "JSON_ARRAYAGG",
    2070            this,
    2071            suffix=f"{order}{null_handling}{return_type}{strict})",
    2072        )
    2073
    2074    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
    2075        this = self.sql(expression, "this")
    2076        kind = self.sql(expression, "kind")
    2077        kind = f" {kind}" if kind else ""
    2078        path = self.sql(expression, "path")
    2079        path = f" PATH {path}" if path else ""
    2080        return f"{this}{kind}{path}"
    2081
    2082    def jsontable_sql(self, expression: exp.JSONTable) -> str:
    2083        this = self.sql(expression, "this")
    2084        path = self.sql(expression, "path")
    2085        path = f", {path}" if path else ""
    2086        error_handling = expression.args.get("error_handling")
    2087        error_handling = f" {error_handling}" if error_handling else ""
    2088        empty_handling = expression.args.get("empty_handling")
    2089        empty_handling = f" {empty_handling}" if empty_handling else ""
    2090        columns = f" COLUMNS ({self.expressions(expression, skip_first=True)})"
    2091        return self.func(
    2092            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling}{columns})"
    2093        )
    2094
    2095    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    2096        this = self.sql(expression, "this")
    2097        kind = self.sql(expression, "kind")
    2098        path = self.sql(expression, "path")
    2099        path = f" {path}" if path else ""
    2100        as_json = " AS JSON" if expression.args.get("as_json") else ""
    2101        return f"{this} {kind}{path}{as_json}"
    2102
    2103    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    2104        this = self.sql(expression, "this")
    2105        path = self.sql(expression, "path")
    2106        path = f", {path}" if path else ""
    2107        expressions = self.expressions(expression)
    2108        with_ = (
    2109            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    2110            if expressions
    2111            else ""
    2112        )
    2113        return f"OPENJSON({this}{path}){with_}"
    2114
    2115    def in_sql(self, expression: exp.In) -> str:
    2116        query = expression.args.get("query")
    2117        unnest = expression.args.get("unnest")
    2118        field = expression.args.get("field")
    2119        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    2120
    2121        if query:
    2122            in_sql = self.wrap(query)
    2123        elif unnest:
    2124            in_sql = self.in_unnest_op(unnest)
    2125        elif field:
    2126            in_sql = self.sql(field)
    2127        else:
    2128            in_sql = f"({self.expressions(expression, flat=True)})"
    2129
    2130        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"
    2131
    2132    def in_unnest_op(self, unnest: exp.Unnest) -> str:
    2133        return f"(SELECT {self.sql(unnest)})"
    2134
    2135    def interval_sql(self, expression: exp.Interval) -> str:
    2136        unit = self.sql(expression, "unit")
    2137        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    2138            unit = self.TIME_PART_SINGULARS.get(unit.lower(), unit)
    2139        unit = f" {unit}" if unit else ""
    2140
    2141        if self.SINGLE_STRING_INTERVAL:
    2142            this = expression.this.name if expression.this else ""
    2143            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    2144
    2145        this = self.sql(expression, "this")
    2146        if this:
    2147            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    2148            this = f" {this}" if unwrapped else f" ({this})"
    2149
    2150        return f"INTERVAL{this}{unit}"
    2151
    2152    def return_sql(self, expression: exp.Return) -> str:
    2153        return f"RETURN {self.sql(expression, 'this')}"
    2154
    2155    def reference_sql(self, expression: exp.Reference) -> str:
    2156        this = self.sql(expression, "this")
    2157        expressions = self.expressions(expression, flat=True)
    2158        expressions = f"({expressions})" if expressions else ""
    2159        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2160        options = f" {options}" if options else ""
    2161        return f"REFERENCES {this}{expressions}{options}"
    2162
    2163    def anonymous_sql(self, expression: exp.Anonymous) -> str:
    2164        return self.func(expression.name, *expression.expressions)
    2165
    2166    def paren_sql(self, expression: exp.Paren) -> str:
    2167        if isinstance(expression.unnest(), exp.Select):
    2168            sql = self.wrap(expression)
    2169        else:
    2170            sql = self.seg(self.indent(self.sql(expression, "this")), sep="")
    2171            sql = f"({sql}{self.seg(')', sep='')}"
    2172
    2173        return self.prepend_ctes(expression, sql)
    2174
    2175    def neg_sql(self, expression: exp.Neg) -> str:
    2176        # This makes sure we don't convert "- - 5" to "--5", which is a comment
    2177        this_sql = self.sql(expression, "this")
    2178        sep = " " if this_sql[0] == "-" else ""
    2179        return f"-{sep}{this_sql}"
    2180
    2181    def not_sql(self, expression: exp.Not) -> str:
    2182        return f"NOT {self.sql(expression, 'this')}"
    2183
    2184    def alias_sql(self, expression: exp.Alias) -> str:
    2185        alias = self.sql(expression, "alias")
    2186        alias = f" AS {alias}" if alias else ""
    2187        return f"{self.sql(expression, 'this')}{alias}"
    2188
    2189    def aliases_sql(self, expression: exp.Aliases) -> str:
    2190        return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})"
    2191
    2192    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    2193        this = self.sql(expression, "this")
    2194        zone = self.sql(expression, "zone")
    2195        return f"{this} AT TIME ZONE {zone}"
    2196
    2197    def add_sql(self, expression: exp.Add) -> str:
    2198        return self.binary(expression, "+")
    2199
    2200    def and_sql(self, expression: exp.And) -> str:
    2201        return self.connector_sql(expression, "AND")
    2202
    2203    def xor_sql(self, expression: exp.Xor) -> str:
    2204        return self.connector_sql(expression, "XOR")
    2205
    2206    def connector_sql(self, expression: exp.Connector, op: str) -> str:
    2207        if not self.pretty:
    2208            return self.binary(expression, op)
    2209
    2210        sqls = tuple(
    2211            self.maybe_comment(self.sql(e), e, e.parent.comments or []) if i != 1 else self.sql(e)
    2212            for i, e in enumerate(expression.flatten(unnest=False))
    2213        )
    2214
    2215        sep = "\n" if self.text_width(sqls) > self.max_text_width else " "
    2216        return f"{sep}{op} ".join(sqls)
    2217
    2218    def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str:
    2219        return self.binary(expression, "&")
    2220
    2221    def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str:
    2222        return self.binary(expression, "<<")
    2223
    2224    def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str:
    2225        return f"~{self.sql(expression, 'this')}"
    2226
    2227    def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str:
    2228        return self.binary(expression, "|")
    2229
    2230    def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str:
    2231        return self.binary(expression, ">>")
    2232
    2233    def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str:
    2234        return self.binary(expression, "^")
    2235
    2236    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    2237        format_sql = self.sql(expression, "format")
    2238        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    2239        return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS {self.sql(expression, 'to')}{format_sql})"
    2240
    2241    def currentdate_sql(self, expression: exp.CurrentDate) -> str:
    2242        zone = self.sql(expression, "this")
    2243        return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE"
    2244
    2245    def collate_sql(self, expression: exp.Collate) -> str:
    2246        return self.binary(expression, "COLLATE")
    2247
    2248    def command_sql(self, expression: exp.Command) -> str:
    2249        return f"{self.sql(expression, 'this').upper()} {expression.text('expression').strip()}"
    2250
    2251    def comment_sql(self, expression: exp.Comment) -> str:
    2252        this = self.sql(expression, "this")
    2253        kind = expression.args["kind"]
    2254        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    2255        expression_sql = self.sql(expression, "expression")
    2256        return f"COMMENT{exists_sql}ON {kind} {this} IS {expression_sql}"
    2257
    2258    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    2259        this = self.sql(expression, "this")
    2260        delete = " DELETE" if expression.args.get("delete") else ""
    2261        recompress = self.sql(expression, "recompress")
    2262        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    2263        to_disk = self.sql(expression, "to_disk")
    2264        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    2265        to_volume = self.sql(expression, "to_volume")
    2266        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    2267        return f"{this}{delete}{recompress}{to_disk}{to_volume}"
    2268
    2269    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    2270        where = self.sql(expression, "where")
    2271        group = self.sql(expression, "group")
    2272        aggregates = self.expressions(expression, key="aggregates")
    2273        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    2274
    2275        if not (where or group or aggregates) and len(expression.expressions) == 1:
    2276            return f"TTL {self.expressions(expression, flat=True)}"
    2277
    2278        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"
    2279
    2280    def transaction_sql(self, expression: exp.Transaction) -> str:
    2281        return "BEGIN"
    2282
    2283    def commit_sql(self, expression: exp.Commit) -> str:
    2284        chain = expression.args.get("chain")
    2285        if chain is not None:
    2286            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    2287
    2288        return f"COMMIT{chain or ''}"
    2289
    2290    def rollback_sql(self, expression: exp.Rollback) -> str:
    2291        savepoint = expression.args.get("savepoint")
    2292        savepoint = f" TO {savepoint}" if savepoint else ""
    2293        return f"ROLLBACK{savepoint}"
    2294
    2295    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    2296        this = self.sql(expression, "this")
    2297
    2298        dtype = self.sql(expression, "dtype")
    2299        if dtype:
    2300            collate = self.sql(expression, "collate")
    2301            collate = f" COLLATE {collate}" if collate else ""
    2302            using = self.sql(expression, "using")
    2303            using = f" USING {using}" if using else ""
    2304            return f"ALTER COLUMN {this} TYPE {dtype}{collate}{using}"
    2305
    2306        default = self.sql(expression, "default")
    2307        if default:
    2308            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    2309
    2310        if not expression.args.get("drop"):
    2311            self.unsupported("Unsupported ALTER COLUMN syntax")
    2312
    2313        return f"ALTER COLUMN {this} DROP DEFAULT"
    2314
    2315    def renametable_sql(self, expression: exp.RenameTable) -> str:
    2316        if not self.RENAME_TABLE_WITH_DB:
    2317            # Remove db from tables
    2318            expression = expression.transform(
    2319                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    2320            )
    2321        this = self.sql(expression, "this")
    2322        return f"RENAME TO {this}"
    2323
    2324    def altertable_sql(self, expression: exp.AlterTable) -> str:
    2325        actions = expression.args["actions"]
    2326
    2327        if isinstance(actions[0], exp.ColumnDef):
    2328            if self.ALTER_TABLE_ADD_COLUMN_KEYWORD:
    2329                actions = self.expressions(
    2330                    expression,
    2331                    key="actions",
    2332                    prefix="ADD COLUMN ",
    2333                )
    2334            else:
    2335                actions = f"ADD {self.expressions(expression, key='actions')}"
    2336        elif isinstance(actions[0], exp.Schema):
    2337            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    2338        elif isinstance(actions[0], exp.Delete):
    2339            actions = self.expressions(expression, key="actions", flat=True)
    2340        else:
    2341            actions = self.expressions(expression, key="actions")
    2342
    2343        exists = " IF EXISTS" if expression.args.get("exists") else ""
    2344        only = " ONLY" if expression.args.get("only") else ""
    2345        return f"ALTER TABLE{exists}{only} {self.sql(expression, 'this')} {actions}"
    2346
    2347    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    2348        expressions = self.expressions(expression)
    2349        exists = " IF EXISTS " if expression.args.get("exists") else " "
    2350        return f"DROP{exists}{expressions}"
    2351
    2352    def addconstraint_sql(self, expression: exp.AddConstraint) -> str:
    2353        this = self.sql(expression, "this")
    2354        expression_ = self.sql(expression, "expression")
    2355        add_constraint = f"ADD CONSTRAINT {this}" if this else "ADD"
    2356
    2357        enforced = expression.args.get("enforced")
    2358        if enforced is not None:
    2359            return f"{add_constraint} CHECK ({expression_}){' ENFORCED' if enforced else ''}"
    2360
    2361        return f"{add_constraint} {expression_}"
    2362
    2363    def distinct_sql(self, expression: exp.Distinct) -> str:
    2364        this = self.expressions(expression, flat=True)
    2365        this = f" {this}" if this else ""
    2366
    2367        on = self.sql(expression, "on")
    2368        on = f" ON {on}" if on else ""
    2369        return f"DISTINCT{this}{on}"
    2370
    2371    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
    2372        return f"{self.sql(expression, 'this')} IGNORE NULLS"
    2373
    2374    def respectnulls_sql(self, expression: exp.RespectNulls) -> str:
    2375        return f"{self.sql(expression, 'this')} RESPECT NULLS"
    2376
    2377    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    2378        return self.sql(
    2379            exp.Cast(
    2380                this=exp.Div(this=expression.this.copy(), expression=expression.expression.copy()),
    2381                to=exp.DataType(this=exp.DataType.Type.INT),
    2382            )
    2383        )
    2384
    2385    def dpipe_sql(self, expression: exp.DPipe) -> str:
    2386        return self.binary(expression, "||")
    2387
    2388    def safedpipe_sql(self, expression: exp.SafeDPipe) -> str:
    2389        if self.STRICT_STRING_CONCAT:
    2390            return self.func("CONCAT", *(exp.cast(e, "text") for e in expression.flatten()))
    2391        return self.dpipe_sql(expression)
    2392
    2393    def div_sql(self, expression: exp.Div) -> str:
    2394        return self.binary(expression, "/")
    2395
    2396    def overlaps_sql(self, expression: exp.Overlaps) -> str:
    2397        return self.binary(expression, "OVERLAPS")
    2398
    2399    def distance_sql(self, expression: exp.Distance) -> str:
    2400        return self.binary(expression, "<->")
    2401
    2402    def dot_sql(self, expression: exp.Dot) -> str:
    2403        return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}"
    2404
    2405    def eq_sql(self, expression: exp.EQ) -> str:
    2406        return self.binary(expression, "=")
    2407
    2408    def escape_sql(self, expression: exp.Escape) -> str:
    2409        return self.binary(expression, "ESCAPE")
    2410
    2411    def glob_sql(self, expression: exp.Glob) -> str:
    2412        return self.binary(expression, "GLOB")
    2413
    2414    def gt_sql(self, expression: exp.GT) -> str:
    2415        return self.binary(expression, ">")
    2416
    2417    def gte_sql(self, expression: exp.GTE) -> str:
    2418        return self.binary(expression, ">=")
    2419
    2420    def ilike_sql(self, expression: exp.ILike) -> str:
    2421        return self.binary(expression, "ILIKE")
    2422
    2423    def ilikeany_sql(self, expression: exp.ILikeAny) -> str:
    2424        return self.binary(expression, "ILIKE ANY")
    2425
    2426    def is_sql(self, expression: exp.Is) -> str:
    2427        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    2428            return self.sql(
    2429                expression.this if expression.expression.this else exp.not_(expression.this)
    2430            )
    2431        return self.binary(expression, "IS")
    2432
    2433    def like_sql(self, expression: exp.Like) -> str:
    2434        return self.binary(expression, "LIKE")
    2435
    2436    def likeany_sql(self, expression: exp.LikeAny) -> str:
    2437        return self.binary(expression, "LIKE ANY")
    2438
    2439    def similarto_sql(self, expression: exp.SimilarTo) -> str:
    2440        return self.binary(expression, "SIMILAR TO")
    2441
    2442    def lt_sql(self, expression: exp.LT) -> str:
    2443        return self.binary(expression, "<")
    2444
    2445    def lte_sql(self, expression: exp.LTE) -> str:
    2446        return self.binary(expression, "<=")
    2447
    2448    def mod_sql(self, expression: exp.Mod) -> str:
    2449        return self.binary(expression, "%")
    2450
    2451    def mul_sql(self, expression: exp.Mul) -> str:
    2452        return self.binary(expression, "*")
    2453
    2454    def neq_sql(self, expression: exp.NEQ) -> str:
    2455        return self.binary(expression, "<>")
    2456
    2457    def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str:
    2458        return self.binary(expression, "IS NOT DISTINCT FROM")
    2459
    2460    def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str:
    2461        return self.binary(expression, "IS DISTINCT FROM")
    2462
    2463    def or_sql(self, expression: exp.Or) -> str:
    2464        return self.connector_sql(expression, "OR")
    2465
    2466    def slice_sql(self, expression: exp.Slice) -> str:
    2467        return self.binary(expression, ":")
    2468
    2469    def sub_sql(self, expression: exp.Sub) -> str:
    2470        return self.binary(expression, "-")
    2471
    2472    def trycast_sql(self, expression: exp.TryCast) -> str:
    2473        return self.cast_sql(expression, safe_prefix="TRY_")
    2474
    2475    def use_sql(self, expression: exp.Use) -> str:
    2476        kind = self.sql(expression, "kind")
    2477        kind = f" {kind}" if kind else ""
    2478        this = self.sql(expression, "this")
    2479        this = f" {this}" if this else ""
    2480        return f"USE{kind}{this}"
    2481
    2482    def binary(self, expression: exp.Binary, op: str) -> str:
    2483        op = self.maybe_comment(op, comments=expression.comments)
    2484        return f"{self.sql(expression, 'this')} {op} {self.sql(expression, 'expression')}"
    2485
    2486    def function_fallback_sql(self, expression: exp.Func) -> str:
    2487        args = []
    2488
    2489        for key in expression.arg_types:
    2490            arg_value = expression.args.get(key)
    2491
    2492            if isinstance(arg_value, list):
    2493                for value in arg_value:
    2494                    args.append(value)
    2495            elif arg_value is not None:
    2496                args.append(arg_value)
    2497
    2498        if self.normalize_functions:
    2499            name = expression.sql_name()
    2500        else:
    2501            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
    2502
    2503        return self.func(name, *args)
    2504
    2505    def func(
    2506        self,
    2507        name: str,
    2508        *args: t.Optional[exp.Expression | str],
    2509        prefix: str = "(",
    2510        suffix: str = ")",
    2511    ) -> str:
    2512        return f"{self.normalize_func(name)}{prefix}{self.format_args(*args)}{suffix}"
    2513
    2514    def format_args(self, *args: t.Optional[str | exp.Expression]) -> str:
    2515        arg_sqls = tuple(self.sql(arg) for arg in args if arg is not None)
    2516        if self.pretty and self.text_width(arg_sqls) > self.max_text_width:
    2517            return self.indent("\n" + f",\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True)
    2518        return ", ".join(arg_sqls)
    2519
    2520    def text_width(self, args: t.Iterable) -> int:
    2521        return sum(len(arg) for arg in args)
    2522
    2523    def format_time(self, expression: exp.Expression) -> t.Optional[str]:
    2524        return format_time(
    2525            self.sql(expression, "format"), self.INVERSE_TIME_MAPPING, self.INVERSE_TIME_TRIE
    2526        )
    2527
    2528    def expressions(
    2529        self,
    2530        expression: t.Optional[exp.Expression] = None,
    2531        key: t.Optional[str] = None,
    2532        sqls: t.Optional[t.List[str]] = None,
    2533        flat: bool = False,
    2534        indent: bool = True,
    2535        skip_first: bool = False,
    2536        sep: str = ", ",
    2537        prefix: str = "",
    2538    ) -> str:
    2539        expressions = expression.args.get(key or "expressions") if expression else sqls
    2540
    2541        if not expressions:
    2542            return ""
    2543
    2544        if flat:
    2545            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
    2546
    2547        num_sqls = len(expressions)
    2548
    2549        # These are calculated once in case we have the leading_comma / pretty option set, correspondingly
    2550        pad = " " * self.pad
    2551        stripped_sep = sep.strip()
    2552
    2553        result_sqls = []
    2554        for i, e in enumerate(expressions):
    2555            sql = self.sql(e, comment=False)
    2556            if not sql:
    2557                continue
    2558
    2559            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    2560
    2561            if self.pretty:
    2562                if self.leading_comma:
    2563                    result_sqls.append(f"{sep if i > 0 else pad}{prefix}{sql}{comments}")
    2564                else:
    2565                    result_sqls.append(
    2566                        f"{prefix}{sql}{stripped_sep if i + 1 < num_sqls else ''}{comments}"
    2567                    )
    2568            else:
    2569                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    2570
    2571        result_sql = "\n".join(result_sqls) if self.pretty else "".join(result_sqls)
    2572        return self.indent(result_sql, skip_first=skip_first) if indent else result_sql
    2573
    2574    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    2575        flat = flat or isinstance(expression.parent, exp.Properties)
    2576        expressions_sql = self.expressions(expression, flat=flat)
    2577        if flat:
    2578            return f"{op} {expressions_sql}"
    2579        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"
    2580
    2581    def naked_property(self, expression: exp.Property) -> str:
    2582        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    2583        if not property_name:
    2584            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    2585        return f"{property_name} {self.sql(expression, 'this')}"
    2586
    2587    def set_operation(self, expression: exp.Expression, op: str) -> str:
    2588        this = self.sql(expression, "this")
    2589        op = self.seg(op)
    2590        return self.query_modifiers(
    2591            expression, f"{this}{op}{self.sep()}{self.sql(expression, 'expression')}"
    2592        )
    2593
    2594    def tag_sql(self, expression: exp.Tag) -> str:
    2595        return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}"
    2596
    2597    def token_sql(self, token_type: TokenType) -> str:
    2598        return self.TOKEN_MAPPING.get(token_type, token_type.name)
    2599
    2600    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    2601        this = self.sql(expression, "this")
    2602        expressions = self.no_identify(self.expressions, expression)
    2603        expressions = (
    2604            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    2605        )
    2606        return f"{this}{expressions}"
    2607
    2608    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    2609        this = self.sql(expression, "this")
    2610        expressions = self.expressions(expression, flat=True)
    2611        return f"{this}({expressions})"
    2612
    2613    def kwarg_sql(self, expression: exp.Kwarg) -> str:
    2614        return self.binary(expression, "=>")
    2615
    2616    def when_sql(self, expression: exp.When) -> str:
    2617        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    2618        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    2619        condition = self.sql(expression, "condition")
    2620        condition = f" AND {condition}" if condition else ""
    2621
    2622        then_expression = expression.args.get("then")
    2623        if isinstance(then_expression, exp.Insert):
    2624            then = f"INSERT {self.sql(then_expression, 'this')}"
    2625            if "expression" in then_expression.args:
    2626                then += f" VALUES {self.sql(then_expression, 'expression')}"
    2627        elif isinstance(then_expression, exp.Update):
    2628            if isinstance(then_expression.args.get("expressions"), exp.Star):
    2629                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    2630            else:
    2631                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    2632        else:
    2633            then = self.sql(then_expression)
    2634        return f"WHEN {matched}{source}{condition} THEN {then}"
    2635
    2636    def merge_sql(self, expression: exp.Merge) -> str:
    2637        table = expression.this
    2638        table_alias = ""
    2639
    2640        hints = table.args.get("hints")
    2641        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
    2642            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
    2643            table = table.copy()
    2644            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
    2645
    2646        this = self.sql(table)
    2647        using = f"USING {self.sql(expression, 'using')}"
    2648        on = f"ON {self.sql(expression, 'on')}"
    2649        expressions = self.expressions(expression, sep=" ")
    2650
    2651        return f"MERGE INTO {this}{table_alias} {using} {on} {expressions}"
    2652
    2653    def tochar_sql(self, expression: exp.ToChar) -> str:
    2654        if expression.args.get("format"):
    2655            self.unsupported("Format argument unsupported for TO_CHAR/TO_VARCHAR function")
    2656
    2657        return self.sql(exp.cast(expression.this, "text"))
    2658
    2659    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    2660        this = self.sql(expression, "this")
    2661        kind = self.sql(expression, "kind")
    2662        settings_sql = self.expressions(expression, key="settings", sep=" ")
    2663        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    2664        return f"{this}({kind}{args})"
    2665
    2666    def dictrange_sql(self, expression: exp.DictRange) -> str:
    2667        this = self.sql(expression, "this")
    2668        max = self.sql(expression, "max")
    2669        min = self.sql(expression, "min")
    2670        return f"{this}(MIN {min} MAX {max})"
    2671
    2672    def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str:
    2673        return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}"
    2674
    2675    def oncluster_sql(self, expression: exp.OnCluster) -> str:
    2676        return ""
    2677
    2678    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    2679        expressions = self.expressions(expression, key="expressions", flat=True)
    2680        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    2681        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    2682        buckets = self.sql(expression, "buckets")
    2683        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"
    2684
    2685    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    2686        this = self.sql(expression, "this")
    2687        having = self.sql(expression, "having")
    2688
    2689        if having:
    2690            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    2691
    2692        return self.func("ANY_VALUE", this)
    2693
    2694    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
    2695        transform = self.func("TRANSFORM", *expression.expressions)
    2696        row_format_before = self.sql(expression, "row_format_before")
    2697        row_format_before = f" {row_format_before}" if row_format_before else ""
    2698        record_writer = self.sql(expression, "record_writer")
    2699        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
    2700        using = f" USING {self.sql(expression, 'command_script')}"
    2701        schema = self.sql(expression, "schema")
    2702        schema = f" AS {schema}" if schema else ""
    2703        row_format_after = self.sql(expression, "row_format_after")
    2704        row_format_after = f" {row_format_after}" if row_format_after else ""
    2705        record_reader = self.sql(expression, "record_reader")
    2706        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
    2707        return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}"
    2708
    2709    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
    2710        key_block_size = self.sql(expression, "key_block_size")
    2711        if key_block_size:
    2712            return f"KEY_BLOCK_SIZE = {key_block_size}"
    2713
    2714        using = self.sql(expression, "using")
    2715        if using:
    2716            return f"USING {using}"
    2717
    2718        parser = self.sql(expression, "parser")
    2719        if parser:
    2720            return f"WITH PARSER {parser}"
    2721
    2722        comment = self.sql(expression, "comment")
    2723        if comment:
    2724            return f"COMMENT {comment}"
    2725
    2726        visible = expression.args.get("visible")
    2727        if visible is not None:
    2728            return "VISIBLE" if visible else "INVISIBLE"
    2729
    2730        engine_attr = self.sql(expression, "engine_attr")
    2731        if engine_attr:
    2732            return f"ENGINE_ATTRIBUTE = {engine_attr}"
    2733
    2734        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
    2735        if secondary_engine_attr:
    2736            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
    2737
    2738        self.unsupported("Unsupported index constraint option.")
    2739        return ""
    2740
    2741    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
    2742        kind = self.sql(expression, "kind")
    2743        kind = f"{kind} INDEX" if kind else "INDEX"
    2744        this = self.sql(expression, "this")
    2745        this = f" {this}" if this else ""
    2746        index_type = self.sql(expression, "index_type")
    2747        index_type = f" USING {index_type}" if index_type else ""
    2748        schema = self.sql(expression, "schema")
    2749        schema = f" {schema}" if schema else ""
    2750        options = self.expressions(expression, key="options", sep=" ")
    2751        options = f" {options}" if options else ""
    2752        return f"{kind}{this}{index_type}{schema}{options}"
    2753
    2754    def nvl2_sql(self, expression: exp.Nvl2) -> str:
    2755        if self.NVL2_SUPPORTED:
    2756            return self.function_fallback_sql(expression)
    2757
    2758        case = exp.Case().when(
    2759            expression.this.is_(exp.null()).not_(copy=False),
    2760            expression.args["true"].copy(),
    2761            copy=False,
    2762        )
    2763        else_cond = expression.args.get("false")
    2764        if else_cond:
    2765            case.else_(else_cond.copy(), copy=False)
    2766
    2767        return self.sql(case)
    2768
    2769    def comprehension_sql(self, expression: exp.Comprehension) -> str:
    2770        this = self.sql(expression, "this")
    2771        expr = self.sql(expression, "expression")
    2772        iterator = self.sql(expression, "iterator")
    2773        condition = self.sql(expression, "condition")
    2774        condition = f" IF {condition}" if condition else ""
    2775        return f"{this} FOR {expr} IN {iterator}{condition}"
    2776
    2777    def columnprefix_sql(self, expression: exp.ColumnPrefix) -> str:
    2778        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

    260    @classmethod
    261    def can_identify(cls, text: str, identify: str | bool = "safe") -> bool:
    262        """Checks if text can be identified given an identify option.
    263
    264        Args:
    265            text: The text to check.
    266            identify:
    267                "always" or `True`: Always returns true.
    268                "safe": True if the identifier is case-insensitive.
    269
    270        Returns:
    271            Whether or not the given text can be identified.
    272        """
    273        if identify is True or identify == "always":
    274            return True
    275
    276        if identify == "safe":
    277            return not cls.case_sensitive(text)
    278
    279        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        index_type = expression.args.get("index_type")
    710        index_type = f" USING {index_type}" if index_type else ""
    711        return f"UNIQUE{this}{index_type}"

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    1617    def null_sql(self, *_) -> str:
    1618        return "NULL"

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    2777    def columnprefix_sql(self, expression: exp.ColumnPrefix) -> str:
    2778        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

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

Returns a cached generator.