sqlglot.generator API documentation

Edit on GitHub

# sqlglot.generator

View Source

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

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

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

    414    def __init__(
    415        self,
    416        pretty: t.Optional[bool] = None,
    417        identify: str | bool = False,
    418        normalize: bool = False,
    419        pad: int = 2,
    420        indent: int = 2,
    421        normalize_functions: t.Optional[str | bool] = None,
    422        unsupported_level: ErrorLevel = ErrorLevel.WARN,
    423        max_unsupported: int = 3,
    424        leading_comma: bool = False,
    425        max_text_width: int = 80,
    426        comments: bool = True,
    427    ):
    428        import sqlglot
    429
    430        self.pretty = pretty if pretty is not None else sqlglot.pretty
    431        self.identify = identify
    432        self.normalize = normalize
    433        self.pad = pad
    434        self._indent = indent
    435        self.unsupported_level = unsupported_level
    436        self.max_unsupported = max_unsupported
    437        self.leading_comma = leading_comma
    438        self.max_text_width = max_text_width
    439        self.comments = comments
    440
    441        # This is both a Dialect property and a Generator argument, so we prioritize the latter
    442        self.normalize_functions = (
    443            self.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions
    444        )
    445
    446        self.unsupported_messages: t.List[str] = []
    447        self._escaped_quote_end: str = self.TOKENIZER_CLASS.STRING_ESCAPES[0] + self.QUOTE_END
    448        self._escaped_identifier_end: str = (
    449            self.TOKENIZER_CLASS.IDENTIFIER_ESCAPES[0] + self.IDENTIFIER_END
    450        )
    451        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.InputModelProperty'>: <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.OutputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ReturnsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SampleProperty'>: <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.TransformModelProperty'>: <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>>}
