sqlglot.generator API documentation

Edit on GitHub

# sqlglot.generator

View Source

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

logger = <Logger sqlglot (WARNING)>
ESCAPED_UNICODE_RE = re.compile('\\\\(\\d+)')
class Generator: View Source

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

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, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None) View Source

    432    def __init__(
    433        self,
    434        pretty: t.Optional[bool] = None,
    435        identify: str | bool = False,
    436        normalize: bool = False,
    437        pad: int = 2,
    438        indent: int = 2,
    439        normalize_functions: t.Optional[str | bool] = None,
    440        unsupported_level: ErrorLevel = ErrorLevel.WARN,
    441        max_unsupported: int = 3,
    442        leading_comma: bool = False,
    443        max_text_width: int = 80,
    444        comments: bool = True,
    445        dialect: DialectType = None,
    446    ):
    447        import sqlglot
    448        from sqlglot.dialects import Dialect
    449
    450        self.pretty = pretty if pretty is not None else sqlglot.pretty
    451        self.identify = identify
    452        self.normalize = normalize
    453        self.pad = pad
    454        self._indent = indent
    455        self.unsupported_level = unsupported_level
    456        self.max_unsupported = max_unsupported
    457        self.leading_comma = leading_comma
    458        self.max_text_width = max_text_width
    459        self.comments = comments
    460        self.dialect = Dialect.get_or_raise(dialect)
    461
    462        # This is both a Dialect property and a Generator argument, so we prioritize the latter
    463        self.normalize_functions = (
    464            self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions
    465        )
    466
    467        self.unsupported_messages: t.List[str] = []
    468        self._escaped_quote_end: str = (
    469            self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END
    470        )
    471        self._escaped_identifier_end: str = (
    472            self.dialect.tokenizer_class.IDENTIFIER_ESCAPES[0] + self.dialect.IDENTIFIER_END
    473        )

TRANSFORMS = {<class 'sqlglot.expressions.DateAdd'>: <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.AutoRefreshProperty'>: <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.InheritsProperty'>: <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.SetConfigProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlReadWriteProperty'>: <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>>}
NULL_ORDERING_SUPPORTED: Optional[bool] = 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
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_INCLUDE_COLUMN_KEYWORD = True
UNNEST_WITH_ORDINALITY = True
AGGREGATE_FILTER_SUPPORTED = True
SEMI_ANTI_JOIN_WITH_SIDE = True
COMPUTED_COLUMN_WITH_TYPE = True
SUPPORTS_TABLE_COPY = True
TABLESAMPLE_REQUIRES_PARENS = True
TABLESAMPLE_SIZE_IS_ROWS = True
TABLESAMPLE_KEYWORDS = 'TABLESAMPLE'
TABLESAMPLE_WITH_METHOD = True
TABLESAMPLE_SEED_KEYWORD = 'SEED'
COLLATE_IS_FUNC = False
DATA_TYPE_SPECIFIERS_ALLOWED = False
ENSURE_BOOLS = False
CTE_RECURSIVE_KEYWORD_REQUIRED = True
SUPPORTS_SINGLE_ARG_CONCAT = True
LAST_DAY_SUPPORTS_DATE_PART = True
SUPPORTS_TABLE_ALIAS_COLUMNS = True
UNPIVOT_ALIASES_ARE_IDENTIFIERS = True
JSON_KEY_VALUE_PAIR_SEP = ':'
INSERT_OVERWRITE = ' OVERWRITE TABLE'
SUPPORTS_SELECT_INTO = False
SUPPORTS_UNLOGGED_TABLES = 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.AutoRefreshProperty'>: <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.InheritsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <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.PartitionedOfProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <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.SetConfigProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SortKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlReadWriteProperty'>: <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'>, <class 'sqlglot.expressions.WithSystemVersioningProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>}
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'>)
EXPRESSIONS_WITHOUT_NESTED_CTES: Set[Type[sqlglot.expressions.Expression]] = set()
KEY_VALUE_DEFINITIONS = (<class 'sqlglot.expressions.Bracket'>, <class 'sqlglot.expressions.EQ'>, <class 'sqlglot.expressions.PropertyEQ'>, <class 'sqlglot.expressions.Slice'>)
SENTINEL_LINE_BREAK = '__SQLGLOT__LB__'
pretty
identify
normalize
pad
unsupported_level
max_unsupported
leading_comma
max_text_width
comments
dialect
normalize_functions
unsupported_messages: List[str]
def generate( self, expression: sqlglot.expressions.Expression, copy: bool = True) -> str: View Source

    475    def generate(self, expression: exp.Expression, copy: bool = True) -> str:
    476        """
    477        Generates the SQL string corresponding to the given syntax tree.
    478
    479        Args:
    480            expression: The syntax tree.
    481            copy: Whether or not to copy the expression. The generator performs mutations so
    482                it is safer to copy.
    483
    484        Returns:
    485            The SQL string corresponding to `expression`.
    486        """
    487        if copy:
    488            expression = expression.copy()
    489
    490        expression = self.preprocess(expression)
    491
    492        self.unsupported_messages = []
    493        sql = self.sql(expression).strip()
    494
    495        if self.pretty:
    496            sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n")
    497
    498        if self.unsupported_level == ErrorLevel.IGNORE:
    499            return sql
    500
    501        if self.unsupported_level == ErrorLevel.WARN:
    502            for msg in self.unsupported_messages:
    503                logger.warning(msg)
    504        elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages:
    505            raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported))
    506
    507        return sql

Generates the SQL string corresponding to the given syntax tree.

###### Arguments:

- expression: The syntax tree.
- copy: Whether or not to copy the expression. The generator performs mutations so it is safer to copy.

###### Returns:

> The SQL string corresponding to `expression`.

def preprocess( self, expression: sqlglot.expressions.Expression) -> sqlglot.expressions.Expression: View Source

    509    def preprocess(self, expression: exp.Expression) -> exp.Expression:
    510        """Apply generic preprocessing transformations to a given expression."""
    511        if (
    512            not expression.parent
    513            and type(expression) in self.EXPRESSIONS_WITHOUT_NESTED_CTES
    514            and any(node.parent is not expression for node in expression.find_all(exp.With))
    515        ):
    516            from sqlglot.transforms import move_ctes_to_top_level
    517
    518            expression = move_ctes_to_top_level(expression)
    519
    520        if self.ENSURE_BOOLS:
    521            from sqlglot.transforms import ensure_bools
    522
    523            expression = ensure_bools(expression)
    524
    525        return expression

Apply generic preprocessing transformations to a given expression.

def unsupported(self, message: str) -> None: View Source

    527    def unsupported(self, message: str) -> None:
    528        if self.unsupported_level == ErrorLevel.IMMEDIATE:
    529            raise UnsupportedError(message)
    530        self.unsupported_messages.append(message)

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

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

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

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

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

    538    def pad_comment(self, comment: str) -> str:
    539        comment = " " + comment if comment[0].strip() else comment
    540        comment = comment + " " if comment[-1].strip() else comment
    541        return comment

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

    543    def maybe_comment(
    544        self,
    545        sql: str,
    546        expression: t.Optional[exp.Expression] = None,
    547        comments: t.Optional[t.List[str]] = None,
    548    ) -> str:
    549        comments = (
    550            ((expression and expression.comments) if comments is None else comments)  # type: ignore
    551            if self.comments
    552            else None
    553        )
    554
    555        if not comments or isinstance(expression, self.EXCLUDE_COMMENTS):
    556            return sql
    557
    558        comments_sql = " ".join(
    559            f"/*{self.pad_comment(comment)}*/" for comment in comments if comment
    560        )
    561
    562        if not comments_sql:
    563            return sql
    564
    565        if isinstance(expression, self.WITH_SEPARATED_COMMENTS):
    566            return (
    567                f"{self.sep()}{comments_sql}{sql}"
    568                if sql[0].isspace()
    569                else f"{comments_sql}{self.sep()}{sql}"
    570            )
    571
    572        return f"{sql} {comments_sql}"

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

    574    def wrap(self, expression: exp.Expression | str) -> str:
    575        this_sql = self.indent(
    576            self.sql(expression)
    577            if isinstance(expression, (exp.Select, exp.Union))
    578            else self.sql(expression, "this"),
    579            level=1,
    580            pad=0,
    581        )
    582        return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"

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

    584    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
    585        original = self.identify
    586        self.identify = False
    587        result = func(*args, **kwargs)
    588        self.identify = original
    589        return result

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

    591    def normalize_func(self, name: str) -> str:
    592        if self.normalize_functions == "upper" or self.normalize_functions is True:
    593            return name.upper()
    594        if self.normalize_functions == "lower":
    595            return name.lower()
    596        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

    598    def indent(
    599        self,
    600        sql: str,
    601        level: int = 0,
    602        pad: t.Optional[int] = None,
    603        skip_first: bool = False,
    604        skip_last: bool = False,
    605    ) -> str:
    606        if not self.pretty:
    607            return sql
    608
    609        pad = self.pad if pad is None else pad
    610        lines = sql.split("\n")
    611
    612        return "\n".join(
    613            line
    614            if (skip_first and i == 0) or (skip_last and i == len(lines) - 1)
    615            else f"{' ' * (level * self._indent + pad)}{line}"
    616            for i, line in enumerate(lines)
    617        )

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

    619    def sql(
    620        self,
    621        expression: t.Optional[str | exp.Expression],
    622        key: t.Optional[str] = None,
    623        comment: bool = True,
    624    ) -> str:
    625        if not expression:
    626            return ""
    627
    628        if isinstance(expression, str):
    629            return expression
    630
    631        if key:
    632            value = expression.args.get(key)
    633            if value:
    634                return self.sql(value)
    635            return ""
    636
    637        transform = self.TRANSFORMS.get(expression.__class__)
    638
    639        if callable(transform):
    640            sql = transform(self, expression)
    641        elif transform:
    642            sql = transform
    643        elif isinstance(expression, exp.Expression):
    644            exp_handler_name = f"{expression.key}_sql"
    645
    646            if hasattr(self, exp_handler_name):
    647                sql = getattr(self, exp_handler_name)(expression)
    648            elif isinstance(expression, exp.Func):
    649                sql = self.function_fallback_sql(expression)
    650            elif isinstance(expression, exp.Property):
    651                sql = self.property_sql(expression)
    652            else:
    653                raise ValueError(f"Unsupported expression type {expression.__class__.__name__}")
    654        else:
    655            raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}")
    656
    657        return self.maybe_comment(sql, expression) if self.comments and comment else sql

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

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

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

    664    def cache_sql(self, expression: exp.Cache) -> str:
    665        lazy = " LAZY" if expression.args.get("lazy") else ""
    666        table = self.sql(expression, "this")
    667        options = expression.args.get("options")
    668        options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else ""
    669        sql = self.sql(expression, "expression")
    670        sql = f" AS{self.sep()}{sql}" if sql else ""
    671        sql = f"CACHE{lazy} TABLE {table}{options}{sql}"
    672        return self.prepend_ctes(expression, sql)

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

    674    def characterset_sql(self, expression: exp.CharacterSet) -> str:
    675        if isinstance(expression.parent, exp.Cast):
    676            return f"CHAR CHARACTER SET {self.sql(expression, 'this')}"
    677        default = "DEFAULT " if expression.args.get("default") else ""
    678        return f"{default}CHARACTER SET={self.sql(expression, 'this')}"

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

    680    def column_sql(self, expression: exp.Column) -> str:
    681        join_mark = " (+)" if expression.args.get("join_mark") else ""
    682
    683        if join_mark and not self.COLUMN_JOIN_MARKS_SUPPORTED:
    684            join_mark = ""
    685            self.unsupported("Outer join syntax using the (+) operator is not supported.")
    686
    687        column = ".".join(
    688            self.sql(part)
    689            for part in (
    690                expression.args.get("catalog"),
    691                expression.args.get("db"),
    692                expression.args.get("table"),
    693                expression.args.get("this"),
    694            )
    695            if part
    696        )
    697
    698        return f"{column}{join_mark}"

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

    700    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
    701        this = self.sql(expression, "this")
    702        this = f" {this}" if this else ""
    703        position = self.sql(expression, "position")
    704        return f"{position}{this}"

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

    706    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
    707        column = self.sql(expression, "this")
    708        kind = self.sql(expression, "kind")
    709        constraints = self.expressions(expression, key="constraints", sep=" ", flat=True)
    710        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
    711        kind = f"{sep}{kind}" if kind else ""
    712        constraints = f" {constraints}" if constraints else ""
    713        position = self.sql(expression, "position")
    714        position = f" {position}" if position else ""
    715
    716        if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE:
    717            kind = ""
    718
    719        return f"{exists}{column}{kind}{constraints}{position}"

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

    721    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
    722        this = self.sql(expression, "this")
    723        kind_sql = self.sql(expression, "kind").strip()
    724        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql

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

    726    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
    727        this = self.sql(expression, "this")
    728        if expression.args.get("not_null"):
    729            persisted = " PERSISTED NOT NULL"
    730        elif expression.args.get("persisted"):
    731            persisted = " PERSISTED"
    732        else:
    733            persisted = ""
    734        return f"AS {this}{persisted}"

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

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

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

    739    def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str:
    740        if isinstance(expression.this, list):
    741            this = self.wrap(self.expressions(expression, key="this", flat=True))
    742        else:
    743            this = self.sql(expression, "this")
    744
    745        return f"COMPRESS {this}"

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

    747    def generatedasidentitycolumnconstraint_sql(
    748        self, expression: exp.GeneratedAsIdentityColumnConstraint
    749    ) -> str:
    750        this = ""
    751        if expression.this is not None:
    752            on_null = " ON NULL" if expression.args.get("on_null") else ""
    753            this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}"
    754
    755        start = expression.args.get("start")
    756        start = f"START WITH {start}" if start else ""
    757        increment = expression.args.get("increment")
    758        increment = f" INCREMENT BY {increment}" if increment else ""
    759        minvalue = expression.args.get("minvalue")
    760        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    761        maxvalue = expression.args.get("maxvalue")
    762        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    763        cycle = expression.args.get("cycle")
    764        cycle_sql = ""
    765
    766        if cycle is not None:
    767            cycle_sql = f"{' NO' if not cycle else ''} CYCLE"
    768            cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql
    769
    770        sequence_opts = ""
    771        if start or increment or cycle_sql:
    772            sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}"
    773            sequence_opts = f" ({sequence_opts.strip()})"
    774
    775        expr = self.sql(expression, "expression")
    776        expr = f"({expr})" if expr else "IDENTITY"
    777
    778        return f"GENERATED{this} AS {expr}{sequence_opts}"