LOG_BASE_FIRST = True
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'
LIMIT_ONLY_LITERALS = False
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
UNNEST_WITH_ORDINALITY = True
AGGREGATE_FILTER_SUPPORTED = True
SEMI_ANTI_JOIN_WITH_SIDE = True
SUPPORTS_PARAMETERS = True
COMPUTED_COLUMN_WITH_TYPE = True
SUPPORTS_TABLE_COPY = True
TABLESAMPLE_REQUIRES_PARENS = True
COLLATE_IS_FUNC = False
DATA_TYPE_SPECIFIERS_ALLOWED = False
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.InputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <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.OutputModelProperty'>: <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.RemoteWithConnectionModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <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.SampleProperty'>: <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.TransformModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <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'>)
EXCLUDE_COMMENTS: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Binary'>, <class 'sqlglot.expressions.Union'>)
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 = {}
INVERSE_ESCAPE_SEQUENCES: Dict[str, str] = {}
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'
@classmethod
def can_identify(text: str, identify: str | bool = 'safe') -> bool: View Source

    279    @classmethod
    280    def can_identify(cls, text: str, identify: str | bool = "safe") -> bool:
    281        """Checks if text can be identified given an identify option.
    282
    283        Args:
    284            text: The text to check.
    285            identify:
    286                "always" or `True`: Always returns true.
    287                "safe": True if the identifier is case-insensitive.
    288
    289        Returns:
    290            Whether or not the given text can be identified.
    291        """
    292        if identify is True or identify == "always":
    293            return True
    294
    295        if identify == "safe":
    296            return not cls.case_sensitive(text)
    297
    298        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

    453    def generate(
    454        self,
    455        expression: t.Optional[exp.Expression],
    456        cache: t.Optional[t.Dict[int, str]] = None,
    457    ) -> str:
    458        """
    459        Generates the SQL string corresponding to the given syntax tree.
    460
    461        Args:
    462            expression: The syntax tree.
    463            cache: An optional sql string cache. This leverages the hash of an Expression
    464                which can be slow to compute, so only use it if you set _hash on each node.
    465
    466        Returns:
    467            The SQL string corresponding to `expression`.
    468        """
    469        if cache is not None:
    470            self._cache = cache
    471
    472        self.unsupported_messages = []
    473        sql = self.sql(expression).strip()
    474        self._cache = None
    475
    476        if self.unsupported_level == ErrorLevel.IGNORE:
    477            return sql
    478
    479        if self.unsupported_level == ErrorLevel.WARN:
    480            for msg in self.unsupported_messages:
    481                logger.warning(msg)
    482        elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages:
    483            raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported))
    484
    485        if self.pretty:
    486            sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n")
    487        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

    489    def unsupported(self, message: str) -> None:
    490        if self.unsupported_level == ErrorLevel.IMMEDIATE:
    491            raise UnsupportedError(message)
    492        self.unsupported_messages.append(message)

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

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

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

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

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

    500    def pad_comment(self, comment: str) -> str:
    501        comment = " " + comment if comment[0].strip() else comment
    502        comment = comment + " " if comment[-1].strip() else comment
    503        return comment

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

    505    def maybe_comment(
    506        self,
    507        sql: str,
    508        expression: t.Optional[exp.Expression] = None,
    509        comments: t.Optional[t.List[str]] = None,
    510    ) -> str:
    511        comments = (
    512            ((expression and expression.comments) if comments is None else comments)  # type: ignore
    513            if self.comments
    514            else None
    515        )
    516
    517        if not comments or isinstance(expression, self.EXCLUDE_COMMENTS):
    518            return sql
    519
    520        comments_sql = " ".join(
    521            f"/*{self.pad_comment(comment)}*/" for comment in comments if comment
    522        )
    523
    524        if not comments_sql:
    525            return sql
    526
    527        if isinstance(expression, self.WITH_SEPARATED_COMMENTS):
    528            return (
    529                f"{self.sep()}{comments_sql}{sql}"
    530                if sql[0].isspace()
    531                else f"{comments_sql}{self.sep()}{sql}"
    532            )
    533
    534        return f"{sql} {comments_sql}"

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

    536    def wrap(self, expression: exp.Expression | str) -> str:
    537        this_sql = self.indent(
    538            self.sql(expression)
    539            if isinstance(expression, (exp.Select, exp.Union))
    540            else self.sql(expression, "this"),
    541            level=1,
    542            pad=0,
    543        )
    544        return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"

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

    546    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
    547        original = self.identify
    548        self.identify = False
    549        result = func(*args, **kwargs)
    550        self.identify = original
    551        return result

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

    553    def normalize_func(self, name: str) -> str:
    554        if self.normalize_functions == "upper" or self.normalize_functions is True:
    555            return name.upper()
    556        if self.normalize_functions == "lower":
    557            return name.lower()
    558        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

    560    def indent(
    561        self,
    562        sql: str,
    563        level: int = 0,
    564        pad: t.Optional[int] = None,
    565        skip_first: bool = False,
    566        skip_last: bool = False,
    567    ) -> str:
    568        if not self.pretty:
    569            return sql
    570
    571        pad = self.pad if pad is None else pad
    572        lines = sql.split("\n")
    573
    574        return "\n".join(
    575            line
    576            if (skip_first and i == 0) or (skip_last and i == len(lines) - 1)
    577            else f"{' ' * (level * self._indent + pad)}{line}"
    578            for i, line in enumerate(lines)
    579        )

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

    581    def sql(
    582        self,
    583        expression: t.Optional[str | exp.Expression],
    584        key: t.Optional[str] = None,
    585        comment: bool = True,
    586    ) -> str:
    587        if not expression:
    588            return ""
    589
    590        if isinstance(expression, str):
    591            return expression
    592
    593        if key:
    594            value = expression.args.get(key)
    595            if value:
    596                return self.sql(value)
    597            return ""
    598
    599        if self._cache is not None:
    600            expression_id = hash(expression)
    601
    602            if expression_id in self._cache:
    603                return self._cache[expression_id]
    604
    605        transform = self.TRANSFORMS.get(expression.__class__)
    606
    607        if callable(transform):
    608            sql = transform(self, expression)
    609        elif transform:
    610            sql = transform
    611        elif isinstance(expression, exp.Expression):
    612            exp_handler_name = f"{expression.key}_sql"
    613
    614            if hasattr(self, exp_handler_name):
    615                sql = getattr(self, exp_handler_name)(expression)
    616            elif isinstance(expression, exp.Func):
    617                sql = self.function_fallback_sql(expression)
    618            elif isinstance(expression, exp.Property):
    619                sql = self.property_sql(expression)
    620            else:
    621                raise ValueError(f"Unsupported expression type {expression.__class__.__name__}")
    622        else:
    623            raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}")
    624
    625        sql = self.maybe_comment(sql, expression) if self.comments and comment else sql
    626
    627        if self._cache is not None:
    628            self._cache[expression_id] = sql
    629        return sql

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

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

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

    636    def cache_sql(self, expression: exp.Cache) -> str:
    637        lazy = " LAZY" if expression.args.get("lazy") else ""
    638        table = self.sql(expression, "this")
    639        options = expression.args.get("options")
    640        options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else ""
    641        sql = self.sql(expression, "expression")
    642        sql = f" AS{self.sep()}{sql}" if sql else ""
    643        sql = f"CACHE{lazy} TABLE {table}{options}{sql}"
    644        return self.prepend_ctes(expression, sql)

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

    646    def characterset_sql(self, expression: exp.CharacterSet) -> str:
    647        if isinstance(expression.parent, exp.Cast):
    648            return f"CHAR CHARACTER SET {self.sql(expression, 'this')}"
    649        default = "DEFAULT " if expression.args.get("default") else ""
    650        return f"{default}CHARACTER SET={self.sql(expression, 'this')}"

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

    652    def column_sql(self, expression: exp.Column) -> str:
    653        join_mark = " (+)" if expression.args.get("join_mark") else ""
    654
    655        if join_mark and not self.COLUMN_JOIN_MARKS_SUPPORTED:
    656            join_mark = ""
    657            self.unsupported("Outer join syntax using the (+) operator is not supported.")
    658
    659        column = ".".join(
    660            self.sql(part)
    661            for part in (
    662                expression.args.get("catalog"),
    663                expression.args.get("db"),
    664                expression.args.get("table"),
    665                expression.args.get("this"),
    666            )
    667            if part
    668        )
    669
    670        return f"{column}{join_mark}"

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

    672    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
    673        this = self.sql(expression, "this")
    674        this = f" {this}" if this else ""
    675        position = self.sql(expression, "position")
    676        return f"{position}{this}"

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

    678    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
    679        column = self.sql(expression, "this")
    680        kind = self.sql(expression, "kind")
    681        constraints = self.expressions(expression, key="constraints", sep=" ", flat=True)
    682        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
    683        kind = f"{sep}{kind}" if kind else ""
    684        constraints = f" {constraints}" if constraints else ""
    685        position = self.sql(expression, "position")
    686        position = f" {position}" if position else ""
    687
    688        if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE:
    689            kind = ""
    690
    691        return f"{exists}{column}{kind}{constraints}{position}"

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

    693    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
    694        this = self.sql(expression, "this")
    695        kind_sql = self.sql(expression, "kind").strip()
    696        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql

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

    698    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
    699        this = self.sql(expression, "this")
    700        if expression.args.get("not_null"):
    701            persisted = " PERSISTED NOT NULL"
    702        elif expression.args.get("persisted"):
    703            persisted = " PERSISTED"
    704        else:
    705            persisted = ""
    706        return f"AS {this}{persisted}"

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

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

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

    711    def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str:
    712        if isinstance(expression.this, list):
    713            this = self.wrap(self.expressions(expression, key="this", flat=True))
    714        else:
    715            this = self.sql(expression, "this")
    716
    717        return f"COMPRESS {this}"

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

    719    def generatedasidentitycolumnconstraint_sql(
    720        self, expression: exp.GeneratedAsIdentityColumnConstraint
    721    ) -> str:
    722        this = ""
    723        if expression.this is not None:
    724            on_null = " ON NULL" if expression.args.get("on_null") else ""
    725            this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}"
    726
    727        start = expression.args.get("start")
    728        start = f"START WITH {start}" if start else ""
    729        increment = expression.args.get("increment")
    730        increment = f" INCREMENT BY {increment}" if increment else ""
    731        minvalue = expression.args.get("minvalue")
    732        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    733        maxvalue = expression.args.get("maxvalue")
    734        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    735        cycle = expression.args.get("cycle")
    736        cycle_sql = ""
    737
    738        if cycle is not None:
    739            cycle_sql = f"{' NO' if not cycle else ''} CYCLE"
    740            cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql
    741
    742        sequence_opts = ""
    743        if start or increment or cycle_sql:
    744            sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}"
    745            sequence_opts = f" ({sequence_opts.strip()})"
    746
    747        expr = self.sql(expression, "expression")
    748        expr = f"({expr})" if expr else "IDENTITY"
    749
    750        return f"GENERATED{this} AS {expr}{sequence_opts}"

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

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

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

    755    def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str:
    756        desc = expression.args.get("desc")
    757        if desc is not None:
    758            return f"PRIMARY KEY{' DESC' if desc else ' ASC'}"
    759        return f"PRIMARY KEY"

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

    761    def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str:
    762        this = self.sql(expression, "this")
    763        this = f" {this}" if this else ""
    764        index_type = expression.args.get("index_type")
    765        index_type = f" USING {index_type}" if index_type else ""
    766        return f"UNIQUE{this}{index_type}"

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

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

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

    771    def create_sql(self, expression: exp.Create) -> str:
    772        kind = self.sql(expression, "kind").upper()
    773        properties = expression.args.get("properties")
    774        properties_locs = self.locate_properties(properties) if properties else defaultdict()
    775
    776        this = self.createable_sql(expression, properties_locs)
    777
    778        properties_sql = ""
    779        if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get(
    780            exp.Properties.Location.POST_WITH
    781        ):
    782            properties_sql = self.sql(
    783                exp.Properties(
    784                    expressions=[
    785                        *properties_locs[exp.Properties.Location.POST_SCHEMA],
    786                        *properties_locs[exp.Properties.Location.POST_WITH],
    787                    ]
    788                )
    789            )
    790
    791        begin = " BEGIN" if expression.args.get("begin") else ""
    792        end = " END" if expression.args.get("end") else ""
    793
    794        expression_sql = self.sql(expression, "expression")
    795        if expression_sql:
    796            expression_sql = f"{begin}{self.sep()}{expression_sql}{end}"
    797
    798            if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return):
    799                if properties_locs.get(exp.Properties.Location.POST_ALIAS):
    800                    postalias_props_sql = self.properties(
    801                        exp.Properties(
    802                            expressions=properties_locs[exp.Properties.Location.POST_ALIAS]
    803                        ),
    804                        wrapped=False,
    805                    )
    806                    expression_sql = f" AS {postalias_props_sql}{expression_sql}"
    807                else:
    808                    expression_sql = f" AS{expression_sql}"
    809
    810        postindex_props_sql = ""
    811        if properties_locs.get(exp.Properties.Location.POST_INDEX):
    812            postindex_props_sql = self.properties(
    813                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]),
    814                wrapped=False,
    815                prefix=" ",
    816            )
    817
    818        indexes = self.expressions(expression, key="indexes", indent=False, sep=" ")
    819        indexes = f" {indexes}" if indexes else ""
    820        index_sql = indexes + postindex_props_sql
    821
    822        replace = " OR REPLACE" if expression.args.get("replace") else ""
    823        unique = " UNIQUE" if expression.args.get("unique") else ""
    824
    825        postcreate_props_sql = ""
    826        if properties_locs.get(exp.Properties.Location.POST_CREATE):
    827            postcreate_props_sql = self.properties(
    828                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]),
    829                sep=" ",
    830                prefix=" ",
    831                wrapped=False,
    832            )
    833
    834        modifiers = "".join((replace, unique, postcreate_props_sql))
    835
    836        postexpression_props_sql = ""
    837        if properties_locs.get(exp.Properties.Location.POST_EXPRESSION):
    838            postexpression_props_sql = self.properties(
    839                exp.Properties(
    840                    expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION]
    841                ),
    842                sep=" ",
    843                prefix=" ",
    844                wrapped=False,
    845            )
    846
    847        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
    848        no_schema_binding = (
    849            " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else ""
    850        )
    851
    852        clone = self.sql(expression, "clone")
    853        clone = f" {clone}" if clone else ""
    854
    855        expression_sql = f"CREATE{modifiers} {kind}{exists_sql} {this}{properties_sql}{expression_sql}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}"
    856        return self.prepend_ctes(expression, expression_sql)

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

    858    def clone_sql(self, expression: exp.Clone) -> str:
    859        this = self.sql(expression, "this")
    860        shallow = "SHALLOW " if expression.args.get("shallow") else ""
    861        keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE"
    862        this = f"{shallow}{keyword} {this}"
    863        when = self.sql(expression, "when")
    864
    865        if when:
    866            kind = self.sql(expression, "kind")
    867            expr = self.sql(expression, "expression")
    868            return f"{this} {when} ({kind} => {expr})"
    869
    870        return this

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

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

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

    875    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
    876        with_ = self.sql(expression, "with")
    877        if with_:
    878            sql = f"{with_}{self.sep()}{sql}"
    879        return sql

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

    881    def with_sql(self, expression: exp.With) -> str:
    882        sql = self.expressions(expression, flat=True)
    883        recursive = "RECURSIVE " if expression.args.get("recursive") else ""
    884
    885        return f"WITH {recursive}{sql}"

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

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

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

    891    def tablealias_sql(self, expression: exp.TableAlias) -> str:
    892        alias = self.sql(expression, "this")
    893        columns = self.expressions(expression, key="columns", flat=True)
    894        columns = f"({columns})" if columns else ""
    895
    896        if not alias and not self.UNNEST_COLUMN_ONLY:
    897            alias = "_t"
    898
    899        return f"{alias}{columns}"

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

    901    def bitstring_sql(self, expression: exp.BitString) -> str:
    902        this = self.sql(expression, "this")
    903        if self.BIT_START:
    904            return f"{self.BIT_START}{this}{self.BIT_END}"
    905        return f"{int(this, 2)}"

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

    907    def hexstring_sql(self, expression: exp.HexString) -> str:
    908        this = self.sql(expression, "this")
    909        if self.HEX_START:
    910            return f"{self.HEX_START}{this}{self.HEX_END}"
    911        return f"{int(this, 16)}"

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

    913    def bytestring_sql(self, expression: exp.ByteString) -> str:
    914        this = self.sql(expression, "this")
    915        if self.BYTE_START:
    916            return f"{self.BYTE_START}{this}{self.BYTE_END}"
    917        return this

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

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

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

    923    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
    924        this = self.sql(expression, "this")
    925        specifier = self.sql(expression, "expression")
    926        specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else ""
    927        return f"{this}{specifier}"

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

    929    def datatype_sql(self, expression: exp.DataType) -> str:
    930        type_value = expression.this
    931
    932        if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"):
    933            type_sql = self.sql(expression, "kind")
    934        else:
    935            type_sql = (
    936                self.TYPE_MAPPING.get(type_value, type_value.value)
    937                if isinstance(type_value, exp.DataType.Type)
    938                else type_value
    939            )
    940
    941        nested = ""
    942        interior = self.expressions(expression, flat=True)
    943        values = ""
    944
    945        if interior:
    946            if expression.args.get("nested"):
    947                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
    948                if expression.args.get("values") is not None:
    949                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
    950                    values = self.expressions(expression, key="values", flat=True)
    951                    values = f"{delimiters[0]}{values}{delimiters[1]}"
    952            elif type_value == exp.DataType.Type.INTERVAL:
    953                nested = f" {interior}"
    954            else:
    955                nested = f"({interior})"
    956
    957        type_sql = f"{type_sql}{nested}{values}"
    958        if self.TZ_TO_WITH_TIME_ZONE and type_value in (
    959            exp.DataType.Type.TIMETZ,
    960            exp.DataType.Type.TIMESTAMPTZ,
    961        ):
    962            type_sql = f"{type_sql} WITH TIME ZONE"
    963
    964        return type_sql

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

    966    def directory_sql(self, expression: exp.Directory) -> str:
    967        local = "LOCAL " if expression.args.get("local") else ""
    968        row_format = self.sql(expression, "row_format")
    969        row_format = f" {row_format}" if row_format else ""
    970        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"

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

    972    def delete_sql(self, expression: exp.Delete) -> str:
    973        this = self.sql(expression, "this")
    974        this = f" FROM {this}" if this else ""
    975        using = self.sql(expression, "using")
    976        using = f" USING {using}" if using else ""
    977        where = self.sql(expression, "where")
    978        returning = self.sql(expression, "returning")
    979        limit = self.sql(expression, "limit")
    980        tables = self.expressions(expression, key="tables")
    981        tables = f" {tables}" if tables else ""
    982        if self.RETURNING_END:
    983            expression_sql = f"{this}{using}{where}{returning}{limit}"
    984        else:
    985            expression_sql = f"{returning}{this}{using}{where}{limit}"
    986        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")

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

    988    def drop_sql(self, expression: exp.Drop) -> str:
    989        this = self.sql(expression, "this")
    990        kind = expression.args["kind"]
    991        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    992        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    993        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    994        cascade = " CASCADE" if expression.args.get("cascade") else ""
    995        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
    996        purge = " PURGE" if expression.args.get("purge") else ""
    997        return (
    998            f"DROP{temporary}{materialized} {kind}{exists_sql}{this}{cascade}{constraints}{purge}"
    999        )

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

    1001    def except_sql(self, expression: exp.Except) -> str:
    1002        return self.prepend_ctes(
    1003            expression,
    1004            self.set_operation(expression, self.except_op(expression)),
    1005        )

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

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

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

    1010    def fetch_sql(self, expression: exp.Fetch) -> str:
    1011        direction = expression.args.get("direction")
    1012        direction = f" {direction.upper()}" if direction else ""
    1013        count = expression.args.get("count")
    1014        count = f" {count}" if count else ""
    1015        if expression.args.get("percent"):
    1016            count = f"{count} PERCENT"
    1017        with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY"
    1018        return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}"

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

    1020    def filter_sql(self, expression: exp.Filter) -> str:
    1021        if self.AGGREGATE_FILTER_SUPPORTED:
    1022            this = self.sql(expression, "this")
    1023            where = self.sql(expression, "expression").strip()
    1024            return f"{this} FILTER({where})"
    1025
    1026        agg = expression.this.copy()
    1027        agg_arg = agg.this
    1028        cond = expression.expression.this
    1029        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
    1030        return self.sql(agg)

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

    1032    def hint_sql(self, expression: exp.Hint) -> str:
    1033        if not self.QUERY_HINTS:
    1034            self.unsupported("Hints are not supported")
    1035            return ""
    1036
    1037        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"

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

    1039    def index_sql(self, expression: exp.Index) -> str:
    1040        unique = "UNIQUE " if expression.args.get("unique") else ""
    1041        primary = "PRIMARY " if expression.args.get("primary") else ""
    1042        amp = "AMP " if expression.args.get("amp") else ""
    1043        name = self.sql(expression, "this")
    1044        name = f"{name} " if name else ""
    1045        table = self.sql(expression, "table")
    1046        table = f"{self.INDEX_ON} {table}" if table else ""
    1047        using = self.sql(expression, "using")
    1048        using = f" USING {using}" if using else ""
    1049        index = "INDEX " if not table else ""
    1050        columns = self.expressions(expression, key="columns", flat=True)
    1051        columns = f"({columns})" if columns else ""
    1052        partition_by = self.expressions(expression, key="partition_by", flat=True)
    1053        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
    1054        where = self.sql(expression, "where")
    1055        return f"{unique}{primary}{amp}{index}{name}{table}{using}{columns}{partition_by}{where}"

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

    1057    def identifier_sql(self, expression: exp.Identifier) -> str:
    1058        text = expression.name
    1059        lower = text.lower()
    1060        text = lower if self.normalize and not expression.quoted else text
    1061        text = text.replace(self.IDENTIFIER_END, self._escaped_identifier_end)
    1062        if (
    1063            expression.quoted
    1064            or self.can_identify(text, self.identify)
    1065            or lower in self.RESERVED_KEYWORDS
    1066            or (not self.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
    1067        ):
    1068            text = f"{self.IDENTIFIER_START}{text}{self.IDENTIFIER_END}"
    1069        return text

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

    1071    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    1072        input_format = self.sql(expression, "input_format")
    1073        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    1074        output_format = self.sql(expression, "output_format")
    1075        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    1076        return self.sep().join((input_format, output_format))

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

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

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

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

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

    1085    def properties_sql(self, expression: exp.Properties) -> str:
    1086        root_properties = []
    1087        with_properties = []
    1088
    1089        for p in expression.expressions:
    1090            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1091            if p_loc == exp.Properties.Location.POST_WITH:
    1092                with_properties.append(p.copy())
    1093            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    1094                root_properties.append(p.copy())
    1095
    1096        return self.root_properties(
    1097            exp.Properties(expressions=root_properties)
    1098        ) + self.with_properties(exp.Properties(expressions=with_properties))

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

    1100    def root_properties(self, properties: exp.Properties) -> str:
    1101        if properties.expressions:
    1102            return self.sep() + self.expressions(properties, indent=False, sep=" ")
    1103        return ""

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

    1105    def properties(
    1106        self,
    1107        properties: exp.Properties,
    1108        prefix: str = "",
    1109        sep: str = ", ",
    1110        suffix: str = "",
    1111        wrapped: bool = True,
    1112    ) -> str:
    1113        if properties.expressions:
    1114            expressions = self.expressions(properties, sep=sep, indent=False)
    1115            if expressions:
    1116                expressions = self.wrap(expressions) if wrapped else expressions
    1117                return f"{prefix}{' ' if prefix and prefix != ' ' else ''}{expressions}{suffix}"
    1118        return ""

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

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

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

    1123    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
    1124        properties_locs = defaultdict(list)
    1125        for p in properties.expressions:
    1126            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1127            if p_loc != exp.Properties.Location.UNSUPPORTED:
    1128                properties_locs[p_loc].append(p.copy())
    1129            else:
    1130                self.unsupported(f"Unsupported property {p.key}")
    1131
    1132        return properties_locs

def property_name( self, expression: sqlglot.expressions.Property, string_key: bool = False) -> str: View Source

    1134    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
    1135        if isinstance(expression.this, exp.Dot):
    1136            return self.sql(expression, "this")
    1137        return f"'{expression.name}'" if string_key else expression.name

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

    1139    def property_sql(self, expression: exp.Property) -> str:
    1140        property_cls = expression.__class__
    1141        if property_cls == exp.Property:
    1142            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
    1143
    1144        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    1145        if not property_name:
    1146            self.unsupported(f"Unsupported property {expression.key}")
    1147
    1148        return f"{property_name}={self.sql(expression, 'this')}"

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

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

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

    1155    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1156        no = "NO " if expression.args.get("no") else ""
    1157        protection = " PROTECTION" if expression.args.get("protection") else ""
    1158        return f"{no}FALLBACK{protection}"

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

    1160    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1161        no = "NO " if expression.args.get("no") else ""
    1162        local = expression.args.get("local")
    1163        local = f"{local} " if local else ""
    1164        dual = "DUAL " if expression.args.get("dual") else ""
    1165        before = "BEFORE " if expression.args.get("before") else ""
    1166        after = "AFTER " if expression.args.get("after") else ""
    1167        return f"{no}{local}{dual}{before}{after}JOURNAL"

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

    1169    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1170        freespace = self.sql(expression, "this")
    1171        percent = " PERCENT" if expression.args.get("percent") else ""
    1172        return f"FREESPACE={freespace}{percent}"

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

    1174    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1175        if expression.args.get("default"):
    1176            property = "DEFAULT"
    1177        elif expression.args.get("on"):
    1178            property = "ON"
    1179        else:
    1180            property = "OFF"
    1181        return f"CHECKSUM={property}"

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

    1183    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1184        if expression.args.get("no"):
    1185            return "NO MERGEBLOCKRATIO"
    1186        if expression.args.get("default"):
    1187            return "DEFAULT MERGEBLOCKRATIO"
    1188
    1189        percent = " PERCENT" if expression.args.get("percent") else ""
    1190        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"

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

    1192    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1193        default = expression.args.get("default")
    1194        minimum = expression.args.get("minimum")
    1195        maximum = expression.args.get("maximum")
    1196        if default or minimum or maximum:
    1197            if default:
    1198                prop = "DEFAULT"
    1199            elif minimum:
    1200                prop = "MINIMUM"
    1201            else:
    1202                prop = "MAXIMUM"
    1203            return f"{prop} DATABLOCKSIZE"
    1204        units = expression.args.get("units")
    1205        units = f" {units}" if units else ""
    1206        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"

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

    1208    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1209        autotemp = expression.args.get("autotemp")
    1210        always = expression.args.get("always")
    1211        default = expression.args.get("default")
    1212        manual = expression.args.get("manual")
    1213        never = expression.args.get("never")
    1214
    1215        if autotemp is not None:
    1216            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1217        elif always:
    1218            prop = "ALWAYS"
    1219        elif default:
    1220            prop = "DEFAULT"
    1221        elif manual:
    1222            prop = "MANUAL"
    1223        elif never:
    1224            prop = "NEVER"
    1225        return f"BLOCKCOMPRESSION={prop}"

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

    1227    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1228        no = expression.args.get("no")
    1229        no = " NO" if no else ""
    1230        concurrent = expression.args.get("concurrent")
    1231        concurrent = " CONCURRENT" if concurrent else ""
    1232
    1233        for_ = ""
    1234        if expression.args.get("for_all"):
    1235            for_ = " FOR ALL"
    1236        elif expression.args.get("for_insert"):
    1237            for_ = " FOR INSERT"
    1238        elif expression.args.get("for_none"):
    1239            for_ = " FOR NONE"
    1240        return f"WITH{no}{concurrent} ISOLATED LOADING{for_}"

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

    1242    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1243        kind = expression.args.get("kind")
    1244        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1245        for_or_in = expression.args.get("for_or_in")
    1246        for_or_in = f" {for_or_in}" if for_or_in else ""
    1247        lock_type = expression.args.get("lock_type")
    1248        override = " OVERRIDE" if expression.args.get("override") else ""
    1249        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"

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

    1251    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1252        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1253        statistics = expression.args.get("statistics")
    1254        statistics_sql = ""
    1255        if statistics is not None:
    1256            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1257        return f"{data_sql}{statistics_sql}"

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

    1259    def insert_sql(self, expression: exp.Insert) -> str:
    1260        overwrite = expression.args.get("overwrite")
    1261
    1262        if isinstance(expression.this, exp.Directory):
    1263            this = " OVERWRITE" if overwrite else " INTO"
    1264        else:
    1265            this = " OVERWRITE TABLE" if overwrite else " INTO"
    1266
    1267        alternative = expression.args.get("alternative")
    1268        alternative = f" OR {alternative}" if alternative else ""
    1269        ignore = " IGNORE" if expression.args.get("ignore") else ""
    1270
    1271        this = f"{this} {self.sql(expression, 'this')}"
    1272
    1273        exists = " IF EXISTS" if expression.args.get("exists") else ""
    1274        partition_sql = (
    1275            f" {self.sql(expression, 'partition')}" if expression.args.get("partition") else ""
    1276        )
    1277        where = self.sql(expression, "where")
    1278        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
    1279        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
    1280        conflict = self.sql(expression, "conflict")
    1281        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1282        returning = self.sql(expression, "returning")
    1283
    1284        if self.RETURNING_END:
    1285            expression_sql = f"{expression_sql}{conflict}{returning}"
    1286        else:
    1287            expression_sql = f"{returning}{expression_sql}{conflict}"
    1288
    1289        sql = f"INSERT{alternative}{ignore}{this}{by_name}{exists}{partition_sql}{where}{expression_sql}"
    1290        return self.prepend_ctes(expression, sql)

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

    1292    def intersect_sql(self, expression: exp.Intersect) -> str:
    1293        return self.prepend_ctes(
    1294            expression,
    1295            self.set_operation(expression, self.intersect_op(expression)),
    1296        )

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

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

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

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

def kill_sql(self, expression: sqlglot.expressions.Kill) -> str: View Source

    1304    def kill_sql(self, expression: exp.Kill) -> str:
    1305        kind = self.sql(expression, "kind")
    1306        kind = f" {kind}" if kind else ""
    1307        this = self.sql(expression, "this")
    1308        this = f" {this}" if this else ""
    1309        return f"KILL{kind}{this}"

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

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

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

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

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

    1317    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1318        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1319        constraint = self.sql(expression, "constraint")
    1320        if constraint:
    1321            constraint = f"ON CONSTRAINT {constraint}"
    1322        key = self.expressions(expression, key="key", flat=True)
    1323        do = "" if expression.args.get("duplicate") else " DO "
    1324        nothing = "NOTHING" if expression.args.get("nothing") else ""
    1325        expressions = self.expressions(expression, flat=True)
    1326        set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
    1327        if expressions:
    1328            expressions = f"UPDATE {set_keyword}{expressions}"
    1329        return f"{self.seg(conflict)} {constraint}{key}{do}{nothing}{expressions}"

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

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

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

    1334    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1335        fields = expression.args.get("fields")
    1336        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1337        escaped = expression.args.get("escaped")
    1338        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1339        items = expression.args.get("collection_items")
    1340        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1341        keys = expression.args.get("map_keys")
    1342        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1343        lines = expression.args.get("lines")
    1344        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1345        null = expression.args.get("null")
    1346        null = f" NULL DEFINED AS {null}" if null else ""
    1347        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"

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

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

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

    1352    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1353        this = f"{self.sql(expression, 'this')} INDEX"
    1354        target = self.sql(expression, "target")
    1355        target = f" FOR {target}" if target else ""
    1356        return f"{this}{target} ({self.expressions(expression, flat=True)})"

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

    1358    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1359        table = ".".join(
    1360            part
    1361            for part in [
    1362                self.sql(expression, "catalog"),
    1363                self.sql(expression, "db"),
    1364                self.sql(expression, "this"),
    1365            ]
    1366            if part
    1367        )
    1368
    1369        version = self.sql(expression, "version")
    1370        version = f" {version}" if version else ""
    1371        alias = self.sql(expression, "alias")
    1372        alias = f"{sep}{alias}" if alias else ""
    1373        hints = self.expressions(expression, key="hints", sep=" ")
    1374        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
    1375        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    1376        pivots = f" {pivots}" if pivots else ""
    1377        joins = self.expressions(expression, key="joins", sep="", skip_first=True)
    1378        laterals = self.expressions(expression, key="laterals", sep="")
    1379
    1380        file_format = self.sql(expression, "format")
    1381        if file_format:
    1382            pattern = self.sql(expression, "pattern")
    1383            pattern = f", PATTERN => {pattern}" if pattern else ""
    1384            file_format = f" (FILE_FORMAT => {file_format}{pattern})"
    1385
    1386        index = self.sql(expression, "index")
    1387        index = f" AT {index}" if index else ""
    1388
    1389        return f"{table}{version}{file_format}{alias}{index}{hints}{pivots}{joins}{laterals}"

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

    1391    def tablesample_sql(
    1392        self, expression: exp.TableSample, seed_prefix: str = "SEED", sep=" AS "
    1393    ) -> str:
    1394        if self.ALIAS_POST_TABLESAMPLE and expression.this.alias:
    1395            table = expression.this.copy()
    1396            table.set("alias", None)
    1397            this = self.sql(table)
    1398            alias = f"{sep}{self.sql(expression.this, 'alias')}"
    1399        else:
    1400            this = self.sql(expression, "this")
    1401            alias = ""
    1402
    1403        method = self.sql(expression, "method")
    1404        method = f"{method.upper()} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    1405        numerator = self.sql(expression, "bucket_numerator")
    1406        denominator = self.sql(expression, "bucket_denominator")
    1407        field = self.sql(expression, "bucket_field")
    1408        field = f" ON {field}" if field else ""
    1409        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    1410        percent = self.sql(expression, "percent")
    1411        percent = f"{percent} PERCENT" if percent else ""
    1412        rows = self.sql(expression, "rows")
    1413        rows = f"{rows} ROWS" if rows else ""
    1414
    1415        size = self.sql(expression, "size")
    1416        if size and self.TABLESAMPLE_SIZE_IS_PERCENT:
    1417            size = f"{size} PERCENT"
    1418
    1419        seed = self.sql(expression, "seed")
    1420        seed = f" {seed_prefix} ({seed})" if seed else ""
    1421        kind = expression.args.get("kind", "TABLESAMPLE")
    1422
    1423        expr = f"{bucket}{percent}{rows}{size}"
    1424        if self.TABLESAMPLE_REQUIRES_PARENS:
    1425            expr = f"({expr})"
    1426
    1427        return f"{this} {kind} {method}{expr}{seed}{alias}"

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

    1429    def pivot_sql(self, expression: exp.Pivot) -> str:
    1430        expressions = self.expressions(expression, flat=True)
    1431
    1432        if expression.this:
    1433            this = self.sql(expression, "this")
    1434            if not expressions:
    1435                return f"UNPIVOT {this}"
    1436
    1437            on = f"{self.seg('ON')} {expressions}"
    1438            using = self.expressions(expression, key="using", flat=True)
    1439            using = f"{self.seg('USING')} {using}" if using else ""
    1440            group = self.sql(expression, "group")
    1441            return f"PIVOT {this}{on}{using}{group}"
    1442
    1443        alias = self.sql(expression, "alias")
    1444        alias = f" AS {alias}" if alias else ""
    1445        unpivot = expression.args.get("unpivot")
    1446        direction = "UNPIVOT" if unpivot else "PIVOT"
    1447        field = self.sql(expression, "field")
    1448        include_nulls = expression.args.get("include_nulls")
    1449        if include_nulls is not None:
    1450            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
    1451        else:
    1452            nulls = ""
    1453        return f"{direction}{nulls}({expressions} FOR {field}){alias}"

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

    1455    def version_sql(self, expression: exp.Version) -> str:
    1456        this = f"FOR {expression.name}"
    1457        kind = expression.text("kind")
    1458        expr = self.sql(expression, "expression")
    1459        return f"{this} {kind} {expr}"

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

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

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

    1464    def update_sql(self, expression: exp.Update) -> str:
    1465        this = self.sql(expression, "this")
    1466        set_sql = self.expressions(expression, flat=True)
    1467        from_sql = self.sql(expression, "from")
    1468        where_sql = self.sql(expression, "where")
    1469        returning = self.sql(expression, "returning")
    1470        order = self.sql(expression, "order")
    1471        limit = self.sql(expression, "limit")
    1472        if self.RETURNING_END:
    1473            expression_sql = f"{from_sql}{where_sql}{returning}"
    1474        else:
    1475            expression_sql = f"{returning}{from_sql}{where_sql}"
    1476        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
    1477        return self.prepend_ctes(expression, sql)

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

    1479    def values_sql(self, expression: exp.Values) -> str:
    1480        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
    1481        if self.VALUES_AS_TABLE or not expression.find_ancestor(exp.From, exp.Join):
    1482            args = self.expressions(expression)
    1483            alias = self.sql(expression, "alias")
    1484            values = f"VALUES{self.seg('')}{args}"
    1485            values = (
    1486                f"({values})"
    1487                if self.WRAP_DERIVED_VALUES and (alias or isinstance(expression.parent, exp.From))
    1488                else values
    1489            )
    1490            return f"{values} AS {alias}" if alias else values
    1491
    1492        # Converts `VALUES...` expression into a series of select unions.
    1493        expression = expression.copy()
    1494        alias_node = expression.args.get("alias")
    1495        column_names = alias_node and alias_node.columns
    1496
    1497        selects: t.List[exp.Subqueryable] = []
    1498
    1499        for i, tup in enumerate(expression.expressions):
    1500            row = tup.expressions
    1501
    1502            if i == 0 and column_names:
    1503                row = [
    1504                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
    1505                ]
    1506
    1507            selects.append(exp.Select(expressions=row))
    1508
    1509        if self.pretty:
    1510            # This may result in poor performance for large-cardinality `VALUES` tables, due to
    1511            # the deep nesting of the resulting exp.Unions. If this is a problem, either increase
    1512            # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`.
    1513            subqueryable = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects)
    1514            return self.subquery_sql(
    1515                subqueryable.subquery(alias_node and alias_node.this, copy=False)
    1516            )
    1517
    1518        alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else ""
    1519        unions = " UNION ALL ".join(self.sql(select) for select in selects)
    1520        return f"({unions}){alias}"

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

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

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

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

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

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

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

    1533    def group_sql(self, expression: exp.Group) -> str:
    1534        group_by = self.op_expressions("GROUP BY", expression)
    1535
    1536        if expression.args.get("all"):
    1537            return f"{group_by} ALL"
    1538
    1539        grouping_sets = self.expressions(expression, key="grouping_sets", indent=False)
    1540        grouping_sets = (
    1541            f"{self.seg('GROUPING SETS')} {self.wrap(grouping_sets)}" if grouping_sets else ""
    1542        )
    1543
    1544        cube = expression.args.get("cube", [])
    1545        if seq_get(cube, 0) is True:
    1546            return f"{group_by}{self.seg('WITH CUBE')}"
    1547        else:
    1548            cube_sql = self.expressions(expression, key="cube", indent=False)
    1549            cube_sql = f"{self.seg('CUBE')} {self.wrap(cube_sql)}" if cube_sql else ""
    1550
    1551        rollup = expression.args.get("rollup", [])
    1552        if seq_get(rollup, 0) is True:
    1553            return f"{group_by}{self.seg('WITH ROLLUP')}"
    1554        else:
    1555            rollup_sql = self.expressions(expression, key="rollup", indent=False)
    1556            rollup_sql = f"{self.seg('ROLLUP')} {self.wrap(rollup_sql)}" if rollup_sql else ""
    1557
    1558        groupings = csv(
    1559            grouping_sets,
    1560            cube_sql,
    1561            rollup_sql,
    1562            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    1563            sep=self.GROUPINGS_SEP,
    1564        )
    1565
    1566        if expression.args.get("expressions") and groupings:
    1567            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    1568
    1569        return f"{group_by}{groupings}"

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

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

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

    1575    def connect_sql(self, expression: exp.Connect) -> str:
    1576        start = self.sql(expression, "start")
    1577        start = self.seg(f"START WITH {start}") if start else ""
    1578        connect = self.sql(expression, "connect")
    1579        connect = self.seg(f"CONNECT BY {connect}")
    1580        return start + connect

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

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

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

    1585    def join_sql(self, expression: exp.Join) -> str:
    1586        if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"):
    1587            side = None
    1588        else:
    1589            side = expression.side
    1590
    1591        op_sql = " ".join(
    1592            op
    1593            for op in (
    1594                expression.method,
    1595                "GLOBAL" if expression.args.get("global") else None,
    1596                side,
    1597                expression.kind,
    1598                expression.hint if self.JOIN_HINTS else None,
    1599            )
    1600            if op
    1601        )
    1602        on_sql = self.sql(expression, "on")
    1603        using = expression.args.get("using")
    1604
    1605        if not on_sql and using:
    1606            on_sql = csv(*(self.sql(column) for column in using))
    1607
    1608        this_sql = self.sql(expression, "this")
    1609
    1610        if on_sql:
    1611            on_sql = self.indent(on_sql, skip_first=True)
    1612            space = self.seg(" " * self.pad) if self.pretty else " "
    1613            if using:
    1614                on_sql = f"{space}USING ({on_sql})"
    1615            else:
    1616                on_sql = f"{space}ON {on_sql}"
    1617        elif not op_sql:
    1618            return f", {this_sql}"
    1619
    1620        op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    1621        return f"{self.seg(op_sql)} {this_sql}{on_sql}"

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

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

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

    1628    def lateral_sql(self, expression: exp.Lateral) -> str:
    1629        this = self.sql(expression, "this")
    1630
    1631        if expression.args.get("view"):
    1632            alias = expression.args["alias"]
    1633            columns = self.expressions(alias, key="columns", flat=True)
    1634            table = f" {alias.name}" if alias.name else ""
    1635            columns = f" AS {columns}" if columns else ""
    1636            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    1637            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    1638
    1639        alias = self.sql(expression, "alias")
    1640        alias = f" AS {alias}" if alias else ""
    1641        return f"LATERAL {this}{alias}"

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

    1643    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    1644        this = self.sql(expression, "this")
    1645        args = ", ".join(
    1646            self.sql(self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e)
    1647            for e in (expression.args.get(k) for k in ("offset", "expression"))
    1648            if e
    1649        )
    1650        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args}"

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

    1652    def offset_sql(self, expression: exp.Offset) -> str:
    1653        this = self.sql(expression, "this")
    1654        expression = expression.expression
    1655        expression = (
    1656            self._simplify_unless_literal(expression) if self.LIMIT_ONLY_LITERALS else expression
    1657        )
    1658        return f"{this}{self.seg('OFFSET')} {self.sql(expression)}"

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

    1660    def setitem_sql(self, expression: exp.SetItem) -> str:
    1661        kind = self.sql(expression, "kind")
    1662        kind = f"{kind} " if kind else ""
    1663        this = self.sql(expression, "this")
    1664        expressions = self.expressions(expression)
    1665        collate = self.sql(expression, "collate")
    1666        collate = f" COLLATE {collate}" if collate else ""
    1667        global_ = "GLOBAL " if expression.args.get("global") else ""
    1668        return f"{global_}{kind}{this}{expressions}{collate}"

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

    1670    def set_sql(self, expression: exp.Set) -> str:
    1671        expressions = (
    1672            f" {self.expressions(expression, flat=True)}" if expression.expressions else ""
    1673        )
    1674        tag = " TAG" if expression.args.get("tag") else ""
    1675        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"

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

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

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

    1680    def lock_sql(self, expression: exp.Lock) -> str:
    1681        if not self.LOCKING_READS_SUPPORTED:
    1682            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    1683            return ""
    1684
    1685        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    1686        expressions = self.expressions(expression, flat=True)
    1687        expressions = f" OF {expressions}" if expressions else ""
    1688        wait = expression.args.get("wait")
    1689
    1690        if wait is not None:
    1691            if isinstance(wait, exp.Literal):
    1692                wait = f" WAIT {self.sql(wait)}"
    1693            else:
    1694                wait = " NOWAIT" if wait else " SKIP LOCKED"
    1695
    1696        return f"{lock_type}{expressions}{wait or ''}"

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

    1698    def literal_sql(self, expression: exp.Literal) -> str:
    1699        text = expression.this or ""
    1700        if expression.is_string:
    1701            text = f"{self.QUOTE_START}{self.escape_str(text)}{self.QUOTE_END}"
    1702        return text

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

    1704    def escape_str(self, text: str) -> str:
    1705        text = text.replace(self.QUOTE_END, self._escaped_quote_end)
    1706        if self.INVERSE_ESCAPE_SEQUENCES:
    1707            text = "".join(self.INVERSE_ESCAPE_SEQUENCES.get(ch, ch) for ch in text)
    1708        elif self.pretty:
    1709            text = text.replace("\n", self.SENTINEL_LINE_BREAK)
    1710        return text

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

    1712    def loaddata_sql(self, expression: exp.LoadData) -> str:
    1713        local = " LOCAL" if expression.args.get("local") else ""
    1714        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    1715        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    1716        this = f" INTO TABLE {self.sql(expression, 'this')}"
    1717        partition = self.sql(expression, "partition")
    1718        partition = f" {partition}" if partition else ""
    1719        input_format = self.sql(expression, "input_format")
    1720        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    1721        serde = self.sql(expression, "serde")
    1722        serde = f" SERDE {serde}" if serde else ""
    1723        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"

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

    1725    def null_sql(self, *_) -> str:
    1726        return "NULL"

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

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

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

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

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

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

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

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

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

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

    1745    def ordered_sql(self, expression: exp.Ordered) -> str:
    1746        desc = expression.args.get("desc")
    1747        asc = not desc
    1748
    1749        nulls_first = expression.args.get("nulls_first")
    1750        nulls_last = not nulls_first
    1751        nulls_are_large = self.NULL_ORDERING == "nulls_are_large"
    1752        nulls_are_small = self.NULL_ORDERING == "nulls_are_small"
    1753        nulls_are_last = self.NULL_ORDERING == "nulls_are_last"
    1754
    1755        sort_order = " DESC" if desc else (" ASC" if desc is False else "")
    1756        nulls_sort_change = ""
    1757        if nulls_first and (
    1758            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
    1759        ):
    1760            nulls_sort_change = " NULLS FIRST"
    1761        elif (
    1762            nulls_last
    1763            and ((asc and nulls_are_small) or (desc and nulls_are_large))
    1764            and not nulls_are_last
    1765        ):
    1766            nulls_sort_change = " NULLS LAST"
    1767
    1768        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
    1769            self.unsupported(
    1770                "Sorting in an ORDER BY on NULLS FIRST/NULLS LAST is not supported by this dialect"
    1771            )
    1772            nulls_sort_change = ""
    1773
    1774        return f"{self.sql(expression, 'this')}{sort_order}{nulls_sort_change}"

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

    1776    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    1777        partition = self.partition_by_sql(expression)
    1778        order = self.sql(expression, "order")
    1779        measures = self.expressions(expression, key="measures")
    1780        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    1781        rows = self.sql(expression, "rows")
    1782        rows = self.seg(rows) if rows else ""
    1783        after = self.sql(expression, "after")
    1784        after = self.seg(after) if after else ""
    1785        pattern = self.sql(expression, "pattern")
    1786        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    1787        definition_sqls = [
    1788            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    1789            for definition in expression.args.get("define", [])
    1790        ]
    1791        definitions = self.expressions(sqls=definition_sqls)
    1792        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    1793        body = "".join(
    1794            (
    1795                partition,
    1796                order,
    1797                measures,
    1798                rows,
    1799                after,
    1800                pattern,
    1801                define,
    1802            )
    1803        )
    1804        alias = self.sql(expression, "alias")
    1805        alias = f" {alias}" if alias else ""
    1806        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"

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

    1808    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    1809        limit: t.Optional[exp.Fetch | exp.Limit] = expression.args.get("limit")
    1810
    1811        # If the limit is generated as TOP, we need to ensure it's not generated twice
    1812        with_offset_limit_modifiers = not isinstance(limit, exp.Limit) or not self.LIMIT_IS_TOP
    1813
    1814        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    1815            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
    1816        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    1817            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
    1818
    1819        fetch = isinstance(limit, exp.Fetch)
    1820
    1821        offset_limit_modifiers = (
    1822            self.offset_limit_modifiers(expression, fetch, limit)
    1823            if with_offset_limit_modifiers
    1824            else []
    1825        )
    1826
    1827        return csv(
    1828            *sqls,
    1829            *[self.sql(join) for join in expression.args.get("joins") or []],
    1830            self.sql(expression, "connect"),
    1831            self.sql(expression, "match"),
    1832            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    1833            self.sql(expression, "where"),
    1834            self.sql(expression, "group"),
    1835            self.sql(expression, "having"),
    1836            *self.after_having_modifiers(expression),
    1837            self.sql(expression, "order"),
    1838            *offset_limit_modifiers,
    1839            *self.after_limit_modifiers(expression),
    1840            sep="",
    1841        )

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

    1843    def offset_limit_modifiers(
    1844        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    1845    ) -> t.List[str]:
    1846        return [
    1847            self.sql(expression, "offset") if fetch else self.sql(limit),
    1848            self.sql(limit) if fetch else self.sql(expression, "offset"),
    1849        ]

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

    1851    def after_having_modifiers(self, expression: exp.Expression) -> t.List[str]:
    1852        return [
    1853            self.sql(expression, "qualify"),
    1854            self.seg("WINDOW ") + self.expressions(expression, key="windows", flat=True)
    1855            if expression.args.get("windows")
    1856            else "",
    1857            self.sql(expression, "distribute"),
    1858            self.sql(expression, "sort"),
    1859            self.sql(expression, "cluster"),
    1860        ]

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

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

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

    1867    def select_sql(self, expression: exp.Select) -> str:
    1868        hint = self.sql(expression, "hint")
    1869        distinct = self.sql(expression, "distinct")
    1870        distinct = f" {distinct}" if distinct else ""
    1871        kind = self.sql(expression, "kind").upper()
    1872        limit = expression.args.get("limit")
    1873        top = (
    1874            self.limit_sql(limit, top=True)
    1875            if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP
    1876            else ""
    1877        )
    1878
    1879        expressions = self.expressions(expression)
    1880
    1881        if kind:
    1882            if kind in self.SELECT_KINDS:
    1883                kind = f" AS {kind}"
    1884            else:
    1885                if kind == "STRUCT":
    1886                    expressions = self.expressions(
    1887                        sqls=[
    1888                            self.sql(
    1889                                exp.Struct(
    1890                                    expressions=[
    1891                                        exp.column(e.output_name).eq(
    1892                                            e.this if isinstance(e, exp.Alias) else e
    1893                                        )
    1894                                        for e in expression.expressions
    1895                                    ]
    1896                                )
    1897                            )
    1898                        ]
    1899                    )
    1900                kind = ""
    1901
    1902        expressions = f"{self.sep()}{expressions}" if expressions else expressions
    1903        sql = self.query_modifiers(
    1904            expression,
    1905            f"SELECT{top}{hint}{distinct}{kind}{expressions}",
    1906            self.sql(expression, "into", comment=False),
    1907            self.sql(expression, "from", comment=False),
    1908        )
    1909        return self.prepend_ctes(expression, sql)

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

    1911    def schema_sql(self, expression: exp.Schema) -> str:
    1912        this = self.sql(expression, "this")
    1913        sql = self.schema_columns_sql(expression)
    1914        return f"{this} {sql}" if this and sql else this or sql

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

    1916    def schema_columns_sql(self, expression: exp.Schema) -> str:
    1917        if expression.expressions:
    1918            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
    1919        return ""

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

    1921    def star_sql(self, expression: exp.Star) -> str:
    1922        except_ = self.expressions(expression, key="except", flat=True)
    1923        except_ = f"{self.seg(self.STAR_MAPPING['except'])} ({except_})" if except_ else ""
    1924        replace = self.expressions(expression, key="replace", flat=True)
    1925        replace = f"{self.seg(self.STAR_MAPPING['replace'])} ({replace})" if replace else ""
    1926        return f"*{except_}{replace}"

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

    1928    def parameter_sql(self, expression: exp.Parameter) -> str:
    1929        this = self.sql(expression, "this")
    1930        return f"{self.PARAMETER_TOKEN}{this}" if self.SUPPORTS_PARAMETERS else this

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

    1932    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    1933        this = self.sql(expression, "this")
    1934        kind = expression.text("kind")
    1935        if kind:
    1936            kind = f"{kind}."
    1937        return f"@@{kind}{this}"

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

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

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

    1942    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    1943        alias = self.sql(expression, "alias")
    1944        alias = f"{sep}{alias}" if alias else ""
    1945
    1946        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    1947        pivots = f" {pivots}" if pivots else ""
    1948
    1949        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    1950        return self.prepend_ctes(expression, sql)

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

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

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

    1956    def union_sql(self, expression: exp.Union) -> str:
    1957        return self.prepend_ctes(
    1958            expression,
    1959            self.set_operation(expression, self.union_op(expression)),
    1960        )

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

    1962    def union_op(self, expression: exp.Union) -> str:
    1963        kind = " DISTINCT" if self.EXPLICIT_UNION else ""
    1964        kind = kind if expression.args.get("distinct") else " ALL"
    1965        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1966        return f"UNION{kind}{by_name}"

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

    1968    def unnest_sql(self, expression: exp.Unnest) -> str:
    1969        args = self.expressions(expression, flat=True)
    1970
    1971        alias = expression.args.get("alias")
    1972        offset = expression.args.get("offset")
    1973
    1974        if self.UNNEST_WITH_ORDINALITY:
    1975            if alias and isinstance(offset, exp.Expression):
    1976                alias = alias.copy()
    1977                alias.append("columns", offset.copy())
    1978
    1979        if alias and self.UNNEST_COLUMN_ONLY:
    1980            columns = alias.columns
    1981            alias = self.sql(columns[0]) if columns else ""
    1982        else:
    1983            alias = self.sql(alias)
    1984
    1985        alias = f" AS {alias}" if alias else alias
    1986        if self.UNNEST_WITH_ORDINALITY:
    1987            suffix = f" WITH ORDINALITY{alias}" if offset else alias
    1988        else:
    1989            if isinstance(offset, exp.Expression):
    1990                suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}"
    1991            elif offset:
    1992                suffix = f"{alias} WITH OFFSET"
    1993            else:
    1994                suffix = alias
    1995
    1996        return f"UNNEST({args}){suffix}"

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

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

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

    2002    def window_sql(self, expression: exp.Window) -> str:
    2003        this = self.sql(expression, "this")
    2004        partition = self.partition_by_sql(expression)
    2005        order = expression.args.get("order")
    2006        order = self.order_sql(order, flat=True) if order else ""
    2007        spec = self.sql(expression, "spec")
    2008        alias = self.sql(expression, "alias")
    2009        over = self.sql(expression, "over") or "OVER"
    2010
    2011        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    2012
    2013        first = expression.args.get("first")
    2014        if first is None:
    2015            first = ""
    2016        else:
    2017            first = "FIRST" if first else "LAST"
    2018
    2019        if not partition and not order and not spec and alias:
    2020            return f"{this} {alias}"
    2021
    2022        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
    2023        return f"{this} ({args})"

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

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

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

    2029    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    2030        kind = self.sql(expression, "kind")
    2031        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    2032        end = (
    2033            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    2034            or "CURRENT ROW"
    2035        )
    2036        return f"{kind} BETWEEN {start} AND {end}"

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

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

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

    2043    def between_sql(self, expression: exp.Between) -> str:
    2044        this = self.sql(expression, "this")
    2045        low = self.sql(expression, "low")
    2046        high = self.sql(expression, "high")
    2047        return f"{this} BETWEEN {low} AND {high}"

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

    2049    def bracket_sql(self, expression: exp.Bracket) -> str:
    2050        expressions = apply_index_offset(expression.this, expression.expressions, self.INDEX_OFFSET)
    2051        expressions_sql = ", ".join(self.sql(e) for e in expressions)
    2052
    2053        return f"{self.sql(expression, 'this')}[{expressions_sql}]"

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

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

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

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

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

    2061    def any_sql(self, expression: exp.Any) -> str:
    2062        this = self.sql(expression, "this")
    2063        if isinstance(expression.this, exp.Subqueryable):
    2064            this = self.wrap(this)
    2065        return f"ANY {this}"

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

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

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

    2070    def case_sql(self, expression: exp.Case) -> str:
    2071        this = self.sql(expression, "this")
    2072        statements = [f"CASE {this}" if this else "CASE"]
    2073
    2074        for e in expression.args["ifs"]:
    2075            statements.append(f"WHEN {self.sql(e, 'this')}")
    2076            statements.append(f"THEN {self.sql(e, 'true')}")
    2077
    2078        default = self.sql(expression, "default")
    2079
    2080        if default:
    2081            statements.append(f"ELSE {default}")
    2082
    2083        statements.append("END")
    2084
    2085        if self.pretty and self.text_width(statements) > self.max_text_width:
    2086            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    2087
    2088        return " ".join(statements)

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

    2090    def constraint_sql(self, expression: exp.Constraint) -> str:
    2091        this = self.sql(expression, "this")
    2092        expressions = self.expressions(expression, flat=True)
    2093        return f"CONSTRAINT {this} {expressions}"

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

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

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

    2100    def extract_sql(self, expression: exp.Extract) -> str:
    2101        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
    2102        expression_sql = self.sql(expression, "expression")
    2103        return f"EXTRACT({this} FROM {expression_sql})"

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

    2105    def trim_sql(self, expression: exp.Trim) -> str:
    2106        trim_type = self.sql(expression, "position")
    2107
    2108        if trim_type == "LEADING":
    2109            return self.func("LTRIM", expression.this)
    2110        elif trim_type == "TRAILING":
    2111            return self.func("RTRIM", expression.this)
    2112        else:
    2113            return self.func("TRIM", expression.this, expression.expression)

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

    2115    def safeconcat_sql(self, expression: exp.SafeConcat) -> str:
    2116        expressions = expression.expressions
    2117        if self.STRICT_STRING_CONCAT:
    2118            expressions = (exp.cast(e, "text") for e in expressions)
    2119        return self.func("CONCAT", *expressions)

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

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

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

    2125    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    2126        expressions = self.expressions(expression, flat=True)
    2127        reference = self.sql(expression, "reference")
    2128        reference = f" {reference}" if reference else ""
    2129        delete = self.sql(expression, "delete")
    2130        delete = f" ON DELETE {delete}" if delete else ""
    2131        update = self.sql(expression, "update")
    2132        update = f" ON UPDATE {update}" if update else ""
    2133        return f"FOREIGN KEY ({expressions}){reference}{delete}{update}"

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

    2135    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    2136        expressions = self.expressions(expression, flat=True)
    2137        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2138        options = f" {options}" if options else ""
    2139        return f"PRIMARY KEY ({expressions}){options}"

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

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

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

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

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

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

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

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

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

    2156    def jsonobject_sql(self, expression: exp.JSONObject) -> str:
    2157        null_handling = expression.args.get("null_handling")
    2158        null_handling = f" {null_handling}" if null_handling else ""
    2159        unique_keys = expression.args.get("unique_keys")
    2160        if unique_keys is not None:
    2161            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    2162        else:
    2163            unique_keys = ""
    2164        return_type = self.sql(expression, "return_type")
    2165        return_type = f" RETURNING {return_type}" if return_type else ""
    2166        encoding = self.sql(expression, "encoding")
    2167        encoding = f" ENCODING {encoding}" if encoding else ""
    2168        return self.func(
    2169            "JSON_OBJECT",
    2170            *expression.expressions,
    2171            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
    2172        )

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

    2174    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
    2175        null_handling = expression.args.get("null_handling")
    2176        null_handling = f" {null_handling}" if null_handling else ""
    2177        return_type = self.sql(expression, "return_type")
    2178        return_type = f" RETURNING {return_type}" if return_type else ""
    2179        strict = " STRICT" if expression.args.get("strict") else ""
    2180        return self.func(
    2181            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
    2182        )

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

    2184    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
    2185        this = self.sql(expression, "this")
    2186        order = self.sql(expression, "order")
    2187        null_handling = expression.args.get("null_handling")
    2188        null_handling = f" {null_handling}" if null_handling else ""
    2189        return_type = self.sql(expression, "return_type")
    2190        return_type = f" RETURNING {return_type}" if return_type else ""
    2191        strict = " STRICT" if expression.args.get("strict") else ""
    2192        return self.func(
    2193            "JSON_ARRAYAGG",
    2194            this,
    2195            suffix=f"{order}{null_handling}{return_type}{strict})",
    2196        )

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

    2198    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
    2199        path = self.sql(expression, "path")
    2200        path = f" PATH {path}" if path else ""
    2201        nested_schema = self.sql(expression, "nested_schema")
    2202
    2203        if nested_schema:
    2204            return f"NESTED{path} {nested_schema}"
    2205
    2206        this = self.sql(expression, "this")
    2207        kind = self.sql(expression, "kind")
    2208        kind = f" {kind}" if kind else ""
    2209        return f"{this}{kind}{path}"

def jsonschema_sql(self, expression: sqlglot.expressions.JSONSchema) -> str: View Source

    2211    def jsonschema_sql(self, expression: exp.JSONSchema) -> str:
    2212        return self.func("COLUMNS", *expression.expressions)

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

    2214    def jsontable_sql(self, expression: exp.JSONTable) -> str:
    2215        this = self.sql(expression, "this")
    2216        path = self.sql(expression, "path")
    2217        path = f", {path}" if path else ""
    2218        error_handling = expression.args.get("error_handling")
    2219        error_handling = f" {error_handling}" if error_handling else ""
    2220        empty_handling = expression.args.get("empty_handling")
    2221        empty_handling = f" {empty_handling}" if empty_handling else ""
    2222        schema = self.sql(expression, "schema")
    2223        return self.func(
    2224            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
    2225        )

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

    2227    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    2228        this = self.sql(expression, "this")
    2229        kind = self.sql(expression, "kind")
    2230        path = self.sql(expression, "path")
    2231        path = f" {path}" if path else ""
    2232        as_json = " AS JSON" if expression.args.get("as_json") else ""
    2233        return f"{this} {kind}{path}{as_json}"

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

    2235    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    2236        this = self.sql(expression, "this")
    2237        path = self.sql(expression, "path")
    2238        path = f", {path}" if path else ""
    2239        expressions = self.expressions(expression)
    2240        with_ = (
    2241            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    2242            if expressions
    2243            else ""
    2244        )
    2245        return f"OPENJSON({this}{path}){with_}"

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

    2247    def in_sql(self, expression: exp.In) -> str:
    2248        query = expression.args.get("query")
    2249        unnest = expression.args.get("unnest")
    2250        field = expression.args.get("field")
    2251        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    2252
    2253        if query:
    2254            in_sql = self.wrap(query)
    2255        elif unnest:
    2256            in_sql = self.in_unnest_op(unnest)
    2257        elif field:
    2258            in_sql = self.sql(field)
    2259        else:
    2260            in_sql = f"({self.expressions(expression, flat=True)})"
    2261
    2262        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"

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

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

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

    2267    def interval_sql(self, expression: exp.Interval) -> str:
    2268        unit = self.sql(expression, "unit")
    2269        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    2270            unit = self.TIME_PART_SINGULARS.get(unit.lower(), unit)
    2271        unit = f" {unit}" if unit else ""
    2272
    2273        if self.SINGLE_STRING_INTERVAL:
    2274            this = expression.this.name if expression.this else ""
    2275            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    2276
    2277        this = self.sql(expression, "this")
    2278        if this:
    2279            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    2280            this = f" {this}" if unwrapped else f" ({this})"
    2281
    2282        return f"INTERVAL{this}{unit}"

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

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

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

    2287    def reference_sql(self, expression: exp.Reference) -> str:
    2288        this = self.sql(expression, "this")
    2289        expressions = self.expressions(expression, flat=True)
    2290        expressions = f"({expressions})" if expressions else ""
    2291        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2292        options = f" {options}" if options else ""
    2293        return f"REFERENCES {this}{expressions}{options}"

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

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

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

    2298    def paren_sql(self, expression: exp.Paren) -> str:
    2299        if isinstance(expression.unnest(), exp.Select):
    2300            sql = self.wrap(expression)
    2301        else:
    2302            sql = self.seg(self.indent(self.sql(expression, "this")), sep="")
    2303            sql = f"({sql}{self.seg(')', sep='')}"
    2304
    2305        return self.prepend_ctes(expression, sql)

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

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

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

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

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

    2316    def alias_sql(self, expression: exp.Alias) -> str:
    2317        alias = self.sql(expression, "alias")
    2318        alias = f" AS {alias}" if alias else ""
    2319        return f"{self.sql(expression, 'this')}{alias}"

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

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

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

    2324    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    2325        this = self.sql(expression, "this")
    2326        zone = self.sql(expression, "zone")
    2327        return f"{this} AT TIME ZONE {zone}"

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

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

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

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

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

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

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

    2338    def connector_sql(self, expression: exp.Connector, op: str) -> str:
    2339        if not self.pretty:
    2340            return self.binary(expression, op)
    2341
    2342        sqls = tuple(
    2343            self.maybe_comment(self.sql(e), e, e.parent.comments or []) if i != 1 else self.sql(e)
    2344            for i, e in enumerate(expression.flatten(unnest=False))
    2345        )
    2346
    2347        sep = "\n" if self.text_width(sqls) > self.max_text_width else " "
    2348        return f"{sep}{op} ".join(sqls)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    2377    def collate_sql(self, expression: exp.Collate) -> str:
    2378        if self.COLLATE_IS_FUNC:
    2379            return self.function_fallback_sql(expression)
    2380        return self.binary(expression, "COLLATE")

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

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

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

    2385    def comment_sql(self, expression: exp.Comment) -> str:
    2386        this = self.sql(expression, "this")
    2387        kind = expression.args["kind"]
    2388        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    2389        expression_sql = self.sql(expression, "expression")
    2390        return f"COMMENT{exists_sql}ON {kind} {this} IS {expression_sql}"

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

    2392    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    2393        this = self.sql(expression, "this")
    2394        delete = " DELETE" if expression.args.get("delete") else ""
    2395        recompress = self.sql(expression, "recompress")
    2396        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    2397        to_disk = self.sql(expression, "to_disk")
    2398        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    2399        to_volume = self.sql(expression, "to_volume")
    2400        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    2401        return f"{this}{delete}{recompress}{to_disk}{to_volume}"

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

    2403    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    2404        where = self.sql(expression, "where")
    2405        group = self.sql(expression, "group")
    2406        aggregates = self.expressions(expression, key="aggregates")
    2407        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    2408
    2409        if not (where or group or aggregates) and len(expression.expressions) == 1:
    2410            return f"TTL {self.expressions(expression, flat=True)}"
    2411
    2412        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"

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

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

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

    2417    def commit_sql(self, expression: exp.Commit) -> str:
    2418        chain = expression.args.get("chain")
    2419        if chain is not None:
    2420            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    2421
    2422        return f"COMMIT{chain or ''}"

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

    2424    def rollback_sql(self, expression: exp.Rollback) -> str:
    2425        savepoint = expression.args.get("savepoint")
    2426        savepoint = f" TO {savepoint}" if savepoint else ""
    2427        return f"ROLLBACK{savepoint}"

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

    2429    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    2430        this = self.sql(expression, "this")
    2431
    2432        dtype = self.sql(expression, "dtype")
    2433        if dtype:
    2434            collate = self.sql(expression, "collate")
    2435            collate = f" COLLATE {collate}" if collate else ""
    2436            using = self.sql(expression, "using")
    2437            using = f" USING {using}" if using else ""
    2438            return f"ALTER COLUMN {this} SET DATA TYPE {dtype}{collate}{using}"
    2439
    2440        default = self.sql(expression, "default")
    2441        if default:
    2442            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    2443
    2444        if not expression.args.get("drop"):
    2445            self.unsupported("Unsupported ALTER COLUMN syntax")
    2446
    2447        return f"ALTER COLUMN {this} DROP DEFAULT"

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

    2449    def renametable_sql(self, expression: exp.RenameTable) -> str:
    2450        if not self.RENAME_TABLE_WITH_DB:
    2451            # Remove db from tables
    2452            expression = expression.transform(
    2453                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    2454            )
    2455        this = self.sql(expression, "this")
    2456        return f"RENAME TO {this}"

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

    2458    def altertable_sql(self, expression: exp.AlterTable) -> str:
    2459        actions = expression.args["actions"]
    2460
    2461        if isinstance(actions[0], exp.ColumnDef):
    2462            if self.ALTER_TABLE_ADD_COLUMN_KEYWORD:
    2463                actions = self.expressions(
    2464                    expression,
    2465                    key="actions",
    2466                    prefix="ADD COLUMN ",
    2467                )
    2468            else:
    2469                actions = f"ADD {self.expressions(expression, key='actions')}"
    2470        elif isinstance(actions[0], exp.Schema):
    2471            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    2472        elif isinstance(actions[0], exp.Delete):
    2473            actions = self.expressions(expression, key="actions", flat=True)
    2474        else:
    2475            actions = self.expressions(expression, key="actions", flat=True)
    2476
    2477        exists = " IF EXISTS" if expression.args.get("exists") else ""
    2478        only = " ONLY" if expression.args.get("only") else ""
    2479        return f"ALTER TABLE{exists}{only} {self.sql(expression, 'this')} {actions}"

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

    2481    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    2482        expressions = self.expressions(expression)
    2483        exists = " IF EXISTS " if expression.args.get("exists") else " "
    2484        return f"DROP{exists}{expressions}"

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

    2486    def addconstraint_sql(self, expression: exp.AddConstraint) -> str:
    2487        this = self.sql(expression, "this")
    2488        expression_ = self.sql(expression, "expression")
    2489        add_constraint = f"ADD CONSTRAINT {this}" if this else "ADD"
    2490
    2491        enforced = expression.args.get("enforced")
    2492        if enforced is not None:
    2493            return f"{add_constraint} CHECK ({expression_}){' ENFORCED' if enforced else ''}"
    2494
    2495        return f"{add_constraint} {expression_}"

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

    2497    def distinct_sql(self, expression: exp.Distinct) -> str:
    2498        this = self.expressions(expression, flat=True)
    2499        this = f" {this}" if this else ""
    2500
    2501        on = self.sql(expression, "on")
    2502        on = f" ON {on}" if on else ""
    2503        return f"DISTINCT{this}{on}"

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

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

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

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

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

    2511    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    2512        return self.sql(
    2513            exp.Cast(
    2514                this=exp.Div(this=expression.this.copy(), expression=expression.expression.copy()),
    2515                to=exp.DataType(this=exp.DataType.Type.INT),
    2516            )
    2517        )

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

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

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

    2522    def safedpipe_sql(self, expression: exp.SafeDPipe) -> str:
    2523        if self.STRICT_STRING_CONCAT:
    2524            return self.func("CONCAT", *(exp.cast(e, "text") for e in expression.flatten()))
    2525        return self.dpipe_sql(expression)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    2560    def is_sql(self, expression: exp.Is) -> str:
    2561        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    2562            return self.sql(
    2563                expression.this if expression.expression.this else exp.not_(expression.this)
    2564            )
    2565        return self.binary(expression, "IS")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