def generatedasrowcolumnconstraint_sql( self, expression: sqlglot.expressions.GeneratedAsRowColumnConstraint) -> str: View Source

    780    def generatedasrowcolumnconstraint_sql(
    781        self, expression: exp.GeneratedAsRowColumnConstraint
    782    ) -> str:
    783        start = "START" if expression.args.get("start") else "END"
    784        hidden = " HIDDEN" if expression.args.get("hidden") else ""
    785        return f"GENERATED ALWAYS AS ROW {start}{hidden}"

def periodforsystemtimeconstraint_sql( self, expression: sqlglot.expressions.PeriodForSystemTimeConstraint) -> str: View Source

    787    def periodforsystemtimeconstraint_sql(
    788        self, expression: exp.PeriodForSystemTimeConstraint
    789    ) -> str:
    790        return f"PERIOD FOR SYSTEM_TIME ({self.sql(expression, 'this')}, {self.sql(expression, 'expression')})"

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

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

def transformcolumnconstraint_sql(self, expression: sqlglot.expressions.TransformColumnConstraint) -> str: View Source

    795    def transformcolumnconstraint_sql(self, expression: exp.TransformColumnConstraint) -> str:
    796        return f"AS {self.sql(expression, 'this')}"

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

    798    def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str:
    799        desc = expression.args.get("desc")
    800        if desc is not None:
    801            return f"PRIMARY KEY{' DESC' if desc else ' ASC'}"
    802        return f"PRIMARY KEY"

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

    804    def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str:
    805        this = self.sql(expression, "this")
    806        this = f" {this}" if this else ""
    807        index_type = expression.args.get("index_type")
    808        index_type = f" USING {index_type}" if index_type else ""
    809        return f"UNIQUE{this}{index_type}"

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

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

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

    814    def create_sql(self, expression: exp.Create) -> str:
    815        kind = self.sql(expression, "kind")
    816        properties = expression.args.get("properties")
    817        properties_locs = self.locate_properties(properties) if properties else defaultdict()
    818
    819        this = self.createable_sql(expression, properties_locs)
    820
    821        properties_sql = ""
    822        if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get(
    823            exp.Properties.Location.POST_WITH
    824        ):
    825            properties_sql = self.sql(
    826                exp.Properties(
    827                    expressions=[
    828                        *properties_locs[exp.Properties.Location.POST_SCHEMA],
    829                        *properties_locs[exp.Properties.Location.POST_WITH],
    830                    ]
    831                )
    832            )
    833
    834        begin = " BEGIN" if expression.args.get("begin") else ""
    835        end = " END" if expression.args.get("end") else ""
    836
    837        expression_sql = self.sql(expression, "expression")
    838        if expression_sql:
    839            expression_sql = f"{begin}{self.sep()}{expression_sql}{end}"
    840
    841            if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return):
    842                if properties_locs.get(exp.Properties.Location.POST_ALIAS):
    843                    postalias_props_sql = self.properties(
    844                        exp.Properties(
    845                            expressions=properties_locs[exp.Properties.Location.POST_ALIAS]
    846                        ),
    847                        wrapped=False,
    848                    )
    849                    expression_sql = f" AS {postalias_props_sql}{expression_sql}"
    850                else:
    851                    expression_sql = f" AS{expression_sql}"
    852
    853        postindex_props_sql = ""
    854        if properties_locs.get(exp.Properties.Location.POST_INDEX):
    855            postindex_props_sql = self.properties(
    856                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]),
    857                wrapped=False,
    858                prefix=" ",
    859            )
    860
    861        indexes = self.expressions(expression, key="indexes", indent=False, sep=" ")
    862        indexes = f" {indexes}" if indexes else ""
    863        index_sql = indexes + postindex_props_sql
    864
    865        replace = " OR REPLACE" if expression.args.get("replace") else ""
    866        unique = " UNIQUE" if expression.args.get("unique") else ""
    867
    868        postcreate_props_sql = ""
    869        if properties_locs.get(exp.Properties.Location.POST_CREATE):
    870            postcreate_props_sql = self.properties(
    871                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]),
    872                sep=" ",
    873                prefix=" ",
    874                wrapped=False,
    875            )
    876
    877        modifiers = "".join((replace, unique, postcreate_props_sql))
    878
    879        postexpression_props_sql = ""
    880        if properties_locs.get(exp.Properties.Location.POST_EXPRESSION):
    881            postexpression_props_sql = self.properties(
    882                exp.Properties(
    883                    expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION]
    884                ),
    885                sep=" ",
    886                prefix=" ",
    887                wrapped=False,
    888            )
    889
    890        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
    891        no_schema_binding = (
    892            " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else ""
    893        )
    894
    895        clone = self.sql(expression, "clone")
    896        clone = f" {clone}" if clone else ""
    897
    898        expression_sql = f"CREATE{modifiers} {kind}{exists_sql} {this}{properties_sql}{expression_sql}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}"
    899        return self.prepend_ctes(expression, expression_sql)

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

    901    def clone_sql(self, expression: exp.Clone) -> str:
    902        this = self.sql(expression, "this")
    903        shallow = "SHALLOW " if expression.args.get("shallow") else ""
    904        keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE"
    905        return f"{shallow}{keyword} {this}"

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

    907    def describe_sql(self, expression: exp.Describe) -> str:
    908        extended = " EXTENDED" if expression.args.get("extended") else ""
    909        return f"DESCRIBE{extended} {self.sql(expression, 'this')}"

def heredoc_sql(self, expression: sqlglot.expressions.Heredoc) -> str: View Source

    911    def heredoc_sql(self, expression: exp.Heredoc) -> str:
    912        tag = self.sql(expression, "tag")
    913        return f"${tag}${self.sql(expression, 'this')}${tag}$"

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

    915    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
    916        with_ = self.sql(expression, "with")
    917        if with_:
    918            sql = f"{with_}{self.sep()}{sql}"
    919        return sql

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

    921    def with_sql(self, expression: exp.With) -> str:
    922        sql = self.expressions(expression, flat=True)
    923        recursive = (
    924            "RECURSIVE "
    925            if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive")
    926            else ""
    927        )
    928
    929        return f"WITH {recursive}{sql}"

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

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

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

    935    def tablealias_sql(self, expression: exp.TableAlias) -> str:
    936        alias = self.sql(expression, "this")
    937        columns = self.expressions(expression, key="columns", flat=True)
    938        columns = f"({columns})" if columns else ""
    939
    940        if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS:
    941            columns = ""
    942            self.unsupported("Named columns are not supported in table alias.")
    943
    944        if not alias and not self.dialect.UNNEST_COLUMN_ONLY:
    945            alias = "_t"
    946
    947        return f"{alias}{columns}"

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

    949    def bitstring_sql(self, expression: exp.BitString) -> str:
    950        this = self.sql(expression, "this")
    951        if self.dialect.BIT_START:
    952            return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}"
    953        return f"{int(this, 2)}"

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

    955    def hexstring_sql(self, expression: exp.HexString) -> str:
    956        this = self.sql(expression, "this")
    957        if self.dialect.HEX_START:
    958            return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"
    959        return f"{int(this, 16)}"

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

    961    def bytestring_sql(self, expression: exp.ByteString) -> str:
    962        this = self.sql(expression, "this")
    963        if self.dialect.BYTE_START:
    964            return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}"
    965        return this

def unicodestring_sql(self, expression: sqlglot.expressions.UnicodeString) -> str: View Source

    967    def unicodestring_sql(self, expression: exp.UnicodeString) -> str:
    968        this = self.sql(expression, "this")
    969        escape = expression.args.get("escape")
    970
    971        if self.dialect.UNICODE_START:
    972            escape = f" UESCAPE {self.sql(escape)}" if escape else ""
    973            return f"{self.dialect.UNICODE_START}{this}{self.dialect.UNICODE_END}{escape}"
    974
    975        if escape:
    976            pattern = re.compile(rf"{escape.name}(\d+)")
    977        else:
    978            pattern = ESCAPED_UNICODE_RE
    979
    980        this = pattern.sub(r"\\u\1", this)
    981        return f"{self.dialect.QUOTE_START}{this}{self.dialect.QUOTE_END}"

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

    983    def rawstring_sql(self, expression: exp.RawString) -> str:
    984        string = self.escape_str(expression.this.replace("\\", "\\\\"))
    985        return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}"

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

    987    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
    988        this = self.sql(expression, "this")
    989        specifier = self.sql(expression, "expression")
    990        specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else ""
    991        return f"{this}{specifier}"

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

     993    def datatype_sql(self, expression: exp.DataType) -> str:
     994        type_value = expression.this
     995
     996        if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"):
     997            type_sql = self.sql(expression, "kind")
     998        else:
     999            type_sql = (
    1000                self.TYPE_MAPPING.get(type_value, type_value.value)
    1001                if isinstance(type_value, exp.DataType.Type)
    1002                else type_value
    1003            )
    1004
    1005        nested = ""
    1006        interior = self.expressions(expression, flat=True)
    1007        values = ""
    1008
    1009        if interior:
    1010            if expression.args.get("nested"):
    1011                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
    1012                if expression.args.get("values") is not None:
    1013                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
    1014                    values = self.expressions(expression, key="values", flat=True)
    1015                    values = f"{delimiters[0]}{values}{delimiters[1]}"
    1016            elif type_value == exp.DataType.Type.INTERVAL:
    1017                nested = f" {interior}"
    1018            else:
    1019                nested = f"({interior})"
    1020
    1021        type_sql = f"{type_sql}{nested}{values}"
    1022        if self.TZ_TO_WITH_TIME_ZONE and type_value in (
    1023            exp.DataType.Type.TIMETZ,
    1024            exp.DataType.Type.TIMESTAMPTZ,
    1025        ):
    1026            type_sql = f"{type_sql} WITH TIME ZONE"
    1027
    1028        return type_sql

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

    1030    def directory_sql(self, expression: exp.Directory) -> str:
    1031        local = "LOCAL " if expression.args.get("local") else ""
    1032        row_format = self.sql(expression, "row_format")
    1033        row_format = f" {row_format}" if row_format else ""
    1034        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"

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

    1036    def delete_sql(self, expression: exp.Delete) -> str:
    1037        this = self.sql(expression, "this")
    1038        this = f" FROM {this}" if this else ""
    1039        using = self.sql(expression, "using")
    1040        using = f" USING {using}" if using else ""
    1041        where = self.sql(expression, "where")
    1042        returning = self.sql(expression, "returning")
    1043        limit = self.sql(expression, "limit")
    1044        tables = self.expressions(expression, key="tables")
    1045        tables = f" {tables}" if tables else ""
    1046        if self.RETURNING_END:
    1047            expression_sql = f"{this}{using}{where}{returning}{limit}"
    1048        else:
    1049            expression_sql = f"{returning}{this}{using}{where}{limit}"
    1050        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")

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

    1052    def drop_sql(self, expression: exp.Drop) -> str:
    1053        this = self.sql(expression, "this")
    1054        kind = expression.args["kind"]
    1055        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    1056        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    1057        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    1058        cascade = " CASCADE" if expression.args.get("cascade") else ""
    1059        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
    1060        purge = " PURGE" if expression.args.get("purge") else ""
    1061        return (
    1062            f"DROP{temporary}{materialized} {kind}{exists_sql}{this}{cascade}{constraints}{purge}"
    1063        )

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

    1065    def except_sql(self, expression: exp.Except) -> str:
    1066        return self.prepend_ctes(
    1067            expression,
    1068            self.set_operation(expression, self.except_op(expression)),
    1069        )

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

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

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

    1074    def fetch_sql(self, expression: exp.Fetch) -> str:
    1075        direction = expression.args.get("direction")
    1076        direction = f" {direction}" if direction else ""
    1077        count = expression.args.get("count")
    1078        count = f" {count}" if count else ""
    1079        if expression.args.get("percent"):
    1080            count = f"{count} PERCENT"
    1081        with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY"
    1082        return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}"

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

    1084    def filter_sql(self, expression: exp.Filter) -> str:
    1085        if self.AGGREGATE_FILTER_SUPPORTED:
    1086            this = self.sql(expression, "this")
    1087            where = self.sql(expression, "expression").strip()
    1088            return f"{this} FILTER({where})"
    1089
    1090        agg = expression.this
    1091        agg_arg = agg.this
    1092        cond = expression.expression.this
    1093        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
    1094        return self.sql(agg)

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

    1096    def hint_sql(self, expression: exp.Hint) -> str:
    1097        if not self.QUERY_HINTS:
    1098            self.unsupported("Hints are not supported")
    1099            return ""
    1100
    1101        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"

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

    1103    def index_sql(self, expression: exp.Index) -> str:
    1104        unique = "UNIQUE " if expression.args.get("unique") else ""
    1105        primary = "PRIMARY " if expression.args.get("primary") else ""
    1106        amp = "AMP " if expression.args.get("amp") else ""
    1107        name = self.sql(expression, "this")
    1108        name = f"{name} " if name else ""
    1109        table = self.sql(expression, "table")
    1110        table = f"{self.INDEX_ON} {table}" if table else ""
    1111        using = self.sql(expression, "using")
    1112        using = f" USING {using}" if using else ""
    1113        index = "INDEX " if not table else ""
    1114        columns = self.expressions(expression, key="columns", flat=True)
    1115        columns = f"({columns})" if columns else ""
    1116        partition_by = self.expressions(expression, key="partition_by", flat=True)
    1117        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
    1118        where = self.sql(expression, "where")
    1119        include = self.expressions(expression, key="include", flat=True)
    1120        if include:
    1121            include = f" INCLUDE ({include})"
    1122        return f"{unique}{primary}{amp}{index}{name}{table}{using}{columns}{include}{partition_by}{where}"

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

    1124    def identifier_sql(self, expression: exp.Identifier) -> str:
    1125        text = expression.name
    1126        lower = text.lower()
    1127        text = lower if self.normalize and not expression.quoted else text
    1128        text = text.replace(self.dialect.IDENTIFIER_END, self._escaped_identifier_end)
    1129        if (
    1130            expression.quoted
    1131            or self.dialect.can_identify(text, self.identify)
    1132            or lower in self.RESERVED_KEYWORDS
    1133            or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
    1134        ):
    1135            text = f"{self.dialect.IDENTIFIER_START}{text}{self.dialect.IDENTIFIER_END}"
    1136        return text

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

    1138    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    1139        input_format = self.sql(expression, "input_format")
    1140        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    1141        output_format = self.sql(expression, "output_format")
    1142        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    1143        return self.sep().join((input_format, output_format))

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

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

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

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

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

    1152    def properties_sql(self, expression: exp.Properties) -> str:
    1153        root_properties = []
    1154        with_properties = []
    1155
    1156        for p in expression.expressions:
    1157            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1158            if p_loc == exp.Properties.Location.POST_WITH:
    1159                with_properties.append(p)
    1160            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    1161                root_properties.append(p)
    1162
    1163        return self.root_properties(
    1164            exp.Properties(expressions=root_properties)
    1165        ) + self.with_properties(exp.Properties(expressions=with_properties))

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

    1167    def root_properties(self, properties: exp.Properties) -> str:
    1168        if properties.expressions:
    1169            return self.sep() + self.expressions(properties, indent=False, sep=" ")
    1170        return ""

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

    1172    def properties(
    1173        self,
    1174        properties: exp.Properties,
    1175        prefix: str = "",
    1176        sep: str = ", ",
    1177        suffix: str = "",
    1178        wrapped: bool = True,
    1179    ) -> str:
    1180        if properties.expressions:
    1181            expressions = self.expressions(properties, sep=sep, indent=False)
    1182            if expressions:
    1183                expressions = self.wrap(expressions) if wrapped else expressions
    1184                return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}"
    1185        return ""

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

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

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

    1190    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
    1191        properties_locs = defaultdict(list)
    1192        for p in properties.expressions:
    1193            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1194            if p_loc != exp.Properties.Location.UNSUPPORTED:
    1195                properties_locs[p_loc].append(p)
    1196            else:
    1197                self.unsupported(f"Unsupported property {p.key}")
    1198
    1199        return properties_locs

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

    1201    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
    1202        if isinstance(expression.this, exp.Dot):
    1203            return self.sql(expression, "this")
    1204        return f"'{expression.name}'" if string_key else expression.name

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

    1206    def property_sql(self, expression: exp.Property) -> str:
    1207        property_cls = expression.__class__
    1208        if property_cls == exp.Property:
    1209            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
    1210
    1211        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    1212        if not property_name:
    1213            self.unsupported(f"Unsupported property {expression.key}")
    1214
    1215        return f"{property_name}={self.sql(expression, 'this')}"

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

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

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

    1222    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1223        no = "NO " if expression.args.get("no") else ""
    1224        protection = " PROTECTION" if expression.args.get("protection") else ""
    1225        return f"{no}FALLBACK{protection}"

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

    1227    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1228        no = "NO " if expression.args.get("no") else ""
    1229        local = expression.args.get("local")
    1230        local = f"{local} " if local else ""
    1231        dual = "DUAL " if expression.args.get("dual") else ""
    1232        before = "BEFORE " if expression.args.get("before") else ""
    1233        after = "AFTER " if expression.args.get("after") else ""
    1234        return f"{no}{local}{dual}{before}{after}JOURNAL"

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

    1236    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1237        freespace = self.sql(expression, "this")
    1238        percent = " PERCENT" if expression.args.get("percent") else ""
    1239        return f"FREESPACE={freespace}{percent}"

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

    1241    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1242        if expression.args.get("default"):
    1243            property = "DEFAULT"
    1244        elif expression.args.get("on"):
    1245            property = "ON"
    1246        else:
    1247            property = "OFF"
    1248        return f"CHECKSUM={property}"

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

    1250    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1251        if expression.args.get("no"):
    1252            return "NO MERGEBLOCKRATIO"
    1253        if expression.args.get("default"):
    1254            return "DEFAULT MERGEBLOCKRATIO"
    1255
    1256        percent = " PERCENT" if expression.args.get("percent") else ""
    1257        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"

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

    1259    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1260        default = expression.args.get("default")
    1261        minimum = expression.args.get("minimum")
    1262        maximum = expression.args.get("maximum")
    1263        if default or minimum or maximum:
    1264            if default:
    1265                prop = "DEFAULT"
    1266            elif minimum:
    1267                prop = "MINIMUM"
    1268            else:
    1269                prop = "MAXIMUM"
    1270            return f"{prop} DATABLOCKSIZE"
    1271        units = expression.args.get("units")
    1272        units = f" {units}" if units else ""
    1273        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"

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

    1275    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1276        autotemp = expression.args.get("autotemp")
    1277        always = expression.args.get("always")
    1278        default = expression.args.get("default")
    1279        manual = expression.args.get("manual")
    1280        never = expression.args.get("never")
    1281
    1282        if autotemp is not None:
    1283            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1284        elif always:
    1285            prop = "ALWAYS"
    1286        elif default:
    1287            prop = "DEFAULT"
    1288        elif manual:
    1289            prop = "MANUAL"
    1290        elif never:
    1291            prop = "NEVER"
    1292        return f"BLOCKCOMPRESSION={prop}"

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

    1294    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1295        no = expression.args.get("no")
    1296        no = " NO" if no else ""
    1297        concurrent = expression.args.get("concurrent")
    1298        concurrent = " CONCURRENT" if concurrent else ""
    1299
    1300        for_ = ""
    1301        if expression.args.get("for_all"):
    1302            for_ = " FOR ALL"
    1303        elif expression.args.get("for_insert"):
    1304            for_ = " FOR INSERT"
    1305        elif expression.args.get("for_none"):
    1306            for_ = " FOR NONE"
    1307        return f"WITH{no}{concurrent} ISOLATED LOADING{for_}"

def partitionboundspec_sql(self, expression: sqlglot.expressions.PartitionBoundSpec) -> str: View Source

    1309    def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str:
    1310        if isinstance(expression.this, list):
    1311            return f"IN ({self.expressions(expression, key='this', flat=True)})"
    1312        if expression.this:
    1313            modulus = self.sql(expression, "this")
    1314            remainder = self.sql(expression, "expression")
    1315            return f"WITH (MODULUS {modulus}, REMAINDER {remainder})"
    1316
    1317        from_expressions = self.expressions(expression, key="from_expressions", flat=True)
    1318        to_expressions = self.expressions(expression, key="to_expressions", flat=True)
    1319        return f"FROM ({from_expressions}) TO ({to_expressions})"

def partitionedofproperty_sql(self, expression: sqlglot.expressions.PartitionedOfProperty) -> str: View Source

    1321    def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str:
    1322        this = self.sql(expression, "this")
    1323
    1324        for_values_or_default = expression.expression
    1325        if isinstance(for_values_or_default, exp.PartitionBoundSpec):
    1326            for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}"
    1327        else:
    1328            for_values_or_default = " DEFAULT"
    1329
    1330        return f"PARTITION OF {this}{for_values_or_default}"

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

    1332    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1333        kind = expression.args.get("kind")
    1334        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1335        for_or_in = expression.args.get("for_or_in")
    1336        for_or_in = f" {for_or_in}" if for_or_in else ""
    1337        lock_type = expression.args.get("lock_type")
    1338        override = " OVERRIDE" if expression.args.get("override") else ""
    1339        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"

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

    1341    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1342        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1343        statistics = expression.args.get("statistics")
    1344        statistics_sql = ""
    1345        if statistics is not None:
    1346            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1347        return f"{data_sql}{statistics_sql}"