def log_sql(self, expression: sqlglot.expressions.Log) -> str: View Source

    2609    def log_sql(self, expression: exp.Log) -> str:
    2610        args = list(expression.args.values())
    2611        if not self.LOG_BASE_FIRST:
    2612            args.reverse()
    2613        return self.func("LOG", *args)

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

    2615    def use_sql(self, expression: exp.Use) -> str:
    2616        kind = self.sql(expression, "kind")
    2617        kind = f" {kind}" if kind else ""
    2618        this = self.sql(expression, "this")
    2619        this = f" {this}" if this else ""
    2620        return f"USE{kind}{this}"

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

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

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

    2626    def function_fallback_sql(self, expression: exp.Func) -> str:
    2627        args = []
    2628
    2629        for key in expression.arg_types:
    2630            arg_value = expression.args.get(key)
    2631
    2632            if isinstance(arg_value, list):
    2633                for value in arg_value:
    2634                    args.append(value)
    2635            elif arg_value is not None:
    2636                args.append(arg_value)
    2637
    2638        if self.normalize_functions:
    2639            name = expression.sql_name()
    2640        else:
    2641            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
    2642
    2643        return self.func(name, *args)

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

    2645    def func(
    2646        self,
    2647        name: str,
    2648        *args: t.Optional[exp.Expression | str],
    2649        prefix: str = "(",
    2650        suffix: str = ")",
    2651    ) -> str:
    2652        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

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

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

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

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

    2663    def format_time(self, expression: exp.Expression) -> t.Optional[str]:
    2664        return format_time(
    2665            self.sql(expression, "format"), self.INVERSE_TIME_MAPPING, self.INVERSE_TIME_TRIE
    2666        )

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

    2668    def expressions(
    2669        self,
    2670        expression: t.Optional[exp.Expression] = None,
    2671        key: t.Optional[str] = None,
    2672        sqls: t.Optional[t.Collection[str | exp.Expression]] = None,
    2673        flat: bool = False,
    2674        indent: bool = True,
    2675        skip_first: bool = False,
    2676        sep: str = ", ",
    2677        prefix: str = "",
    2678    ) -> str:
    2679        expressions = expression.args.get(key or "expressions") if expression else sqls
    2680
    2681        if not expressions:
    2682            return ""
    2683
    2684        if flat:
    2685            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
    2686
    2687        num_sqls = len(expressions)
    2688
    2689        # These are calculated once in case we have the leading_comma / pretty option set, correspondingly
    2690        pad = " " * self.pad
    2691        stripped_sep = sep.strip()
    2692
    2693        result_sqls = []
    2694        for i, e in enumerate(expressions):
    2695            sql = self.sql(e, comment=False)
    2696            if not sql:
    2697                continue
    2698
    2699            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    2700
    2701            if self.pretty:
    2702                if self.leading_comma:
    2703                    result_sqls.append(f"{sep if i > 0 else pad}{prefix}{sql}{comments}")
    2704                else:
    2705                    result_sqls.append(
    2706                        f"{prefix}{sql}{stripped_sep if i + 1 < num_sqls else ''}{comments}"
    2707                    )
    2708            else:
    2709                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    2710
    2711        result_sql = "\n".join(result_sqls) if self.pretty else "".join(result_sqls)
    2712        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

    2714    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    2715        flat = flat or isinstance(expression.parent, exp.Properties)
    2716        expressions_sql = self.expressions(expression, flat=flat)
    2717        if flat:
    2718            return f"{op} {expressions_sql}"
    2719        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"

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

    2721    def naked_property(self, expression: exp.Property) -> str:
    2722        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    2723        if not property_name:
    2724            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    2725        return f"{property_name} {self.sql(expression, 'this')}"

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

    2727    def set_operation(self, expression: exp.Union, op: str) -> str:
    2728        this = self.maybe_comment(self.sql(expression, "this"), comments=expression.comments)
    2729        op = self.seg(op)
    2730        return self.query_modifiers(
    2731            expression, f"{this}{op}{self.sep()}{self.sql(expression, 'expression')}"
    2732        )

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

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

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

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

    2740    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    2741        this = self.sql(expression, "this")
    2742        expressions = self.no_identify(self.expressions, expression)
    2743        expressions = (
    2744            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    2745        )
    2746        return f"{this}{expressions}"

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

    2748    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    2749        this = self.sql(expression, "this")
    2750        expressions = self.expressions(expression, flat=True)
    2751        return f"{this}({expressions})"

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

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

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

    2756    def when_sql(self, expression: exp.When) -> str:
    2757        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    2758        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    2759        condition = self.sql(expression, "condition")
    2760        condition = f" AND {condition}" if condition else ""
    2761
    2762        then_expression = expression.args.get("then")
    2763        if isinstance(then_expression, exp.Insert):
    2764            then = f"INSERT {self.sql(then_expression, 'this')}"
    2765            if "expression" in then_expression.args:
    2766                then += f" VALUES {self.sql(then_expression, 'expression')}"
    2767        elif isinstance(then_expression, exp.Update):
    2768            if isinstance(then_expression.args.get("expressions"), exp.Star):
    2769                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    2770            else:
    2771                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    2772        else:
    2773            then = self.sql(then_expression)
    2774        return f"WHEN {matched}{source}{condition} THEN {then}"

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

    2776    def merge_sql(self, expression: exp.Merge) -> str:
    2777        table = expression.this
    2778        table_alias = ""
    2779
    2780        hints = table.args.get("hints")
    2781        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
    2782            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
    2783            table = table.copy()
    2784            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
    2785
    2786        this = self.sql(table)
    2787        using = f"USING {self.sql(expression, 'using')}"
    2788        on = f"ON {self.sql(expression, 'on')}"
    2789        expressions = self.expressions(expression, sep=" ")
    2790
    2791        return f"MERGE INTO {this}{table_alias} {using} {on} {expressions}"

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

    2793    def tochar_sql(self, expression: exp.ToChar) -> str:
    2794        if expression.args.get("format"):
    2795            self.unsupported("Format argument unsupported for TO_CHAR/TO_VARCHAR function")
    2796
    2797        return self.sql(exp.cast(expression.this, "text"))

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

    2799    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    2800        this = self.sql(expression, "this")
    2801        kind = self.sql(expression, "kind")
    2802        settings_sql = self.expressions(expression, key="settings", sep=" ")
    2803        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    2804        return f"{this}({kind}{args})"

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

    2806    def dictrange_sql(self, expression: exp.DictRange) -> str:
    2807        this = self.sql(expression, "this")
    2808        max = self.sql(expression, "max")
    2809        min = self.sql(expression, "min")
    2810        return f"{this}(MIN {min} MAX {max})"

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

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

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

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

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

    2818    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    2819        expressions = self.expressions(expression, key="expressions", flat=True)
    2820        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    2821        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    2822        buckets = self.sql(expression, "buckets")
    2823        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"

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

    2825    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    2826        this = self.sql(expression, "this")
    2827        having = self.sql(expression, "having")
    2828
    2829        if having:
    2830            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    2831
    2832        return self.func("ANY_VALUE", this)

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

    2834    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
    2835        transform = self.func("TRANSFORM", *expression.expressions)
    2836        row_format_before = self.sql(expression, "row_format_before")
    2837        row_format_before = f" {row_format_before}" if row_format_before else ""
    2838        record_writer = self.sql(expression, "record_writer")
    2839        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
    2840        using = f" USING {self.sql(expression, 'command_script')}"
    2841        schema = self.sql(expression, "schema")
    2842        schema = f" AS {schema}" if schema else ""
    2843        row_format_after = self.sql(expression, "row_format_after")
    2844        row_format_after = f" {row_format_after}" if row_format_after else ""
    2845        record_reader = self.sql(expression, "record_reader")
    2846        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
    2847        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

    2849    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
    2850        key_block_size = self.sql(expression, "key_block_size")
    2851        if key_block_size:
    2852            return f"KEY_BLOCK_SIZE = {key_block_size}"
    2853
    2854        using = self.sql(expression, "using")
    2855        if using:
    2856            return f"USING {using}"
    2857
    2858        parser = self.sql(expression, "parser")
    2859        if parser:
    2860            return f"WITH PARSER {parser}"
    2861
    2862        comment = self.sql(expression, "comment")
    2863        if comment:
    2864            return f"COMMENT {comment}"
    2865
    2866        visible = expression.args.get("visible")
    2867        if visible is not None:
    2868            return "VISIBLE" if visible else "INVISIBLE"
    2869
    2870        engine_attr = self.sql(expression, "engine_attr")
    2871        if engine_attr:
    2872            return f"ENGINE_ATTRIBUTE = {engine_attr}"
    2873
    2874        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
    2875        if secondary_engine_attr:
    2876            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
    2877
    2878        self.unsupported("Unsupported index constraint option.")
    2879        return ""

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

    2881    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
    2882        kind = self.sql(expression, "kind")
    2883        kind = f"{kind} INDEX" if kind else "INDEX"
    2884        this = self.sql(expression, "this")
    2885        this = f" {this}" if this else ""
    2886        index_type = self.sql(expression, "index_type")
    2887        index_type = f" USING {index_type}" if index_type else ""
    2888        schema = self.sql(expression, "schema")
    2889        schema = f" {schema}" if schema else ""
    2890        options = self.expressions(expression, key="options", sep=" ")
    2891        options = f" {options}" if options else ""
    2892        return f"{kind}{this}{index_type}{schema}{options}"

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

    2894    def nvl2_sql(self, expression: exp.Nvl2) -> str:
    2895        if self.NVL2_SUPPORTED:
    2896            return self.function_fallback_sql(expression)
    2897
    2898        case = exp.Case().when(
    2899            expression.this.is_(exp.null()).not_(copy=False),
    2900            expression.args["true"].copy(),
    2901            copy=False,
    2902        )
    2903        else_cond = expression.args.get("false")
    2904        if else_cond:
    2905            case.else_(else_cond.copy(), copy=False)
    2906
    2907        return self.sql(case)

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

    2909    def comprehension_sql(self, expression: exp.Comprehension) -> str:
    2910        this = self.sql(expression, "this")
    2911        expr = self.sql(expression, "expression")
    2912        iterator = self.sql(expression, "iterator")
    2913        condition = self.sql(expression, "condition")
    2914        condition = f" IF {condition}" if condition else ""
    2915        return f"{this} FOR {expr} IN {iterator}{condition}"

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

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

def opclass_sql(self, expression: sqlglot.expressions.Opclass) -> str: View Source

    2920    def opclass_sql(self, expression: exp.Opclass) -> str:
    2921        return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}"

def predict_sql(self, expression: sqlglot.expressions.Predict) -> str: View Source

    2923    def predict_sql(self, expression: exp.Predict) -> str:
    2924        model = self.sql(expression, "this")
    2925        model = f"MODEL {model}"
    2926        table = self.sql(expression, "expression")
    2927        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
    2928        parameters = self.sql(expression, "params_struct")
    2929        return self.func("PREDICT", model, table, parameters or None)

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

    2940def cached_generator(
    2941    cache: t.Optional[t.Dict[int, str]] = None
    2942) -> t.Callable[[exp.Expression], str]:
    2943    """Returns a cached generator."""
    2944    cache = {} if cache is None else cache
    2945    generator = Generator(normalize=True, identify="safe")
    2946    return lambda e: generator.generate(e, cache)

Returns a cached generator.