def withsystemversioningproperty_sql( self, expression: sqlglot.expressions.WithSystemVersioningProperty) -> str: View Source

    1349    def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str:
    1350        sql = "WITH(SYSTEM_VERSIONING=ON"
    1351
    1352        if expression.this:
    1353            history_table = self.sql(expression, "this")
    1354            sql = f"{sql}(HISTORY_TABLE={history_table}"
    1355
    1356            if expression.expression:
    1357                data_consistency_check = self.sql(expression, "expression")
    1358                sql = f"{sql}, DATA_CONSISTENCY_CHECK={data_consistency_check}"
    1359
    1360            sql = f"{sql})"
    1361
    1362        return f"{sql})"

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

    1364    def insert_sql(self, expression: exp.Insert) -> str:
    1365        overwrite = expression.args.get("overwrite")
    1366
    1367        if isinstance(expression.this, exp.Directory):
    1368            this = " OVERWRITE" if overwrite else " INTO"
    1369        else:
    1370            this = self.INSERT_OVERWRITE if overwrite else " INTO"
    1371
    1372        alternative = expression.args.get("alternative")
    1373        alternative = f" OR {alternative}" if alternative else ""
    1374        ignore = " IGNORE" if expression.args.get("ignore") else ""
    1375
    1376        this = f"{this} {self.sql(expression, 'this')}"
    1377
    1378        exists = " IF EXISTS" if expression.args.get("exists") else ""
    1379        partition_sql = (
    1380            f" {self.sql(expression, 'partition')}" if expression.args.get("partition") else ""
    1381        )
    1382        where = self.sql(expression, "where")
    1383        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
    1384        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
    1385        conflict = self.sql(expression, "conflict")
    1386        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1387        returning = self.sql(expression, "returning")
    1388
    1389        if self.RETURNING_END:
    1390            expression_sql = f"{expression_sql}{conflict}{returning}"
    1391        else:
    1392            expression_sql = f"{returning}{expression_sql}{conflict}"
    1393
    1394        sql = f"INSERT{alternative}{ignore}{this}{by_name}{exists}{partition_sql}{where}{expression_sql}"
    1395        return self.prepend_ctes(expression, sql)

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

    1397    def intersect_sql(self, expression: exp.Intersect) -> str:
    1398        return self.prepend_ctes(
    1399            expression,
    1400            self.set_operation(expression, self.intersect_op(expression)),
    1401        )

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

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

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

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

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

    1409    def kill_sql(self, expression: exp.Kill) -> str:
    1410        kind = self.sql(expression, "kind")
    1411        kind = f" {kind}" if kind else ""
    1412        this = self.sql(expression, "this")
    1413        this = f" {this}" if this else ""
    1414        return f"KILL{kind}{this}"

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

    1416    def pseudotype_sql(self, expression: exp.PseudoType) -> str:
    1417        return expression.name

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

    1419    def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str:
    1420        return expression.name

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

    1422    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1423        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1424        constraint = self.sql(expression, "constraint")
    1425        if constraint:
    1426            constraint = f"ON CONSTRAINT {constraint}"
    1427        key = self.expressions(expression, key="key", flat=True)
    1428        do = "" if expression.args.get("duplicate") else " DO "
    1429        nothing = "NOTHING" if expression.args.get("nothing") else ""
    1430        expressions = self.expressions(expression, flat=True)
    1431        set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
    1432        if expressions:
    1433            expressions = f"UPDATE {set_keyword}{expressions}"
    1434        return f"{self.seg(conflict)} {constraint}{key}{do}{nothing}{expressions}"

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

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

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

    1439    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1440        fields = expression.args.get("fields")
    1441        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1442        escaped = expression.args.get("escaped")
    1443        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1444        items = expression.args.get("collection_items")
    1445        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1446        keys = expression.args.get("map_keys")
    1447        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1448        lines = expression.args.get("lines")
    1449        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1450        null = expression.args.get("null")
    1451        null = f" NULL DEFINED AS {null}" if null else ""
    1452        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"

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

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

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

    1457    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1458        this = f"{self.sql(expression, 'this')} INDEX"
    1459        target = self.sql(expression, "target")
    1460        target = f" FOR {target}" if target else ""
    1461        return f"{this}{target} ({self.expressions(expression, flat=True)})"

def historicaldata_sql(self, expression: sqlglot.expressions.HistoricalData) -> str: View Source

    1463    def historicaldata_sql(self, expression: exp.HistoricalData) -> str:
    1464        this = self.sql(expression, "this")
    1465        kind = self.sql(expression, "kind")
    1466        expr = self.sql(expression, "expression")
    1467        return f"{this} ({kind} => {expr})"

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

    1469    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1470        table = ".".join(
    1471            self.sql(part)
    1472            for part in (
    1473                expression.args.get("catalog"),
    1474                expression.args.get("db"),
    1475                expression.args.get("this"),
    1476            )
    1477            if part is not None
    1478        )
    1479
    1480        version = self.sql(expression, "version")
    1481        version = f" {version}" if version else ""
    1482        alias = self.sql(expression, "alias")
    1483        alias = f"{sep}{alias}" if alias else ""
    1484        hints = self.expressions(expression, key="hints", sep=" ")
    1485        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
    1486        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    1487        pivots = f" {pivots}" if pivots else ""
    1488        joins = self.expressions(expression, key="joins", sep="", skip_first=True)
    1489        laterals = self.expressions(expression, key="laterals", sep="")
    1490
    1491        file_format = self.sql(expression, "format")
    1492        if file_format:
    1493            pattern = self.sql(expression, "pattern")
    1494            pattern = f", PATTERN => {pattern}" if pattern else ""
    1495            file_format = f" (FILE_FORMAT => {file_format}{pattern})"
    1496
    1497        ordinality = expression.args.get("ordinality") or ""
    1498        if ordinality:
    1499            ordinality = f" WITH ORDINALITY{alias}"
    1500            alias = ""
    1501
    1502        when = self.sql(expression, "when")
    1503        if when:
    1504            table = f"{table} {when}"
    1505
    1506        return f"{table}{version}{file_format}{alias}{hints}{pivots}{joins}{laterals}{ordinality}"

def tablesample_sql( self, expression: sqlglot.expressions.TableSample, sep: str = ' AS ', tablesample_keyword: Optional[str] = None) -> str: View Source

    1508    def tablesample_sql(
    1509        self,
    1510        expression: exp.TableSample,
    1511        sep: str = " AS ",
    1512        tablesample_keyword: t.Optional[str] = None,
    1513    ) -> str:
    1514        if self.dialect.ALIAS_POST_TABLESAMPLE and expression.this and expression.this.alias:
    1515            table = expression.this.copy()
    1516            table.set("alias", None)
    1517            this = self.sql(table)
    1518            alias = f"{sep}{self.sql(expression.this, 'alias')}"
    1519        else:
    1520            this = self.sql(expression, "this")
    1521            alias = ""
    1522
    1523        method = self.sql(expression, "method")
    1524        method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    1525        numerator = self.sql(expression, "bucket_numerator")
    1526        denominator = self.sql(expression, "bucket_denominator")
    1527        field = self.sql(expression, "bucket_field")
    1528        field = f" ON {field}" if field else ""
    1529        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    1530        seed = self.sql(expression, "seed")
    1531        seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else ""
    1532
    1533        size = self.sql(expression, "size")
    1534        if size and self.TABLESAMPLE_SIZE_IS_ROWS:
    1535            size = f"{size} ROWS"
    1536
    1537        percent = self.sql(expression, "percent")
    1538        if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT:
    1539            percent = f"{percent} PERCENT"
    1540
    1541        expr = f"{bucket}{percent}{size}"
    1542        if self.TABLESAMPLE_REQUIRES_PARENS:
    1543            expr = f"({expr})"
    1544
    1545        return (
    1546            f"{this} {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}{alias}"
    1547        )

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

    1549    def pivot_sql(self, expression: exp.Pivot) -> str:
    1550        expressions = self.expressions(expression, flat=True)
    1551
    1552        if expression.this:
    1553            this = self.sql(expression, "this")
    1554            if not expressions:
    1555                return f"UNPIVOT {this}"
    1556
    1557            on = f"{self.seg('ON')} {expressions}"
    1558            using = self.expressions(expression, key="using", flat=True)
    1559            using = f"{self.seg('USING')} {using}" if using else ""
    1560            group = self.sql(expression, "group")
    1561            return f"PIVOT {this}{on}{using}{group}"
    1562
    1563        alias = self.sql(expression, "alias")
    1564        alias = f" AS {alias}" if alias else ""
    1565        direction = "UNPIVOT" if expression.unpivot else "PIVOT"
    1566        field = self.sql(expression, "field")
    1567        include_nulls = expression.args.get("include_nulls")
    1568        if include_nulls is not None:
    1569            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
    1570        else:
    1571            nulls = ""
    1572        return f"{direction}{nulls}({expressions} FOR {field}){alias}"

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

    1574    def version_sql(self, expression: exp.Version) -> str:
    1575        this = f"FOR {expression.name}"
    1576        kind = expression.text("kind")
    1577        expr = self.sql(expression, "expression")
    1578        return f"{this} {kind} {expr}"

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

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

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

    1583    def update_sql(self, expression: exp.Update) -> str:
    1584        this = self.sql(expression, "this")
    1585        set_sql = self.expressions(expression, flat=True)
    1586        from_sql = self.sql(expression, "from")
    1587        where_sql = self.sql(expression, "where")
    1588        returning = self.sql(expression, "returning")
    1589        order = self.sql(expression, "order")
    1590        limit = self.sql(expression, "limit")
    1591        if self.RETURNING_END:
    1592            expression_sql = f"{from_sql}{where_sql}{returning}"
    1593        else:
    1594            expression_sql = f"{returning}{from_sql}{where_sql}"
    1595        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
    1596        return self.prepend_ctes(expression, sql)

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

    1598    def values_sql(self, expression: exp.Values) -> str:
    1599        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
    1600        if self.VALUES_AS_TABLE or not expression.find_ancestor(exp.From, exp.Join):
    1601            args = self.expressions(expression)
    1602            alias = self.sql(expression, "alias")
    1603            values = f"VALUES{self.seg('')}{args}"
    1604            values = (
    1605                f"({values})"
    1606                if self.WRAP_DERIVED_VALUES and (alias or isinstance(expression.parent, exp.From))
    1607                else values
    1608            )
    1609            return f"{values} AS {alias}" if alias else values
    1610
    1611        # Converts `VALUES...` expression into a series of select unions.
    1612        alias_node = expression.args.get("alias")
    1613        column_names = alias_node and alias_node.columns
    1614
    1615        selects: t.List[exp.Subqueryable] = []
    1616
    1617        for i, tup in enumerate(expression.expressions):
    1618            row = tup.expressions
    1619
    1620            if i == 0 and column_names:
    1621                row = [
    1622                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
    1623                ]
    1624
    1625            selects.append(exp.Select(expressions=row))
    1626
    1627        if self.pretty:
    1628            # This may result in poor performance for large-cardinality `VALUES` tables, due to
    1629            # the deep nesting of the resulting exp.Unions. If this is a problem, either increase
    1630            # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`.
    1631            subqueryable = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects)
    1632            return self.subquery_sql(
    1633                subqueryable.subquery(alias_node and alias_node.this, copy=False)
    1634            )
    1635
    1636        alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else ""
    1637        unions = " UNION ALL ".join(self.sql(select) for select in selects)
    1638        return f"({unions}){alias}"

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

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

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

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

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

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

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

    1651    def group_sql(self, expression: exp.Group) -> str:
    1652        group_by = self.op_expressions("GROUP BY", expression)
    1653
    1654        if expression.args.get("all"):
    1655            return f"{group_by} ALL"
    1656
    1657        grouping_sets = self.expressions(expression, key="grouping_sets", indent=False)
    1658        grouping_sets = (
    1659            f"{self.seg('GROUPING SETS')} {self.wrap(grouping_sets)}" if grouping_sets else ""
    1660        )
    1661
    1662        cube = expression.args.get("cube", [])
    1663        if seq_get(cube, 0) is True:
    1664            return f"{group_by}{self.seg('WITH CUBE')}"
    1665        else:
    1666            cube_sql = self.expressions(expression, key="cube", indent=False)
    1667            cube_sql = f"{self.seg('CUBE')} {self.wrap(cube_sql)}" if cube_sql else ""
    1668
    1669        rollup = expression.args.get("rollup", [])
    1670        if seq_get(rollup, 0) is True:
    1671            return f"{group_by}{self.seg('WITH ROLLUP')}"
    1672        else:
    1673            rollup_sql = self.expressions(expression, key="rollup", indent=False)
    1674            rollup_sql = f"{self.seg('ROLLUP')} {self.wrap(rollup_sql)}" if rollup_sql else ""
    1675
    1676        groupings = csv(
    1677            grouping_sets,
    1678            cube_sql,
    1679            rollup_sql,
    1680            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    1681            sep=self.GROUPINGS_SEP,
    1682        )
    1683
    1684        if expression.args.get("expressions") and groupings:
    1685            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    1686
    1687        return f"{group_by}{groupings}"

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

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

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

    1693    def connect_sql(self, expression: exp.Connect) -> str:
    1694        start = self.sql(expression, "start")
    1695        start = self.seg(f"START WITH {start}") if start else ""
    1696        connect = self.sql(expression, "connect")
    1697        connect = self.seg(f"CONNECT BY {connect}")
    1698        return start + connect

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

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

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

    1703    def join_sql(self, expression: exp.Join) -> str:
    1704        if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"):
    1705            side = None
    1706        else:
    1707            side = expression.side
    1708
    1709        op_sql = " ".join(
    1710            op
    1711            for op in (
    1712                expression.method,
    1713                "GLOBAL" if expression.args.get("global") else None,
    1714                side,
    1715                expression.kind,
    1716                expression.hint if self.JOIN_HINTS else None,
    1717            )
    1718            if op
    1719        )
    1720        on_sql = self.sql(expression, "on")
    1721        using = expression.args.get("using")
    1722
    1723        if not on_sql and using:
    1724            on_sql = csv(*(self.sql(column) for column in using))
    1725
    1726        this = expression.this
    1727        this_sql = self.sql(this)
    1728
    1729        if on_sql:
    1730            on_sql = self.indent(on_sql, skip_first=True)
    1731            space = self.seg(" " * self.pad) if self.pretty else " "
    1732            if using:
    1733                on_sql = f"{space}USING ({on_sql})"
    1734            else:
    1735                on_sql = f"{space}ON {on_sql}"
    1736        elif not op_sql:
    1737            if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None:
    1738                return f" {this_sql}"
    1739
    1740            return f", {this_sql}"
    1741
    1742        op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    1743        return f"{self.seg(op_sql)} {this_sql}{on_sql}"

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

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

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

    1750    def lateral_op(self, expression: exp.Lateral) -> str:
    1751        cross_apply = expression.args.get("cross_apply")
    1752
    1753        # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/
    1754        if cross_apply is True:
    1755            op = "INNER JOIN "
    1756        elif cross_apply is False:
    1757            op = "LEFT JOIN "
    1758        else:
    1759            op = ""
    1760
    1761        return f"{op}LATERAL"

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

    1763    def lateral_sql(self, expression: exp.Lateral) -> str:
    1764        this = self.sql(expression, "this")
    1765
    1766        if expression.args.get("view"):
    1767            alias = expression.args["alias"]
    1768            columns = self.expressions(alias, key="columns", flat=True)
    1769            table = f" {alias.name}" if alias.name else ""
    1770            columns = f" AS {columns}" if columns else ""
    1771            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    1772            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    1773
    1774        alias = self.sql(expression, "alias")
    1775        alias = f" AS {alias}" if alias else ""
    1776        return f"{self.lateral_op(expression)} {this}{alias}"

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

    1778    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    1779        this = self.sql(expression, "this")
    1780
    1781        args = [
    1782            self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e
    1783            for e in (expression.args.get(k) for k in ("offset", "expression"))
    1784            if e
    1785        ]
    1786
    1787        args_sql = ", ".join(self.sql(e) for e in args)
    1788        args_sql = f"({args_sql})" if any(top and not e.is_number for e in args) else args_sql
    1789        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}"

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

    1791    def offset_sql(self, expression: exp.Offset) -> str:
    1792        this = self.sql(expression, "this")
    1793        expression = expression.expression
    1794        expression = (
    1795            self._simplify_unless_literal(expression) if self.LIMIT_ONLY_LITERALS else expression
    1796        )
    1797        return f"{this}{self.seg('OFFSET')} {self.sql(expression)}"

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

    1799    def setitem_sql(self, expression: exp.SetItem) -> str:
    1800        kind = self.sql(expression, "kind")
    1801        kind = f"{kind} " if kind else ""
    1802        this = self.sql(expression, "this")
    1803        expressions = self.expressions(expression)
    1804        collate = self.sql(expression, "collate")
    1805        collate = f" COLLATE {collate}" if collate else ""
    1806        global_ = "GLOBAL " if expression.args.get("global") else ""
    1807        return f"{global_}{kind}{this}{expressions}{collate}"

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

    1809    def set_sql(self, expression: exp.Set) -> str:
    1810        expressions = (
    1811            f" {self.expressions(expression, flat=True)}" if expression.expressions else ""
    1812        )
    1813        tag = " TAG" if expression.args.get("tag") else ""
    1814        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"

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

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

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

    1819    def lock_sql(self, expression: exp.Lock) -> str:
    1820        if not self.LOCKING_READS_SUPPORTED:
    1821            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    1822            return ""
    1823
    1824        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    1825        expressions = self.expressions(expression, flat=True)
    1826        expressions = f" OF {expressions}" if expressions else ""
    1827        wait = expression.args.get("wait")
    1828
    1829        if wait is not None:
    1830            if isinstance(wait, exp.Literal):
    1831                wait = f" WAIT {self.sql(wait)}"
    1832            else:
    1833                wait = " NOWAIT" if wait else " SKIP LOCKED"
    1834
    1835        return f"{lock_type}{expressions}{wait or ''}"

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

    1837    def literal_sql(self, expression: exp.Literal) -> str:
    1838        text = expression.this or ""
    1839        if expression.is_string:
    1840            text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}"
    1841        return text

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

    1843    def escape_str(self, text: str) -> str:
    1844        text = text.replace(self.dialect.QUOTE_END, self._escaped_quote_end)
    1845        if self.dialect.INVERSE_ESCAPE_SEQUENCES:
    1846            text = "".join(self.dialect.INVERSE_ESCAPE_SEQUENCES.get(ch, ch) for ch in text)
    1847        elif self.pretty:
    1848            text = text.replace("\n", self.SENTINEL_LINE_BREAK)
    1849        return text

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

    1851    def loaddata_sql(self, expression: exp.LoadData) -> str:
    1852        local = " LOCAL" if expression.args.get("local") else ""
    1853        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    1854        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    1855        this = f" INTO TABLE {self.sql(expression, 'this')}"
    1856        partition = self.sql(expression, "partition")
    1857        partition = f" {partition}" if partition else ""
    1858        input_format = self.sql(expression, "input_format")
    1859        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    1860        serde = self.sql(expression, "serde")
    1861        serde = f" SERDE {serde}" if serde else ""
    1862        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"

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

    1864    def null_sql(self, *_) -> str:
    1865        return "NULL"

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

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

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

    1870    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    1871        this = self.sql(expression, "this")
    1872        this = f"{this} " if this else this
    1873        siblings = "SIBLINGS " if expression.args.get("siblings") else ""
    1874        order = self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat)  # type: ignore
    1875        interpolated_values = [
    1876            f"{self.sql(named_expression, 'alias')} AS {self.sql(named_expression, 'this')}"
    1877            for named_expression in expression.args.get("interpolate") or []
    1878        ]
    1879        interpolate = (
    1880            f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else ""
    1881        )
    1882        return f"{order}{interpolate}"

def withfill_sql(self, expression: sqlglot.expressions.WithFill) -> str: View Source

    1884    def withfill_sql(self, expression: exp.WithFill) -> str:
    1885        from_sql = self.sql(expression, "from")
    1886        from_sql = f" FROM {from_sql}" if from_sql else ""
    1887        to_sql = self.sql(expression, "to")
    1888        to_sql = f" TO {to_sql}" if to_sql else ""
    1889        step_sql = self.sql(expression, "step")
    1890        step_sql = f" STEP {step_sql}" if step_sql else ""
    1891        return f"WITH FILL{from_sql}{to_sql}{step_sql}"

def cluster_sql(self, expression: sqlglot.expressions.Cluster) -> str: View Source

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

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

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

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

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

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

    1902    def ordered_sql(self, expression: exp.Ordered) -> str:
    1903        desc = expression.args.get("desc")
    1904        asc = not desc
    1905
    1906        nulls_first = expression.args.get("nulls_first")
    1907        nulls_last = not nulls_first
    1908        nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large"
    1909        nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small"
    1910        nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last"
    1911
    1912        this = self.sql(expression, "this")
    1913
    1914        sort_order = " DESC" if desc else (" ASC" if desc is False else "")
    1915        nulls_sort_change = ""
    1916        if nulls_first and (
    1917            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
    1918        ):
    1919            nulls_sort_change = " NULLS FIRST"
    1920        elif (
    1921            nulls_last
    1922            and ((asc and nulls_are_small) or (desc and nulls_are_large))
    1923            and not nulls_are_last
    1924        ):
    1925            nulls_sort_change = " NULLS LAST"
    1926
    1927        # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it
    1928        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
    1929            window = expression.find_ancestor(exp.Window, exp.Select)
    1930            if isinstance(window, exp.Window) and window.args.get("spec"):
    1931                self.unsupported(
    1932                    f"'{nulls_sort_change.strip()}' translation not supported in window functions"
    1933                )
    1934                nulls_sort_change = ""
    1935            elif self.NULL_ORDERING_SUPPORTED is None:
    1936                if expression.this.is_int:
    1937                    self.unsupported(
    1938                        f"'{nulls_sort_change.strip()}' translation not supported with positional ordering"
    1939                    )
    1940                else:
    1941                    null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else ""
    1942                    this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}"
    1943                nulls_sort_change = ""
    1944
    1945        with_fill = self.sql(expression, "with_fill")
    1946        with_fill = f" {with_fill}" if with_fill else ""
    1947
    1948        return f"{this}{sort_order}{nulls_sort_change}{with_fill}"

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

    1950    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    1951        partition = self.partition_by_sql(expression)
    1952        order = self.sql(expression, "order")
    1953        measures = self.expressions(expression, key="measures")
    1954        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    1955        rows = self.sql(expression, "rows")
    1956        rows = self.seg(rows) if rows else ""
    1957        after = self.sql(expression, "after")
    1958        after = self.seg(after) if after else ""
    1959        pattern = self.sql(expression, "pattern")
    1960        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    1961        definition_sqls = [
    1962            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    1963            for definition in expression.args.get("define", [])
    1964        ]
    1965        definitions = self.expressions(sqls=definition_sqls)
    1966        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    1967        body = "".join(
    1968            (
    1969                partition,
    1970                order,
    1971                measures,
    1972                rows,
    1973                after,
    1974                pattern,
    1975                define,
    1976            )
    1977        )
    1978        alias = self.sql(expression, "alias")
    1979        alias = f" {alias}" if alias else ""
    1980        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"

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

    1982    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    1983        limit: t.Optional[exp.Fetch | exp.Limit] = expression.args.get("limit")
    1984
    1985        # If the limit is generated as TOP, we need to ensure it's not generated twice
    1986        with_offset_limit_modifiers = not isinstance(limit, exp.Limit) or not self.LIMIT_IS_TOP
    1987
    1988        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    1989            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
    1990        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    1991            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
    1992
    1993        fetch = isinstance(limit, exp.Fetch)
    1994
    1995        offset_limit_modifiers = (
    1996            self.offset_limit_modifiers(expression, fetch, limit)
    1997            if with_offset_limit_modifiers
    1998            else []
    1999        )
    2000
    2001        return csv(
    2002            *sqls,
    2003            *[self.sql(join) for join in expression.args.get("joins") or []],
    2004            self.sql(expression, "connect"),
    2005            self.sql(expression, "match"),
    2006            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    2007            self.sql(expression, "where"),
    2008            self.sql(expression, "group"),
    2009            self.sql(expression, "having"),
    2010            *self.after_having_modifiers(expression),
    2011            self.sql(expression, "order"),
    2012            *offset_limit_modifiers,
    2013            *self.after_limit_modifiers(expression),
    2014            sep="",
    2015        )

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

    2017    def offset_limit_modifiers(
    2018        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    2019    ) -> t.List[str]:
    2020        return [
    2021            self.sql(expression, "offset") if fetch else self.sql(limit),
    2022            self.sql(limit) if fetch else self.sql(expression, "offset"),
    2023        ]

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

    2025    def after_having_modifiers(self, expression: exp.Expression) -> t.List[str]:
    2026        return [
    2027            self.sql(expression, "qualify"),
    2028            self.seg("WINDOW ") + self.expressions(expression, key="windows", flat=True)
    2029            if expression.args.get("windows")
    2030            else "",
    2031            self.sql(expression, "distribute"),
    2032            self.sql(expression, "sort"),
    2033            self.sql(expression, "cluster"),
    2034        ]

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

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

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

    2041    def select_sql(self, expression: exp.Select) -> str:
    2042        into = expression.args.get("into")
    2043        if not self.SUPPORTS_SELECT_INTO and into:
    2044            into.pop()
    2045
    2046        hint = self.sql(expression, "hint")
    2047        distinct = self.sql(expression, "distinct")
    2048        distinct = f" {distinct}" if distinct else ""
    2049        kind = self.sql(expression, "kind")
    2050        limit = expression.args.get("limit")
    2051        top = (
    2052            self.limit_sql(limit, top=True)
    2053            if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP
    2054            else ""
    2055        )
    2056
    2057        expressions = self.expressions(expression)
    2058
    2059        if kind:
    2060            if kind in self.SELECT_KINDS:
    2061                kind = f" AS {kind}"
    2062            else:
    2063                if kind == "STRUCT":
    2064                    expressions = self.expressions(
    2065                        sqls=[
    2066                            self.sql(
    2067                                exp.Struct(
    2068                                    expressions=[
    2069                                        exp.column(e.output_name).eq(
    2070                                            e.this if isinstance(e, exp.Alias) else e
    2071                                        )
    2072                                        for e in expression.expressions
    2073                                    ]
    2074                                )
    2075                            )
    2076                        ]
    2077                    )
    2078                kind = ""
    2079
    2080        # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata
    2081        # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first.
    2082        top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}"
    2083        expressions = f"{self.sep()}{expressions}" if expressions else expressions
    2084        sql = self.query_modifiers(
    2085            expression,
    2086            f"SELECT{top_distinct}{kind}{expressions}",
    2087            self.sql(expression, "into", comment=False),
    2088            self.sql(expression, "from", comment=False),
    2089        )
    2090
    2091        sql = self.prepend_ctes(expression, sql)
    2092
    2093        if not self.SUPPORTS_SELECT_INTO and into:
    2094            if into.args.get("temporary"):
    2095                table_kind = " TEMPORARY"
    2096            elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"):
    2097                table_kind = " UNLOGGED"
    2098            else:
    2099                table_kind = ""
    2100            sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}"
    2101
    2102        return sql

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

    2104    def schema_sql(self, expression: exp.Schema) -> str:
    2105        this = self.sql(expression, "this")
    2106        sql = self.schema_columns_sql(expression)
    2107        return f"{this} {sql}" if this and sql else this or sql

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

    2109    def schema_columns_sql(self, expression: exp.Schema) -> str:
    2110        if expression.expressions:
    2111            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
    2112        return ""

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

    2114    def star_sql(self, expression: exp.Star) -> str:
    2115        except_ = self.expressions(expression, key="except", flat=True)
    2116        except_ = f"{self.seg(self.STAR_MAPPING['except'])} ({except_})" if except_ else ""
    2117        replace = self.expressions(expression, key="replace", flat=True)
    2118        replace = f"{self.seg(self.STAR_MAPPING['replace'])} ({replace})" if replace else ""
    2119        return f"*{except_}{replace}"

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

    2121    def parameter_sql(self, expression: exp.Parameter) -> str:
    2122        this = self.sql(expression, "this")
    2123        return f"{self.PARAMETER_TOKEN}{this}"

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

    2125    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    2126        this = self.sql(expression, "this")
    2127        kind = expression.text("kind")
    2128        if kind:
    2129            kind = f"{kind}."
    2130        return f"@@{kind}{this}"

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

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

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

    2135    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    2136        alias = self.sql(expression, "alias")
    2137        alias = f"{sep}{alias}" if alias else ""
    2138
    2139        pivots = self.expressions(expression, key="pivots", sep=" ", flat=True)
    2140        pivots = f" {pivots}" if pivots else ""
    2141
    2142        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    2143        return self.prepend_ctes(expression, sql)

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

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

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

    2149    def union_sql(self, expression: exp.Union) -> str:
    2150        return self.prepend_ctes(
    2151            expression,
    2152            self.set_operation(expression, self.union_op(expression)),
    2153        )

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

    2155    def union_op(self, expression: exp.Union) -> str:
    2156        kind = " DISTINCT" if self.EXPLICIT_UNION else ""
    2157        kind = kind if expression.args.get("distinct") else " ALL"
    2158        by_name = " BY NAME" if expression.args.get("by_name") else ""
    2159        return f"UNION{kind}{by_name}"

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

    2161    def unnest_sql(self, expression: exp.Unnest) -> str:
    2162        args = self.expressions(expression, flat=True)
    2163
    2164        alias = expression.args.get("alias")
    2165        offset = expression.args.get("offset")
    2166
    2167        if self.UNNEST_WITH_ORDINALITY:
    2168            if alias and isinstance(offset, exp.Expression):
    2169                alias.append("columns", offset)
    2170
    2171        if alias and self.dialect.UNNEST_COLUMN_ONLY:
    2172            columns = alias.columns
    2173            alias = self.sql(columns[0]) if columns else ""
    2174        else:
    2175            alias = self.sql(alias)
    2176
    2177        alias = f" AS {alias}" if alias else alias
    2178        if self.UNNEST_WITH_ORDINALITY:
    2179            suffix = f" WITH ORDINALITY{alias}" if offset else alias
    2180        else:
    2181            if isinstance(offset, exp.Expression):
    2182                suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}"
    2183            elif offset:
    2184                suffix = f"{alias} WITH OFFSET"
    2185            else:
    2186                suffix = alias
    2187
    2188        return f"UNNEST({args}){suffix}"

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

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

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

    2194    def window_sql(self, expression: exp.Window) -> str:
    2195        this = self.sql(expression, "this")
    2196        partition = self.partition_by_sql(expression)
    2197        order = expression.args.get("order")
    2198        order = self.order_sql(order, flat=True) if order else ""
    2199        spec = self.sql(expression, "spec")
    2200        alias = self.sql(expression, "alias")
    2201        over = self.sql(expression, "over") or "OVER"
    2202
    2203        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    2204
    2205        first = expression.args.get("first")
    2206        if first is None:
    2207            first = ""
    2208        else:
    2209            first = "FIRST" if first else "LAST"
    2210
    2211        if not partition and not order and not spec and alias:
    2212            return f"{this} {alias}"
    2213
    2214        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
    2215        return f"{this} ({args})"

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

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

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

    2221    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    2222        kind = self.sql(expression, "kind")
    2223        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    2224        end = (
    2225            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    2226            or "CURRENT ROW"
    2227        )
    2228        return f"{kind} BETWEEN {start} AND {end}"

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

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

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

    2235    def between_sql(self, expression: exp.Between) -> str:
    2236        this = self.sql(expression, "this")
    2237        low = self.sql(expression, "low")
    2238        high = self.sql(expression, "high")
    2239        return f"{this} BETWEEN {low} AND {high}"

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

    2241    def bracket_sql(self, expression: exp.Bracket) -> str:
    2242        expressions = apply_index_offset(
    2243            expression.this,
    2244            expression.expressions,
    2245            self.dialect.INDEX_OFFSET - expression.args.get("offset", 0),
    2246        )
    2247        expressions_sql = ", ".join(self.sql(e) for e in expressions)
    2248        return f"{self.sql(expression, 'this')}[{expressions_sql}]"

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

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

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

    2253    def any_sql(self, expression: exp.Any) -> str:
    2254        this = self.sql(expression, "this")
    2255        if isinstance(expression.this, exp.Subqueryable):
    2256            this = self.wrap(this)
    2257        return f"ANY {this}"

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

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

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

    2262    def case_sql(self, expression: exp.Case) -> str:
    2263        this = self.sql(expression, "this")
    2264        statements = [f"CASE {this}" if this else "CASE"]
    2265
    2266        for e in expression.args["ifs"]:
    2267            statements.append(f"WHEN {self.sql(e, 'this')}")
    2268            statements.append(f"THEN {self.sql(e, 'true')}")
    2269
    2270        default = self.sql(expression, "default")
    2271
    2272        if default:
    2273            statements.append(f"ELSE {default}")
    2274
    2275        statements.append("END")
    2276
    2277        if self.pretty and self.text_width(statements) > self.max_text_width:
    2278            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    2279
    2280        return " ".join(statements)

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

    2282    def constraint_sql(self, expression: exp.Constraint) -> str:
    2283        this = self.sql(expression, "this")
    2284        expressions = self.expressions(expression, flat=True)
    2285        return f"CONSTRAINT {this} {expressions}"

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

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

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

    2292    def extract_sql(self, expression: exp.Extract) -> str:
    2293        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
    2294        expression_sql = self.sql(expression, "expression")
    2295        return f"EXTRACT({this} FROM {expression_sql})"

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

    2297    def trim_sql(self, expression: exp.Trim) -> str:
    2298        trim_type = self.sql(expression, "position")
    2299
    2300        if trim_type == "LEADING":
    2301            return self.func("LTRIM", expression.this)
    2302        elif trim_type == "TRAILING":
    2303            return self.func("RTRIM", expression.this)
    2304        else:
    2305            return self.func("TRIM", expression.this, expression.expression)

def convert_concat_args( self, expression: sqlglot.expressions.Concat | sqlglot.expressions.ConcatWs) -> List[sqlglot.expressions.Expression]: View Source

    2307    def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]:
    2308        args = expression.expressions
    2309        if isinstance(expression, exp.ConcatWs):
    2310            args = args[1:]  # Skip the delimiter
    2311
    2312        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    2313            args = [exp.cast(e, "text") for e in args]
    2314
    2315        if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"):
    2316            args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args]
    2317
    2318        return args

def concat_sql(self, expression: sqlglot.expressions.Concat) -> str: View Source

    2320    def concat_sql(self, expression: exp.Concat) -> str:
    2321        expressions = self.convert_concat_args(expression)
    2322
    2323        # Some dialects don't allow a single-argument CONCAT call
    2324        if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1:
    2325            return self.sql(expressions[0])
    2326
    2327        return self.func("CONCAT", *expressions)

def concatws_sql(self, expression: sqlglot.expressions.ConcatWs) -> str: View Source

    2329    def concatws_sql(self, expression: exp.ConcatWs) -> str:
    2330        return self.func(
    2331            "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression)
    2332        )

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

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

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

    2338    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    2339        expressions = self.expressions(expression, flat=True)
    2340        reference = self.sql(expression, "reference")
    2341        reference = f" {reference}" if reference else ""
    2342        delete = self.sql(expression, "delete")
    2343        delete = f" ON DELETE {delete}" if delete else ""
    2344        update = self.sql(expression, "update")
    2345        update = f" ON UPDATE {update}" if update else ""
    2346        return f"FOREIGN KEY ({expressions}){reference}{delete}{update}"

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

    2348    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    2349        expressions = self.expressions(expression, flat=True)
    2350        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2351        options = f" {options}" if options else ""
    2352        return f"PRIMARY KEY ({expressions}){options}"

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

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

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

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

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

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

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

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

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

    2368    def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str:
    2369        null_handling = expression.args.get("null_handling")
    2370        null_handling = f" {null_handling}" if null_handling else ""
    2371
    2372        unique_keys = expression.args.get("unique_keys")
    2373        if unique_keys is not None:
    2374            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    2375        else:
    2376            unique_keys = ""
    2377
    2378        return_type = self.sql(expression, "return_type")
    2379        return_type = f" RETURNING {return_type}" if return_type else ""
    2380        encoding = self.sql(expression, "encoding")
    2381        encoding = f" ENCODING {encoding}" if encoding else ""
    2382
    2383        return self.func(
    2384            "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG",
    2385            *expression.expressions,
    2386            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
    2387        )

def jsonobjectagg_sql(self, expression: sqlglot.expressions.JSONObjectAgg) -> str: View Source

    2389    def jsonobjectagg_sql(self, expression: exp.JSONObjectAgg) -> str:
    2390        return self.jsonobject_sql(expression)

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

    2392    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
    2393        null_handling = expression.args.get("null_handling")
    2394        null_handling = f" {null_handling}" if null_handling else ""
    2395        return_type = self.sql(expression, "return_type")
    2396        return_type = f" RETURNING {return_type}" if return_type else ""
    2397        strict = " STRICT" if expression.args.get("strict") else ""
    2398        return self.func(
    2399            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
    2400        )

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

    2402    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
    2403        this = self.sql(expression, "this")
    2404        order = self.sql(expression, "order")
    2405        null_handling = expression.args.get("null_handling")
    2406        null_handling = f" {null_handling}" if null_handling else ""
    2407        return_type = self.sql(expression, "return_type")
    2408        return_type = f" RETURNING {return_type}" if return_type else ""
    2409        strict = " STRICT" if expression.args.get("strict") else ""
    2410        return self.func(
    2411            "JSON_ARRAYAGG",
    2412            this,
    2413            suffix=f"{order}{null_handling}{return_type}{strict})",
    2414        )

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

    2416    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
    2417        path = self.sql(expression, "path")
    2418        path = f" PATH {path}" if path else ""
    2419        nested_schema = self.sql(expression, "nested_schema")
    2420
    2421        if nested_schema:
    2422            return f"NESTED{path} {nested_schema}"
    2423
    2424        this = self.sql(expression, "this")
    2425        kind = self.sql(expression, "kind")
    2426        kind = f" {kind}" if kind else ""
    2427        return f"{this}{kind}{path}"

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

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

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

    2432    def jsontable_sql(self, expression: exp.JSONTable) -> str:
    2433        this = self.sql(expression, "this")
    2434        path = self.sql(expression, "path")
    2435        path = f", {path}" if path else ""
    2436        error_handling = expression.args.get("error_handling")
    2437        error_handling = f" {error_handling}" if error_handling else ""
    2438        empty_handling = expression.args.get("empty_handling")
    2439        empty_handling = f" {empty_handling}" if empty_handling else ""
    2440        schema = self.sql(expression, "schema")
    2441        return self.func(
    2442            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
    2443        )

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

    2445    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    2446        this = self.sql(expression, "this")
    2447        kind = self.sql(expression, "kind")
    2448        path = self.sql(expression, "path")
    2449        path = f" {path}" if path else ""
    2450        as_json = " AS JSON" if expression.args.get("as_json") else ""
    2451        return f"{this} {kind}{path}{as_json}"

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

    2453    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    2454        this = self.sql(expression, "this")
    2455        path = self.sql(expression, "path")
    2456        path = f", {path}" if path else ""
    2457        expressions = self.expressions(expression)
    2458        with_ = (
    2459            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    2460            if expressions
    2461            else ""
    2462        )
    2463        return f"OPENJSON({this}{path}){with_}"

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

    2465    def in_sql(self, expression: exp.In) -> str:
    2466        query = expression.args.get("query")
    2467        unnest = expression.args.get("unnest")
    2468        field = expression.args.get("field")
    2469        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    2470
    2471        if query:
    2472            in_sql = self.wrap(query)
    2473        elif unnest:
    2474            in_sql = self.in_unnest_op(unnest)
    2475        elif field:
    2476            in_sql = self.sql(field)
    2477        else:
    2478            in_sql = f"({self.expressions(expression, flat=True)})"
    2479
    2480        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"

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

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

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

    2485    def interval_sql(self, expression: exp.Interval) -> str:
    2486        unit = self.sql(expression, "unit")
    2487        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    2488            unit = self.TIME_PART_SINGULARS.get(unit, unit)
    2489        unit = f" {unit}" if unit else ""
    2490
    2491        if self.SINGLE_STRING_INTERVAL:
    2492            this = expression.this.name if expression.this else ""
    2493            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    2494
    2495        this = self.sql(expression, "this")
    2496        if this:
    2497            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    2498            this = f" {this}" if unwrapped else f" ({this})"
    2499
    2500        return f"INTERVAL{this}{unit}"

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

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

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

    2505    def reference_sql(self, expression: exp.Reference) -> str:
    2506        this = self.sql(expression, "this")
    2507        expressions = self.expressions(expression, flat=True)
    2508        expressions = f"({expressions})" if expressions else ""
    2509        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2510        options = f" {options}" if options else ""
    2511        return f"REFERENCES {this}{expressions}{options}"

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

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

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

    2516    def paren_sql(self, expression: exp.Paren) -> str:
    2517        if isinstance(expression.unnest(), exp.Select):
    2518            sql = self.wrap(expression)
    2519        else:
    2520            sql = self.seg(self.indent(self.sql(expression, "this")), sep="")
    2521            sql = f"({sql}{self.seg(')', sep='')}"
    2522
    2523        return self.prepend_ctes(expression, sql)

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

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

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

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

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

    2534    def alias_sql(self, expression: exp.Alias) -> str:
    2535        alias = self.sql(expression, "alias")
    2536        alias = f" AS {alias}" if alias else ""
    2537        return f"{self.sql(expression, 'this')}{alias}"

def pivotalias_sql(self, expression: sqlglot.expressions.PivotAlias) -> str: View Source

    2539    def pivotalias_sql(self, expression: exp.PivotAlias) -> str:
    2540        alias = expression.args["alias"]
    2541        identifier_alias = isinstance(alias, exp.Identifier)
    2542
    2543        if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    2544            alias.replace(exp.Literal.string(alias.output_name))
    2545        elif not identifier_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    2546            alias.replace(exp.to_identifier(alias.output_name))
    2547
    2548        return self.alias_sql(expression)

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

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

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

    2553    def atindex_sql(self, expression: exp.AtTimeZone) -> str:
    2554        this = self.sql(expression, "this")
    2555        index = self.sql(expression, "expression")
    2556        return f"{this} AT {index}"

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

    2558    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    2559        this = self.sql(expression, "this")
    2560        zone = self.sql(expression, "zone")
    2561        return f"{this} AT TIME ZONE {zone}"

def fromtimezone_sql(self, expression: sqlglot.expressions.FromTimeZone) -> str: View Source

    2563    def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str:
    2564        this = self.sql(expression, "this")
    2565        zone = self.sql(expression, "zone")
    2566        return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'"

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

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

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

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

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

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

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

    2577    def connector_sql(self, expression: exp.Connector, op: str) -> str:
    2578        if not self.pretty:
    2579            return self.binary(expression, op)
    2580
    2581        sqls = tuple(
    2582            self.maybe_comment(self.sql(e), e, e.parent.comments or []) if i != 1 else self.sql(e)
    2583            for i, e in enumerate(expression.flatten(unnest=False))
    2584        )
    2585
    2586        sep = "\n" if self.text_width(sqls) > self.max_text_width else " "
    2587        return f"{sep}{op} ".join(sqls)

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

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

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

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

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

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

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

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

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

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

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

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

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

    2607    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    2608        format_sql = self.sql(expression, "format")
    2609        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    2610        to_sql = self.sql(expression, "to")
    2611        to_sql = f" {to_sql}" if to_sql else ""
    2612        return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{format_sql})"

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

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

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

    2618    def collate_sql(self, expression: exp.Collate) -> str:
    2619        if self.COLLATE_IS_FUNC:
    2620            return self.function_fallback_sql(expression)
    2621        return self.binary(expression, "COLLATE")

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

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

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

    2626    def comment_sql(self, expression: exp.Comment) -> str:
    2627        this = self.sql(expression, "this")
    2628        kind = expression.args["kind"]
    2629        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    2630        expression_sql = self.sql(expression, "expression")
    2631        return f"COMMENT{exists_sql}ON {kind} {this} IS {expression_sql}"

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

    2633    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    2634        this = self.sql(expression, "this")
    2635        delete = " DELETE" if expression.args.get("delete") else ""
    2636        recompress = self.sql(expression, "recompress")
    2637        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    2638        to_disk = self.sql(expression, "to_disk")
    2639        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    2640        to_volume = self.sql(expression, "to_volume")
    2641        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    2642        return f"{this}{delete}{recompress}{to_disk}{to_volume}"

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

    2644    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    2645        where = self.sql(expression, "where")
    2646        group = self.sql(expression, "group")
    2647        aggregates = self.expressions(expression, key="aggregates")
    2648        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    2649
    2650        if not (where or group or aggregates) and len(expression.expressions) == 1:
    2651            return f"TTL {self.expressions(expression, flat=True)}"
    2652
    2653        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"

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

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

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

    2658    def commit_sql(self, expression: exp.Commit) -> str:
    2659        chain = expression.args.get("chain")
    2660        if chain is not None:
    2661            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    2662
    2663        return f"COMMIT{chain or ''}"

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

    2665    def rollback_sql(self, expression: exp.Rollback) -> str:
    2666        savepoint = expression.args.get("savepoint")
    2667        savepoint = f" TO {savepoint}" if savepoint else ""
    2668        return f"ROLLBACK{savepoint}"

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

    2670    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    2671        this = self.sql(expression, "this")
    2672
    2673        dtype = self.sql(expression, "dtype")
    2674        if dtype:
    2675            collate = self.sql(expression, "collate")
    2676            collate = f" COLLATE {collate}" if collate else ""
    2677            using = self.sql(expression, "using")
    2678            using = f" USING {using}" if using else ""
    2679            return f"ALTER COLUMN {this} SET DATA TYPE {dtype}{collate}{using}"
    2680
    2681        default = self.sql(expression, "default")
    2682        if default:
    2683            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    2684
    2685        if not expression.args.get("drop"):
    2686            self.unsupported("Unsupported ALTER COLUMN syntax")
    2687
    2688        return f"ALTER COLUMN {this} DROP DEFAULT"

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

    2690    def renametable_sql(self, expression: exp.RenameTable) -> str:
    2691        if not self.RENAME_TABLE_WITH_DB:
    2692            # Remove db from tables
    2693            expression = expression.transform(
    2694                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    2695            )
    2696        this = self.sql(expression, "this")
    2697        return f"RENAME TO {this}"

def renamecolumn_sql(self, expression: sqlglot.expressions.RenameColumn) -> str: View Source

    2699    def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
    2700        exists = " IF EXISTS" if expression.args.get("exists") else ""
    2701        old_column = self.sql(expression, "this")
    2702        new_column = self.sql(expression, "to")
    2703        return f"RENAME COLUMN{exists} {old_column} TO {new_column}"

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

    2705    def altertable_sql(self, expression: exp.AlterTable) -> str:
    2706        actions = expression.args["actions"]
    2707
    2708        if isinstance(actions[0], exp.ColumnDef):
    2709            actions = self.add_column_sql(expression)
    2710        elif isinstance(actions[0], exp.Schema):
    2711            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    2712        elif isinstance(actions[0], exp.Delete):
    2713            actions = self.expressions(expression, key="actions", flat=True)
    2714        else:
    2715            actions = self.expressions(expression, key="actions", flat=True)
    2716
    2717        exists = " IF EXISTS" if expression.args.get("exists") else ""
    2718        only = " ONLY" if expression.args.get("only") else ""
    2719        return f"ALTER TABLE{exists}{only} {self.sql(expression, 'this')} {actions}"

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

    2721    def add_column_sql(self, expression: exp.AlterTable) -> str:
    2722        if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD:
    2723            return self.expressions(
    2724                expression,
    2725                key="actions",
    2726                prefix="ADD COLUMN ",
    2727            )
    2728        return f"ADD {self.expressions(expression, key='actions', flat=True)}"

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

    2730    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    2731        expressions = self.expressions(expression)
    2732        exists = " IF EXISTS " if expression.args.get("exists") else " "
    2733        return f"DROP{exists}{expressions}"

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

    2735    def addconstraint_sql(self, expression: exp.AddConstraint) -> str:
    2736        this = self.sql(expression, "this")
    2737        expression_ = self.sql(expression, "expression")
    2738        add_constraint = f"ADD CONSTRAINT {this}" if this else "ADD"
    2739
    2740        enforced = expression.args.get("enforced")
    2741        if enforced is not None:
    2742            return f"{add_constraint} CHECK ({expression_}){' ENFORCED' if enforced else ''}"
    2743
    2744        return f"{add_constraint} {expression_}"

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

    2746    def distinct_sql(self, expression: exp.Distinct) -> str:
    2747        this = self.expressions(expression, flat=True)
    2748        this = f" {this}" if this else ""
    2749
    2750        on = self.sql(expression, "on")
    2751        on = f" ON {on}" if on else ""
    2752        return f"DISTINCT{this}{on}"

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

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

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

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

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

    2760    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    2761        return self.sql(
    2762            exp.Cast(
    2763                this=exp.Div(this=expression.this, expression=expression.expression),
    2764                to=exp.DataType(this=exp.DataType.Type.INT),
    2765            )
    2766        )

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

    2768    def dpipe_sql(self, expression: exp.DPipe) -> str:
    2769        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    2770            return self.func("CONCAT", *(exp.cast(e, "text") for e in expression.flatten()))
    2771        return self.binary(expression, "||")

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

    2773    def div_sql(self, expression: exp.Div) -> str:
    2774        l, r = expression.left, expression.right
    2775
    2776        if not self.dialect.SAFE_DIVISION and expression.args.get("safe"):
    2777            r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0)))
    2778
    2779        if self.dialect.TYPED_DIVISION and not expression.args.get("typed"):
    2780            if not l.is_type(*exp.DataType.FLOAT_TYPES) and not r.is_type(
    2781                *exp.DataType.FLOAT_TYPES
    2782            ):
    2783                l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE))
    2784
    2785        elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"):
    2786            if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES):
    2787                return self.sql(
    2788                    exp.cast(
    2789                        l / r,
    2790                        to=exp.DataType.Type.BIGINT,
    2791                    )
    2792                )
    2793
    2794        return self.binary(expression, "/")

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

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

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

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

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

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

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

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

def propertyeq_sql(self, expression: sqlglot.expressions.PropertyEQ) -> str: View Source

    2808    def propertyeq_sql(self, expression: exp.PropertyEQ) -> str:
    2809        return self.binary(expression, ":=")

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

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

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

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

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

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

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

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

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

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

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

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

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

    2829    def is_sql(self, expression: exp.Is) -> str:
    2830        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    2831            return self.sql(
    2832                expression.this if expression.expression.this else exp.not_(expression.this)
    2833            )
    2834        return self.binary(expression, "IS")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    2878    def log_sql(self, expression: exp.Log) -> str:
    2879        this = expression.this
    2880        expr = expression.expression
    2881
    2882        if not self.dialect.LOG_BASE_FIRST:
    2883            this, expr = expr, this
    2884
    2885        return self.func("LOG", this, expr)

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

    2887    def use_sql(self, expression: exp.Use) -> str:
    2888        kind = self.sql(expression, "kind")
    2889        kind = f" {kind}" if kind else ""
    2890        this = self.sql(expression, "this")
    2891        this = f" {this}" if this else ""
    2892        return f"USE{kind}{this}"

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

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

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

    2898    def function_fallback_sql(self, expression: exp.Func) -> str:
    2899        args = []
    2900
    2901        for key in expression.arg_types:
    2902            arg_value = expression.args.get(key)
    2903
    2904            if isinstance(arg_value, list):
    2905                for value in arg_value:
    2906                    args.append(value)
    2907            elif arg_value is not None:
    2908                args.append(arg_value)
    2909
    2910        if self.normalize_functions:
    2911            name = expression.sql_name()
    2912        else:
    2913            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
    2914
    2915        return self.func(name, *args)

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

    2917    def func(
    2918        self,
    2919        name: str,
    2920        *args: t.Optional[exp.Expression | str],
    2921        prefix: str = "(",
    2922        suffix: str = ")",
    2923    ) -> str:
    2924        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

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

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

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

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

    2935    def format_time(self, expression: exp.Expression) -> t.Optional[str]:
    2936        return format_time(
    2937            self.sql(expression, "format"),
    2938            self.dialect.INVERSE_TIME_MAPPING,
    2939            self.dialect.INVERSE_TIME_TRIE,
    2940        )

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

    2942    def expressions(
    2943        self,
    2944        expression: t.Optional[exp.Expression] = None,
    2945        key: t.Optional[str] = None,
    2946        sqls: t.Optional[t.Collection[str | exp.Expression]] = None,
    2947        flat: bool = False,
    2948        indent: bool = True,
    2949        skip_first: bool = False,
    2950        sep: str = ", ",
    2951        prefix: str = "",
    2952    ) -> str:
    2953        expressions = expression.args.get(key or "expressions") if expression else sqls
    2954
    2955        if not expressions:
    2956            return ""
    2957
    2958        if flat:
    2959            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
    2960
    2961        num_sqls = len(expressions)
    2962
    2963        # These are calculated once in case we have the leading_comma / pretty option set, correspondingly
    2964        pad = " " * self.pad
    2965        stripped_sep = sep.strip()
    2966
    2967        result_sqls = []
    2968        for i, e in enumerate(expressions):
    2969            sql = self.sql(e, comment=False)
    2970            if not sql:
    2971                continue
    2972
    2973            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    2974
    2975            if self.pretty:
    2976                if self.leading_comma:
    2977                    result_sqls.append(f"{sep if i > 0 else pad}{prefix}{sql}{comments}")
    2978                else:
    2979                    result_sqls.append(
    2980                        f"{prefix}{sql}{stripped_sep if i + 1 < num_sqls else ''}{comments}"
    2981                    )
    2982            else:
    2983                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    2984
    2985        result_sql = "\n".join(result_sqls) if self.pretty else "".join(result_sqls)
    2986        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

    2988    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    2989        flat = flat or isinstance(expression.parent, exp.Properties)
    2990        expressions_sql = self.expressions(expression, flat=flat)
    2991        if flat:
    2992            return f"{op} {expressions_sql}"
    2993        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"

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

    2995    def naked_property(self, expression: exp.Property) -> str:
    2996        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    2997        if not property_name:
    2998            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    2999        return f"{property_name} {self.sql(expression, 'this')}"

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

    3001    def set_operation(self, expression: exp.Union, op: str) -> str:
    3002        this = self.maybe_comment(self.sql(expression, "this"), comments=expression.comments)
    3003        op = self.seg(op)
    3004        return self.query_modifiers(
    3005            expression, f"{this}{op}{self.sep()}{self.sql(expression, 'expression')}"
    3006        )

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

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

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

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

    3014    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    3015        this = self.sql(expression, "this")
    3016        expressions = self.no_identify(self.expressions, expression)
    3017        expressions = (
    3018            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    3019        )
    3020        return f"{this}{expressions}"

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

    3022    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    3023        this = self.sql(expression, "this")
    3024        expressions = self.expressions(expression, flat=True)
    3025        return f"{this}({expressions})"

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

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

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

    3030    def when_sql(self, expression: exp.When) -> str:
    3031        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    3032        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    3033        condition = self.sql(expression, "condition")
    3034        condition = f" AND {condition}" if condition else ""
    3035
    3036        then_expression = expression.args.get("then")
    3037        if isinstance(then_expression, exp.Insert):
    3038            then = f"INSERT {self.sql(then_expression, 'this')}"
    3039            if "expression" in then_expression.args:
    3040                then += f" VALUES {self.sql(then_expression, 'expression')}"
    3041        elif isinstance(then_expression, exp.Update):
    3042            if isinstance(then_expression.args.get("expressions"), exp.Star):
    3043                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    3044            else:
    3045                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    3046        else:
    3047            then = self.sql(then_expression)
    3048        return f"WHEN {matched}{source}{condition} THEN {then}"

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

    3050    def merge_sql(self, expression: exp.Merge) -> str:
    3051        table = expression.this
    3052        table_alias = ""
    3053
    3054        hints = table.args.get("hints")
    3055        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
    3056            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
    3057            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
    3058
    3059        this = self.sql(table)
    3060        using = f"USING {self.sql(expression, 'using')}"
    3061        on = f"ON {self.sql(expression, 'on')}"
    3062        expressions = self.expressions(expression, sep=" ")
    3063
    3064        return self.prepend_ctes(
    3065            expression, f"MERGE INTO {this}{table_alias} {using} {on} {expressions}"
    3066        )

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

    3068    def tochar_sql(self, expression: exp.ToChar) -> str:
    3069        if expression.args.get("format"):
    3070            self.unsupported("Format argument unsupported for TO_CHAR/TO_VARCHAR function")
    3071
    3072        return self.sql(exp.cast(expression.this, "text"))

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

    3074    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    3075        this = self.sql(expression, "this")
    3076        kind = self.sql(expression, "kind")
    3077        settings_sql = self.expressions(expression, key="settings", sep=" ")
    3078        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    3079        return f"{this}({kind}{args})"

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

    3081    def dictrange_sql(self, expression: exp.DictRange) -> str:
    3082        this = self.sql(expression, "this")
    3083        max = self.sql(expression, "max")
    3084        min = self.sql(expression, "min")
    3085        return f"{this}(MIN {min} MAX {max})"

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

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

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

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

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

    3093    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    3094        expressions = self.expressions(expression, key="expressions", flat=True)
    3095        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    3096        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    3097        buckets = self.sql(expression, "buckets")
    3098        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"

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

    3100    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    3101        this = self.sql(expression, "this")
    3102        having = self.sql(expression, "having")
    3103
    3104        if having:
    3105            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    3106
    3107        return self.func("ANY_VALUE", this)

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

    3109    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
    3110        transform = self.func("TRANSFORM", *expression.expressions)
    3111        row_format_before = self.sql(expression, "row_format_before")
    3112        row_format_before = f" {row_format_before}" if row_format_before else ""
    3113        record_writer = self.sql(expression, "record_writer")
    3114        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
    3115        using = f" USING {self.sql(expression, 'command_script')}"
    3116        schema = self.sql(expression, "schema")
    3117        schema = f" AS {schema}" if schema else ""
    3118        row_format_after = self.sql(expression, "row_format_after")
    3119        row_format_after = f" {row_format_after}" if row_format_after else ""
    3120        record_reader = self.sql(expression, "record_reader")
    3121        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
    3122        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

    3124    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
    3125        key_block_size = self.sql(expression, "key_block_size")
    3126        if key_block_size:
    3127            return f"KEY_BLOCK_SIZE = {key_block_size}"
    3128
    3129        using = self.sql(expression, "using")
    3130        if using:
    3131            return f"USING {using}"
    3132
    3133        parser = self.sql(expression, "parser")
    3134        if parser:
    3135            return f"WITH PARSER {parser}"
    3136
    3137        comment = self.sql(expression, "comment")
    3138        if comment:
    3139            return f"COMMENT {comment}"
    3140
    3141        visible = expression.args.get("visible")
    3142        if visible is not None:
    3143            return "VISIBLE" if visible else "INVISIBLE"
    3144
    3145        engine_attr = self.sql(expression, "engine_attr")
    3146        if engine_attr:
    3147            return f"ENGINE_ATTRIBUTE = {engine_attr}"
    3148
    3149        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
    3150        if secondary_engine_attr:
    3151            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
    3152
    3153        self.unsupported("Unsupported index constraint option.")
    3154        return ""

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

    3156    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
    3157        kind = self.sql(expression, "kind")
    3158        kind = f"{kind} INDEX" if kind else "INDEX"
    3159        this = self.sql(expression, "this")
    3160        this = f" {this}" if this else ""
    3161        index_type = self.sql(expression, "index_type")
    3162        index_type = f" USING {index_type}" if index_type else ""
    3163        schema = self.sql(expression, "schema")
    3164        schema = f" {schema}" if schema else ""
    3165        options = self.expressions(expression, key="options", sep=" ")
    3166        options = f" {options}" if options else ""
    3167        return f"{kind}{this}{index_type}{schema}{options}"

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

    3169    def nvl2_sql(self, expression: exp.Nvl2) -> str:
    3170        if self.NVL2_SUPPORTED:
    3171            return self.function_fallback_sql(expression)
    3172
    3173        case = exp.Case().when(
    3174            expression.this.is_(exp.null()).not_(copy=False),
    3175            expression.args["true"],
    3176            copy=False,
    3177        )
    3178        else_cond = expression.args.get("false")
    3179        if else_cond:
    3180            case.else_(else_cond, copy=False)
    3181
    3182        return self.sql(case)

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

    3184    def comprehension_sql(self, expression: exp.Comprehension) -> str:
    3185        this = self.sql(expression, "this")
    3186        expr = self.sql(expression, "expression")
    3187        iterator = self.sql(expression, "iterator")
    3188        condition = self.sql(expression, "condition")
    3189        condition = f" IF {condition}" if condition else ""
    3190        return f"{this} FOR {expr} IN {iterator}{condition}"

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

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

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

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

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

    3198    def predict_sql(self, expression: exp.Predict) -> str:
    3199        model = self.sql(expression, "this")
    3200        model = f"MODEL {model}"
    3201        table = self.sql(expression, "expression")
    3202        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
    3203        parameters = self.sql(expression, "params_struct")
    3204        return self.func("PREDICT", model, table, parameters or None)

def forin_sql(self, expression: sqlglot.expressions.ForIn) -> str: View Source

    3206    def forin_sql(self, expression: exp.ForIn) -> str:
    3207        this = self.sql(expression, "this")
    3208        expression_sql = self.sql(expression, "expression")
    3209        return f"FOR {this} DO {expression_sql}"

def refresh_sql(self, expression: sqlglot.expressions.Refresh) -> str: View Source

    3211    def refresh_sql(self, expression: exp.Refresh) -> str:
    3212        this = self.sql(expression, "this")
    3213        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
    3214        return f"REFRESH {table}{this}"

def operator_sql(self, expression: sqlglot.expressions.Operator) -> str: View Source

    3216    def operator_sql(self, expression: exp.Operator) -> str:
    3217        return self.binary(expression, f"OPERATOR({self.sql(expression, 'operator')})")

def toarray_sql(self, expression: sqlglot.expressions.ToArray) -> str: View Source

    3219    def toarray_sql(self, expression: exp.ToArray) -> str:
    3220        arg = expression.this
    3221        if not arg.type:
    3222            from sqlglot.optimizer.annotate_types import annotate_types
    3223
    3224            arg = annotate_types(arg)
    3225
    3226        if arg.is_type(exp.DataType.Type.ARRAY):
    3227            return self.sql(arg)
    3228
    3229        cond_for_null = arg.is_(exp.null())
    3230        return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.Array(expressions=[arg])))

def tsordstotime_sql(self, expression: sqlglot.expressions.TsOrDsToTime) -> str: View Source

    3232    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
    3233        this = expression.this
    3234        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
    3235            return self.sql(this)
    3236
    3237        return self.sql(exp.cast(this, "time"))

def tsordstodate_sql(self, expression: sqlglot.expressions.TsOrDsToDate) -> str: View Source

    3239    def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:
    3240        this = expression.this
    3241        time_format = self.format_time(expression)
    3242
    3243        if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT):
    3244            return self.sql(
    3245                exp.cast(exp.StrToTime(this=this, format=expression.args["format"]), "date")
    3246            )
    3247
    3248        if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE):
    3249            return self.sql(this)
    3250
    3251        return self.sql(exp.cast(this, "date"))

def unixdate_sql(self, expression: sqlglot.expressions.UnixDate) -> str: View Source

    3253    def unixdate_sql(self, expression: exp.UnixDate) -> str:
    3254        return self.sql(
    3255            exp.func(
    3256                "DATEDIFF",
    3257                expression.this,
    3258                exp.cast(exp.Literal.string("1970-01-01"), "date"),
    3259                "day",
    3260            )
    3261        )

def lastday_sql(self, expression: sqlglot.expressions.LastDay) -> str: View Source

    3263    def lastday_sql(self, expression: exp.LastDay) -> str:
    3264        if self.LAST_DAY_SUPPORTS_DATE_PART:
    3265            return self.function_fallback_sql(expression)
    3266
    3267        unit = expression.text("unit")
    3268        if unit and unit != "MONTH":
    3269            self.unsupported("Date parts are not supported in LAST_DAY.")
    3270
    3271        return self.func("LAST_DAY", expression.this)