Edit on GitHub

sqlglot.generator

   1from __future__ import annotations
   2
   3import logging
   4import re
   5import typing as t
   6from collections import defaultdict
   7from functools import reduce, wraps
   8
   9from sqlglot import exp
  10from sqlglot.errors import ErrorLevel, UnsupportedError, concat_messages
  11from sqlglot.helper import apply_index_offset, csv, name_sequence, seq_get
  12from sqlglot.jsonpath import ALL_JSON_PATH_PARTS, JSON_PATH_PART_TRANSFORMS
  13from sqlglot.time import format_time
  14from sqlglot.tokens import TokenType
  15
  16if t.TYPE_CHECKING:
  17    from sqlglot._typing import E
  18    from sqlglot.dialects.dialect import DialectType
  19
  20    G = t.TypeVar("G", bound="Generator")
  21    GeneratorMethod = t.Callable[[G, E], str]
  22
  23logger = logging.getLogger("sqlglot")
  24
  25ESCAPED_UNICODE_RE = re.compile(r"\\(\d+)")
  26UNSUPPORTED_TEMPLATE = "Argument '{}' is not supported for expression '{}' when targeting {}."
  27
  28
  29def unsupported_args(
  30    *args: t.Union[str, t.Tuple[str, str]],
  31) -> t.Callable[[GeneratorMethod], GeneratorMethod]:
  32    """
  33    Decorator that can be used to mark certain args of an `Expression` subclass as unsupported.
  34    It expects a sequence of argument names or pairs of the form (argument_name, diagnostic_msg).
  35    """
  36    diagnostic_by_arg: t.Dict[str, t.Optional[str]] = {}
  37    for arg in args:
  38        if isinstance(arg, str):
  39            diagnostic_by_arg[arg] = None
  40        else:
  41            diagnostic_by_arg[arg[0]] = arg[1]
  42
  43    def decorator(func: GeneratorMethod) -> GeneratorMethod:
  44        @wraps(func)
  45        def _func(generator: G, expression: E) -> str:
  46            expression_name = expression.__class__.__name__
  47            dialect_name = generator.dialect.__class__.__name__
  48
  49            for arg_name, diagnostic in diagnostic_by_arg.items():
  50                if expression.args.get(arg_name):
  51                    diagnostic = diagnostic or UNSUPPORTED_TEMPLATE.format(
  52                        arg_name, expression_name, dialect_name
  53                    )
  54                    generator.unsupported(diagnostic)
  55
  56            return func(generator, expression)
  57
  58        return _func
  59
  60    return decorator
  61
  62
  63class _Generator(type):
  64    def __new__(cls, clsname, bases, attrs):
  65        klass = super().__new__(cls, clsname, bases, attrs)
  66
  67        # Remove transforms that correspond to unsupported JSONPathPart expressions
  68        for part in ALL_JSON_PATH_PARTS - klass.SUPPORTED_JSON_PATH_PARTS:
  69            klass.TRANSFORMS.pop(part, None)
  70
  71        return klass
  72
  73
  74class Generator(metaclass=_Generator):
  75    """
  76    Generator converts a given syntax tree to the corresponding SQL string.
  77
  78    Args:
  79        pretty: Whether to format the produced SQL string.
  80            Default: False.
  81        identify: Determines when an identifier should be quoted. Possible values are:
  82            False (default): Never quote, except in cases where it's mandatory by the dialect.
  83            True or 'always': Always quote.
  84            'safe': Only quote identifiers that are case insensitive.
  85        normalize: Whether to normalize identifiers to lowercase.
  86            Default: False.
  87        pad: The pad size in a formatted string. For example, this affects the indentation of
  88            a projection in a query, relative to its nesting level.
  89            Default: 2.
  90        indent: The indentation size in a formatted string. For example, this affects the
  91            indentation of subqueries and filters under a `WHERE` clause.
  92            Default: 2.
  93        normalize_functions: How to normalize function names. Possible values are:
  94            "upper" or True (default): Convert names to uppercase.
  95            "lower": Convert names to lowercase.
  96            False: Disables function name normalization.
  97        unsupported_level: Determines the generator's behavior when it encounters unsupported expressions.
  98            Default ErrorLevel.WARN.
  99        max_unsupported: Maximum number of unsupported messages to include in a raised UnsupportedError.
 100            This is only relevant if unsupported_level is ErrorLevel.RAISE.
 101            Default: 3
 102        leading_comma: Whether the comma is leading or trailing in select expressions.
 103            This is only relevant when generating in pretty mode.
 104            Default: False
 105        max_text_width: The max number of characters in a segment before creating new lines in pretty mode.
 106            The default is on the smaller end because the length only represents a segment and not the true
 107            line length.
 108            Default: 80
 109        comments: Whether to preserve comments in the output SQL code.
 110            Default: True
 111    """
 112
 113    TRANSFORMS: t.Dict[t.Type[exp.Expression], t.Callable[..., str]] = {
 114        **JSON_PATH_PART_TRANSFORMS,
 115        exp.AllowedValuesProperty: lambda self,
 116        e: f"ALLOWED_VALUES {self.expressions(e, flat=True)}",
 117        exp.AnalyzeColumns: lambda self, e: self.sql(e, "this"),
 118        exp.AnalyzeWith: lambda self, e: self.expressions(e, prefix="WITH ", sep=" "),
 119        exp.ArrayContainsAll: lambda self, e: self.binary(e, "@>"),
 120        exp.ArrayOverlaps: lambda self, e: self.binary(e, "&&"),
 121        exp.AutoRefreshProperty: lambda self, e: f"AUTO REFRESH {self.sql(e, 'this')}",
 122        exp.BackupProperty: lambda self, e: f"BACKUP {self.sql(e, 'this')}",
 123        exp.CaseSpecificColumnConstraint: lambda _,
 124        e: f"{'NOT ' if e.args.get('not_') else ''}CASESPECIFIC",
 125        exp.Ceil: lambda self, e: self.ceil_floor(e),
 126        exp.CharacterSetColumnConstraint: lambda self, e: f"CHARACTER SET {self.sql(e, 'this')}",
 127        exp.CharacterSetProperty: lambda self,
 128        e: f"{'DEFAULT ' if e.args.get('default') else ''}CHARACTER SET={self.sql(e, 'this')}",
 129        exp.ClusteredColumnConstraint: lambda self,
 130        e: f"CLUSTERED ({self.expressions(e, 'this', indent=False)})",
 131        exp.CollateColumnConstraint: lambda self, e: f"COLLATE {self.sql(e, 'this')}",
 132        exp.CommentColumnConstraint: lambda self, e: f"COMMENT {self.sql(e, 'this')}",
 133        exp.ConnectByRoot: lambda self, e: f"CONNECT_BY_ROOT {self.sql(e, 'this')}",
 134        exp.ConvertToCharset: lambda self, e: self.func(
 135            "CONVERT", e.this, e.args["dest"], e.args.get("source")
 136        ),
 137        exp.CopyGrantsProperty: lambda *_: "COPY GRANTS",
 138        exp.CredentialsProperty: lambda self,
 139        e: f"CREDENTIALS=({self.expressions(e, 'expressions', sep=' ')})",
 140        exp.DateFormatColumnConstraint: lambda self, e: f"FORMAT {self.sql(e, 'this')}",
 141        exp.DefaultColumnConstraint: lambda self, e: f"DEFAULT {self.sql(e, 'this')}",
 142        exp.DynamicProperty: lambda *_: "DYNAMIC",
 143        exp.EmptyProperty: lambda *_: "EMPTY",
 144        exp.EncodeColumnConstraint: lambda self, e: f"ENCODE {self.sql(e, 'this')}",
 145        exp.EnviromentProperty: lambda self, e: f"ENVIRONMENT ({self.expressions(e, flat=True)})",
 146        exp.EphemeralColumnConstraint: lambda self,
 147        e: f"EPHEMERAL{(' ' + self.sql(e, 'this')) if e.this else ''}",
 148        exp.ExcludeColumnConstraint: lambda self, e: f"EXCLUDE {self.sql(e, 'this').lstrip()}",
 149        exp.ExecuteAsProperty: lambda self, e: self.naked_property(e),
 150        exp.Except: lambda self, e: self.set_operations(e),
 151        exp.ExternalProperty: lambda *_: "EXTERNAL",
 152        exp.Floor: lambda self, e: self.ceil_floor(e),
 153        exp.Get: lambda self, e: self.get_put_sql(e),
 154        exp.GlobalProperty: lambda *_: "GLOBAL",
 155        exp.HeapProperty: lambda *_: "HEAP",
 156        exp.IcebergProperty: lambda *_: "ICEBERG",
 157        exp.InheritsProperty: lambda self, e: f"INHERITS ({self.expressions(e, flat=True)})",
 158        exp.InlineLengthColumnConstraint: lambda self, e: f"INLINE LENGTH {self.sql(e, 'this')}",
 159        exp.InputModelProperty: lambda self, e: f"INPUT{self.sql(e, 'this')}",
 160        exp.Intersect: lambda self, e: self.set_operations(e),
 161        exp.IntervalSpan: lambda self, e: f"{self.sql(e, 'this')} TO {self.sql(e, 'expression')}",
 162        exp.Int64: lambda self, e: self.sql(exp.cast(e.this, exp.DataType.Type.BIGINT)),
 163        exp.LanguageProperty: lambda self, e: self.naked_property(e),
 164        exp.LocationProperty: lambda self, e: self.naked_property(e),
 165        exp.LogProperty: lambda _, e: f"{'NO ' if e.args.get('no') else ''}LOG",
 166        exp.MaterializedProperty: lambda *_: "MATERIALIZED",
 167        exp.NonClusteredColumnConstraint: lambda self,
 168        e: f"NONCLUSTERED ({self.expressions(e, 'this', indent=False)})",
 169        exp.NoPrimaryIndexProperty: lambda *_: "NO PRIMARY INDEX",
 170        exp.NotForReplicationColumnConstraint: lambda *_: "NOT FOR REPLICATION",
 171        exp.OnCommitProperty: lambda _,
 172        e: f"ON COMMIT {'DELETE' if e.args.get('delete') else 'PRESERVE'} ROWS",
 173        exp.OnProperty: lambda self, e: f"ON {self.sql(e, 'this')}",
 174        exp.OnUpdateColumnConstraint: lambda self, e: f"ON UPDATE {self.sql(e, 'this')}",
 175        exp.Operator: lambda self, e: self.binary(e, ""),  # The operator is produced in `binary`
 176        exp.OutputModelProperty: lambda self, e: f"OUTPUT{self.sql(e, 'this')}",
 177        exp.PathColumnConstraint: lambda self, e: f"PATH {self.sql(e, 'this')}",
 178        exp.PartitionedByBucket: lambda self, e: self.func("BUCKET", e.this, e.expression),
 179        exp.PartitionByTruncate: lambda self, e: self.func("TRUNCATE", e.this, e.expression),
 180        exp.PivotAny: lambda self, e: f"ANY{self.sql(e, 'this')}",
 181        exp.ProjectionPolicyColumnConstraint: lambda self,
 182        e: f"PROJECTION POLICY {self.sql(e, 'this')}",
 183        exp.Put: lambda self, e: self.get_put_sql(e),
 184        exp.RemoteWithConnectionModelProperty: lambda self,
 185        e: f"REMOTE WITH CONNECTION {self.sql(e, 'this')}",
 186        exp.ReturnsProperty: lambda self, e: (
 187            "RETURNS NULL ON NULL INPUT" if e.args.get("null") else self.naked_property(e)
 188        ),
 189        exp.SampleProperty: lambda self, e: f"SAMPLE BY {self.sql(e, 'this')}",
 190        exp.SecureProperty: lambda *_: "SECURE",
 191        exp.SecurityProperty: lambda self, e: f"SECURITY {self.sql(e, 'this')}",
 192        exp.SetConfigProperty: lambda self, e: self.sql(e, "this"),
 193        exp.SetProperty: lambda _, e: f"{'MULTI' if e.args.get('multi') else ''}SET",
 194        exp.SettingsProperty: lambda self, e: f"SETTINGS{self.seg('')}{(self.expressions(e))}",
 195        exp.SharingProperty: lambda self, e: f"SHARING={self.sql(e, 'this')}",
 196        exp.SqlReadWriteProperty: lambda _, e: e.name,
 197        exp.SqlSecurityProperty: lambda _,
 198        e: f"SQL SECURITY {'DEFINER' if e.args.get('definer') else 'INVOKER'}",
 199        exp.StabilityProperty: lambda _, e: e.name,
 200        exp.Stream: lambda self, e: f"STREAM {self.sql(e, 'this')}",
 201        exp.StreamingTableProperty: lambda *_: "STREAMING",
 202        exp.StrictProperty: lambda *_: "STRICT",
 203        exp.SwapTable: lambda self, e: f"SWAP WITH {self.sql(e, 'this')}",
 204        exp.Tags: lambda self, e: f"TAG ({self.expressions(e, flat=True)})",
 205        exp.TemporaryProperty: lambda *_: "TEMPORARY",
 206        exp.TitleColumnConstraint: lambda self, e: f"TITLE {self.sql(e, 'this')}",
 207        exp.ToMap: lambda self, e: f"MAP {self.sql(e, 'this')}",
 208        exp.ToTableProperty: lambda self, e: f"TO {self.sql(e.this)}",
 209        exp.TransformModelProperty: lambda self, e: self.func("TRANSFORM", *e.expressions),
 210        exp.TransientProperty: lambda *_: "TRANSIENT",
 211        exp.Union: lambda self, e: self.set_operations(e),
 212        exp.UnloggedProperty: lambda *_: "UNLOGGED",
 213        exp.UsingTemplateProperty: lambda self, e: f"USING TEMPLATE {self.sql(e, 'this')}",
 214        exp.UsingData: lambda self, e: f"USING DATA {self.sql(e, 'this')}",
 215        exp.Uuid: lambda *_: "UUID()",
 216        exp.UppercaseColumnConstraint: lambda *_: "UPPERCASE",
 217        exp.VarMap: lambda self, e: self.func("MAP", e.args["keys"], e.args["values"]),
 218        exp.ViewAttributeProperty: lambda self, e: f"WITH {self.sql(e, 'this')}",
 219        exp.VolatileProperty: lambda *_: "VOLATILE",
 220        exp.WithJournalTableProperty: lambda self, e: f"WITH JOURNAL TABLE={self.sql(e, 'this')}",
 221        exp.WithProcedureOptions: lambda self, e: f"WITH {self.expressions(e, flat=True)}",
 222        exp.WithSchemaBindingProperty: lambda self, e: f"WITH SCHEMA {self.sql(e, 'this')}",
 223        exp.WithOperator: lambda self, e: f"{self.sql(e, 'this')} WITH {self.sql(e, 'op')}",
 224        exp.ForceProperty: lambda *_: "FORCE",
 225    }
 226
 227    # Whether null ordering is supported in order by
 228    # True: Full Support, None: No support, False: No support for certain cases
 229    # such as window specifications, aggregate functions etc
 230    NULL_ORDERING_SUPPORTED: t.Optional[bool] = True
 231
 232    # Whether ignore nulls is inside the agg or outside.
 233    # FIRST(x IGNORE NULLS) OVER vs FIRST (x) IGNORE NULLS OVER
 234    IGNORE_NULLS_IN_FUNC = False
 235
 236    # Whether locking reads (i.e. SELECT ... FOR UPDATE/SHARE) are supported
 237    LOCKING_READS_SUPPORTED = False
 238
 239    # Whether the EXCEPT and INTERSECT operations can return duplicates
 240    EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = True
 241
 242    # Wrap derived values in parens, usually standard but spark doesn't support it
 243    WRAP_DERIVED_VALUES = True
 244
 245    # Whether create function uses an AS before the RETURN
 246    CREATE_FUNCTION_RETURN_AS = True
 247
 248    # Whether MERGE ... WHEN MATCHED BY SOURCE is allowed
 249    MATCHED_BY_SOURCE = True
 250
 251    # Whether the INTERVAL expression works only with values like '1 day'
 252    SINGLE_STRING_INTERVAL = False
 253
 254    # Whether the plural form of date parts like day (i.e. "days") is supported in INTERVALs
 255    INTERVAL_ALLOWS_PLURAL_FORM = True
 256
 257    # Whether limit and fetch are supported (possible values: "ALL", "LIMIT", "FETCH")
 258    LIMIT_FETCH = "ALL"
 259
 260    # Whether limit and fetch allows expresions or just limits
 261    LIMIT_ONLY_LITERALS = False
 262
 263    # Whether a table is allowed to be renamed with a db
 264    RENAME_TABLE_WITH_DB = True
 265
 266    # The separator for grouping sets and rollups
 267    GROUPINGS_SEP = ","
 268
 269    # The string used for creating an index on a table
 270    INDEX_ON = "ON"
 271
 272    # Whether join hints should be generated
 273    JOIN_HINTS = True
 274
 275    # Whether table hints should be generated
 276    TABLE_HINTS = True
 277
 278    # Whether query hints should be generated
 279    QUERY_HINTS = True
 280
 281    # What kind of separator to use for query hints
 282    QUERY_HINT_SEP = ", "
 283
 284    # Whether comparing against booleans (e.g. x IS TRUE) is supported
 285    IS_BOOL_ALLOWED = True
 286
 287    # Whether to include the "SET" keyword in the "INSERT ... ON DUPLICATE KEY UPDATE" statement
 288    DUPLICATE_KEY_UPDATE_WITH_SET = True
 289
 290    # Whether to generate the limit as TOP <value> instead of LIMIT <value>
 291    LIMIT_IS_TOP = False
 292
 293    # Whether to generate INSERT INTO ... RETURNING or INSERT INTO RETURNING ...
 294    RETURNING_END = True
 295
 296    # Whether to generate an unquoted value for EXTRACT's date part argument
 297    EXTRACT_ALLOWS_QUOTES = True
 298
 299    # Whether TIMETZ / TIMESTAMPTZ will be generated using the "WITH TIME ZONE" syntax
 300    TZ_TO_WITH_TIME_ZONE = False
 301
 302    # Whether the NVL2 function is supported
 303    NVL2_SUPPORTED = True
 304
 305    # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax
 306    SELECT_KINDS: t.Tuple[str, ...] = ("STRUCT", "VALUE")
 307
 308    # Whether VALUES statements can be used as derived tables.
 309    # MySQL 5 and Redshift do not allow this, so when False, it will convert
 310    # SELECT * VALUES into SELECT UNION
 311    VALUES_AS_TABLE = True
 312
 313    # Whether the word COLUMN is included when adding a column with ALTER TABLE
 314    ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = True
 315
 316    # UNNEST WITH ORDINALITY (presto) instead of UNNEST WITH OFFSET (bigquery)
 317    UNNEST_WITH_ORDINALITY = True
 318
 319    # Whether FILTER (WHERE cond) can be used for conditional aggregation
 320    AGGREGATE_FILTER_SUPPORTED = True
 321
 322    # Whether JOIN sides (LEFT, RIGHT) are supported in conjunction with SEMI/ANTI join kinds
 323    SEMI_ANTI_JOIN_WITH_SIDE = True
 324
 325    # Whether to include the type of a computed column in the CREATE DDL
 326    COMPUTED_COLUMN_WITH_TYPE = True
 327
 328    # Whether CREATE TABLE .. COPY .. is supported. False means we'll generate CLONE instead of COPY
 329    SUPPORTS_TABLE_COPY = True
 330
 331    # Whether parentheses are required around the table sample's expression
 332    TABLESAMPLE_REQUIRES_PARENS = True
 333
 334    # Whether a table sample clause's size needs to be followed by the ROWS keyword
 335    TABLESAMPLE_SIZE_IS_ROWS = True
 336
 337    # The keyword(s) to use when generating a sample clause
 338    TABLESAMPLE_KEYWORDS = "TABLESAMPLE"
 339
 340    # Whether the TABLESAMPLE clause supports a method name, like BERNOULLI
 341    TABLESAMPLE_WITH_METHOD = True
 342
 343    # The keyword to use when specifying the seed of a sample clause
 344    TABLESAMPLE_SEED_KEYWORD = "SEED"
 345
 346    # Whether COLLATE is a function instead of a binary operator
 347    COLLATE_IS_FUNC = False
 348
 349    # Whether data types support additional specifiers like e.g. CHAR or BYTE (oracle)
 350    DATA_TYPE_SPECIFIERS_ALLOWED = False
 351
 352    # Whether conditions require booleans WHERE x = 0 vs WHERE x
 353    ENSURE_BOOLS = False
 354
 355    # Whether the "RECURSIVE" keyword is required when defining recursive CTEs
 356    CTE_RECURSIVE_KEYWORD_REQUIRED = True
 357
 358    # Whether CONCAT requires >1 arguments
 359    SUPPORTS_SINGLE_ARG_CONCAT = True
 360
 361    # Whether LAST_DAY function supports a date part argument
 362    LAST_DAY_SUPPORTS_DATE_PART = True
 363
 364    # Whether named columns are allowed in table aliases
 365    SUPPORTS_TABLE_ALIAS_COLUMNS = True
 366
 367    # Whether UNPIVOT aliases are Identifiers (False means they're Literals)
 368    UNPIVOT_ALIASES_ARE_IDENTIFIERS = True
 369
 370    # What delimiter to use for separating JSON key/value pairs
 371    JSON_KEY_VALUE_PAIR_SEP = ":"
 372
 373    # INSERT OVERWRITE TABLE x override
 374    INSERT_OVERWRITE = " OVERWRITE TABLE"
 375
 376    # Whether the SELECT .. INTO syntax is used instead of CTAS
 377    SUPPORTS_SELECT_INTO = False
 378
 379    # Whether UNLOGGED tables can be created
 380    SUPPORTS_UNLOGGED_TABLES = False
 381
 382    # Whether the CREATE TABLE LIKE statement is supported
 383    SUPPORTS_CREATE_TABLE_LIKE = True
 384
 385    # Whether the LikeProperty needs to be specified inside of the schema clause
 386    LIKE_PROPERTY_INSIDE_SCHEMA = False
 387
 388    # Whether DISTINCT can be followed by multiple args in an AggFunc. If not, it will be
 389    # transpiled into a series of CASE-WHEN-ELSE, ultimately using a tuple conseisting of the args
 390    MULTI_ARG_DISTINCT = True
 391
 392    # Whether the JSON extraction operators expect a value of type JSON
 393    JSON_TYPE_REQUIRED_FOR_EXTRACTION = False
 394
 395    # Whether bracketed keys like ["foo"] are supported in JSON paths
 396    JSON_PATH_BRACKETED_KEY_SUPPORTED = True
 397
 398    # Whether to escape keys using single quotes in JSON paths
 399    JSON_PATH_SINGLE_QUOTE_ESCAPE = False
 400
 401    # The JSONPathPart expressions supported by this dialect
 402    SUPPORTED_JSON_PATH_PARTS = ALL_JSON_PATH_PARTS.copy()
 403
 404    # Whether any(f(x) for x in array) can be implemented by this dialect
 405    CAN_IMPLEMENT_ARRAY_ANY = False
 406
 407    # Whether the function TO_NUMBER is supported
 408    SUPPORTS_TO_NUMBER = True
 409
 410    # Whether EXCLUDE in window specification is supported
 411    SUPPORTS_WINDOW_EXCLUDE = False
 412
 413    # Whether or not set op modifiers apply to the outer set op or select.
 414    # SELECT * FROM x UNION SELECT * FROM y LIMIT 1
 415    # True means limit 1 happens after the set op, False means it it happens on y.
 416    SET_OP_MODIFIERS = True
 417
 418    # Whether parameters from COPY statement are wrapped in parentheses
 419    COPY_PARAMS_ARE_WRAPPED = True
 420
 421    # Whether values of params are set with "=" token or empty space
 422    COPY_PARAMS_EQ_REQUIRED = False
 423
 424    # Whether COPY statement has INTO keyword
 425    COPY_HAS_INTO_KEYWORD = True
 426
 427    # Whether the conditional TRY(expression) function is supported
 428    TRY_SUPPORTED = True
 429
 430    # Whether the UESCAPE syntax in unicode strings is supported
 431    SUPPORTS_UESCAPE = True
 432
 433    # The keyword to use when generating a star projection with excluded columns
 434    STAR_EXCEPT = "EXCEPT"
 435
 436    # The HEX function name
 437    HEX_FUNC = "HEX"
 438
 439    # The keywords to use when prefixing & separating WITH based properties
 440    WITH_PROPERTIES_PREFIX = "WITH"
 441
 442    # Whether to quote the generated expression of exp.JsonPath
 443    QUOTE_JSON_PATH = True
 444
 445    # Whether the text pattern/fill (3rd) parameter of RPAD()/LPAD() is optional (defaults to space)
 446    PAD_FILL_PATTERN_IS_REQUIRED = False
 447
 448    # Whether a projection can explode into multiple rows, e.g. by unnesting an array.
 449    SUPPORTS_EXPLODING_PROJECTIONS = True
 450
 451    # Whether ARRAY_CONCAT can be generated with varlen args or if it should be reduced to 2-arg version
 452    ARRAY_CONCAT_IS_VAR_LEN = True
 453
 454    # Whether CONVERT_TIMEZONE() is supported; if not, it will be generated as exp.AtTimeZone
 455    SUPPORTS_CONVERT_TIMEZONE = False
 456
 457    # Whether MEDIAN(expr) is supported; if not, it will be generated as PERCENTILE_CONT(expr, 0.5)
 458    SUPPORTS_MEDIAN = True
 459
 460    # Whether UNIX_SECONDS(timestamp) is supported
 461    SUPPORTS_UNIX_SECONDS = False
 462
 463    # Whether to wrap <props> in `AlterSet`, e.g., ALTER ... SET (<props>)
 464    ALTER_SET_WRAPPED = False
 465
 466    # The name to generate for the JSONPath expression. If `None`, only `this` will be generated
 467    PARSE_JSON_NAME: t.Optional[str] = "PARSE_JSON"
 468
 469    # The function name of the exp.ArraySize expression
 470    ARRAY_SIZE_NAME: str = "ARRAY_LENGTH"
 471
 472    # The syntax to use when altering the type of a column
 473    ALTER_SET_TYPE = "SET DATA TYPE"
 474
 475    # Whether exp.ArraySize should generate the dimension arg too (valid for Postgres & DuckDB)
 476    # None -> Doesn't support it at all
 477    # False (DuckDB) -> Has backwards-compatible support, but preferably generated without
 478    # True (Postgres) -> Explicitly requires it
 479    ARRAY_SIZE_DIM_REQUIRED: t.Optional[bool] = None
 480
 481    TYPE_MAPPING = {
 482        exp.DataType.Type.DATETIME2: "TIMESTAMP",
 483        exp.DataType.Type.NCHAR: "CHAR",
 484        exp.DataType.Type.NVARCHAR: "VARCHAR",
 485        exp.DataType.Type.MEDIUMTEXT: "TEXT",
 486        exp.DataType.Type.LONGTEXT: "TEXT",
 487        exp.DataType.Type.TINYTEXT: "TEXT",
 488        exp.DataType.Type.BLOB: "VARBINARY",
 489        exp.DataType.Type.MEDIUMBLOB: "BLOB",
 490        exp.DataType.Type.LONGBLOB: "BLOB",
 491        exp.DataType.Type.TINYBLOB: "BLOB",
 492        exp.DataType.Type.INET: "INET",
 493        exp.DataType.Type.ROWVERSION: "VARBINARY",
 494        exp.DataType.Type.SMALLDATETIME: "TIMESTAMP",
 495    }
 496
 497    TIME_PART_SINGULARS = {
 498        "MICROSECONDS": "MICROSECOND",
 499        "SECONDS": "SECOND",
 500        "MINUTES": "MINUTE",
 501        "HOURS": "HOUR",
 502        "DAYS": "DAY",
 503        "WEEKS": "WEEK",
 504        "MONTHS": "MONTH",
 505        "QUARTERS": "QUARTER",
 506        "YEARS": "YEAR",
 507    }
 508
 509    AFTER_HAVING_MODIFIER_TRANSFORMS = {
 510        "cluster": lambda self, e: self.sql(e, "cluster"),
 511        "distribute": lambda self, e: self.sql(e, "distribute"),
 512        "sort": lambda self, e: self.sql(e, "sort"),
 513        "windows": lambda self, e: (
 514            self.seg("WINDOW ") + self.expressions(e, key="windows", flat=True)
 515            if e.args.get("windows")
 516            else ""
 517        ),
 518        "qualify": lambda self, e: self.sql(e, "qualify"),
 519    }
 520
 521    TOKEN_MAPPING: t.Dict[TokenType, str] = {}
 522
 523    STRUCT_DELIMITER = ("<", ">")
 524
 525    PARAMETER_TOKEN = "@"
 526    NAMED_PLACEHOLDER_TOKEN = ":"
 527
 528    EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: t.Set[str] = set()
 529
 530    PROPERTIES_LOCATION = {
 531        exp.AllowedValuesProperty: exp.Properties.Location.POST_SCHEMA,
 532        exp.AlgorithmProperty: exp.Properties.Location.POST_CREATE,
 533        exp.AutoIncrementProperty: exp.Properties.Location.POST_SCHEMA,
 534        exp.AutoRefreshProperty: exp.Properties.Location.POST_SCHEMA,
 535        exp.BackupProperty: exp.Properties.Location.POST_SCHEMA,
 536        exp.BlockCompressionProperty: exp.Properties.Location.POST_NAME,
 537        exp.CharacterSetProperty: exp.Properties.Location.POST_SCHEMA,
 538        exp.ChecksumProperty: exp.Properties.Location.POST_NAME,
 539        exp.CollateProperty: exp.Properties.Location.POST_SCHEMA,
 540        exp.CopyGrantsProperty: exp.Properties.Location.POST_SCHEMA,
 541        exp.Cluster: exp.Properties.Location.POST_SCHEMA,
 542        exp.ClusteredByProperty: exp.Properties.Location.POST_SCHEMA,
 543        exp.DistributedByProperty: exp.Properties.Location.POST_SCHEMA,
 544        exp.DuplicateKeyProperty: exp.Properties.Location.POST_SCHEMA,
 545        exp.DataBlocksizeProperty: exp.Properties.Location.POST_NAME,
 546        exp.DataDeletionProperty: exp.Properties.Location.POST_SCHEMA,
 547        exp.DefinerProperty: exp.Properties.Location.POST_CREATE,
 548        exp.DictRange: exp.Properties.Location.POST_SCHEMA,
 549        exp.DictProperty: exp.Properties.Location.POST_SCHEMA,
 550        exp.DynamicProperty: exp.Properties.Location.POST_CREATE,
 551        exp.DistKeyProperty: exp.Properties.Location.POST_SCHEMA,
 552        exp.DistStyleProperty: exp.Properties.Location.POST_SCHEMA,
 553        exp.EmptyProperty: exp.Properties.Location.POST_SCHEMA,
 554        exp.EncodeProperty: exp.Properties.Location.POST_EXPRESSION,
 555        exp.EngineProperty: exp.Properties.Location.POST_SCHEMA,
 556        exp.EnviromentProperty: exp.Properties.Location.POST_SCHEMA,
 557        exp.ExecuteAsProperty: exp.Properties.Location.POST_SCHEMA,
 558        exp.ExternalProperty: exp.Properties.Location.POST_CREATE,
 559        exp.FallbackProperty: exp.Properties.Location.POST_NAME,
 560        exp.FileFormatProperty: exp.Properties.Location.POST_WITH,
 561        exp.FreespaceProperty: exp.Properties.Location.POST_NAME,
 562        exp.GlobalProperty: exp.Properties.Location.POST_CREATE,
 563        exp.HeapProperty: exp.Properties.Location.POST_WITH,
 564        exp.InheritsProperty: exp.Properties.Location.POST_SCHEMA,
 565        exp.IcebergProperty: exp.Properties.Location.POST_CREATE,
 566        exp.IncludeProperty: exp.Properties.Location.POST_SCHEMA,
 567        exp.InputModelProperty: exp.Properties.Location.POST_SCHEMA,
 568        exp.IsolatedLoadingProperty: exp.Properties.Location.POST_NAME,
 569        exp.JournalProperty: exp.Properties.Location.POST_NAME,
 570        exp.LanguageProperty: exp.Properties.Location.POST_SCHEMA,
 571        exp.LikeProperty: exp.Properties.Location.POST_SCHEMA,
 572        exp.LocationProperty: exp.Properties.Location.POST_SCHEMA,
 573        exp.LockProperty: exp.Properties.Location.POST_SCHEMA,
 574        exp.LockingProperty: exp.Properties.Location.POST_ALIAS,
 575        exp.LogProperty: exp.Properties.Location.POST_NAME,
 576        exp.MaterializedProperty: exp.Properties.Location.POST_CREATE,
 577        exp.MergeBlockRatioProperty: exp.Properties.Location.POST_NAME,
 578        exp.NoPrimaryIndexProperty: exp.Properties.Location.POST_EXPRESSION,
 579        exp.OnProperty: exp.Properties.Location.POST_SCHEMA,
 580        exp.OnCommitProperty: exp.Properties.Location.POST_EXPRESSION,
 581        exp.Order: exp.Properties.Location.POST_SCHEMA,
 582        exp.OutputModelProperty: exp.Properties.Location.POST_SCHEMA,
 583        exp.PartitionedByProperty: exp.Properties.Location.POST_WITH,
 584        exp.PartitionedOfProperty: exp.Properties.Location.POST_SCHEMA,
 585        exp.PrimaryKey: exp.Properties.Location.POST_SCHEMA,
 586        exp.Property: exp.Properties.Location.POST_WITH,
 587        exp.RemoteWithConnectionModelProperty: exp.Properties.Location.POST_SCHEMA,
 588        exp.ReturnsProperty: exp.Properties.Location.POST_SCHEMA,
 589        exp.RowFormatProperty: exp.Properties.Location.POST_SCHEMA,
 590        exp.RowFormatDelimitedProperty: exp.Properties.Location.POST_SCHEMA,
 591        exp.RowFormatSerdeProperty: exp.Properties.Location.POST_SCHEMA,
 592        exp.SampleProperty: exp.Properties.Location.POST_SCHEMA,
 593        exp.SchemaCommentProperty: exp.Properties.Location.POST_SCHEMA,
 594        exp.SecureProperty: exp.Properties.Location.POST_CREATE,
 595        exp.SecurityProperty: exp.Properties.Location.POST_SCHEMA,
 596        exp.SerdeProperties: exp.Properties.Location.POST_SCHEMA,
 597        exp.Set: exp.Properties.Location.POST_SCHEMA,
 598        exp.SettingsProperty: exp.Properties.Location.POST_SCHEMA,
 599        exp.SetProperty: exp.Properties.Location.POST_CREATE,
 600        exp.SetConfigProperty: exp.Properties.Location.POST_SCHEMA,
 601        exp.SharingProperty: exp.Properties.Location.POST_EXPRESSION,
 602        exp.SequenceProperties: exp.Properties.Location.POST_EXPRESSION,
 603        exp.SortKeyProperty: exp.Properties.Location.POST_SCHEMA,
 604        exp.SqlReadWriteProperty: exp.Properties.Location.POST_SCHEMA,
 605        exp.SqlSecurityProperty: exp.Properties.Location.POST_CREATE,
 606        exp.StabilityProperty: exp.Properties.Location.POST_SCHEMA,
 607        exp.StorageHandlerProperty: exp.Properties.Location.POST_SCHEMA,
 608        exp.StreamingTableProperty: exp.Properties.Location.POST_CREATE,
 609        exp.StrictProperty: exp.Properties.Location.POST_SCHEMA,
 610        exp.Tags: exp.Properties.Location.POST_WITH,
 611        exp.TemporaryProperty: exp.Properties.Location.POST_CREATE,
 612        exp.ToTableProperty: exp.Properties.Location.POST_SCHEMA,
 613        exp.TransientProperty: exp.Properties.Location.POST_CREATE,
 614        exp.TransformModelProperty: exp.Properties.Location.POST_SCHEMA,
 615        exp.MergeTreeTTL: exp.Properties.Location.POST_SCHEMA,
 616        exp.UnloggedProperty: exp.Properties.Location.POST_CREATE,
 617        exp.UsingTemplateProperty: exp.Properties.Location.POST_SCHEMA,
 618        exp.ViewAttributeProperty: exp.Properties.Location.POST_SCHEMA,
 619        exp.VolatileProperty: exp.Properties.Location.POST_CREATE,
 620        exp.WithDataProperty: exp.Properties.Location.POST_EXPRESSION,
 621        exp.WithJournalTableProperty: exp.Properties.Location.POST_NAME,
 622        exp.WithProcedureOptions: exp.Properties.Location.POST_SCHEMA,
 623        exp.WithSchemaBindingProperty: exp.Properties.Location.POST_SCHEMA,
 624        exp.WithSystemVersioningProperty: exp.Properties.Location.POST_SCHEMA,
 625        exp.ForceProperty: exp.Properties.Location.POST_CREATE,
 626    }
 627
 628    # Keywords that can't be used as unquoted identifier names
 629    RESERVED_KEYWORDS: t.Set[str] = set()
 630
 631    # Expressions whose comments are separated from them for better formatting
 632    WITH_SEPARATED_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = (
 633        exp.Command,
 634        exp.Create,
 635        exp.Describe,
 636        exp.Delete,
 637        exp.Drop,
 638        exp.From,
 639        exp.Insert,
 640        exp.Join,
 641        exp.MultitableInserts,
 642        exp.Select,
 643        exp.SetOperation,
 644        exp.Update,
 645        exp.Where,
 646        exp.With,
 647    )
 648
 649    # Expressions that should not have their comments generated in maybe_comment
 650    EXCLUDE_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = (
 651        exp.Binary,
 652        exp.SetOperation,
 653    )
 654
 655    # Expressions that can remain unwrapped when appearing in the context of an INTERVAL
 656    UNWRAPPED_INTERVAL_VALUES: t.Tuple[t.Type[exp.Expression], ...] = (
 657        exp.Column,
 658        exp.Literal,
 659        exp.Neg,
 660        exp.Paren,
 661    )
 662
 663    PARAMETERIZABLE_TEXT_TYPES = {
 664        exp.DataType.Type.NVARCHAR,
 665        exp.DataType.Type.VARCHAR,
 666        exp.DataType.Type.CHAR,
 667        exp.DataType.Type.NCHAR,
 668    }
 669
 670    # Expressions that need to have all CTEs under them bubbled up to them
 671    EXPRESSIONS_WITHOUT_NESTED_CTES: t.Set[t.Type[exp.Expression]] = set()
 672
 673    RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS: t.Tuple[t.Type[exp.Expression], ...] = ()
 674
 675    SENTINEL_LINE_BREAK = "__SQLGLOT__LB__"
 676
 677    __slots__ = (
 678        "pretty",
 679        "identify",
 680        "normalize",
 681        "pad",
 682        "_indent",
 683        "normalize_functions",
 684        "unsupported_level",
 685        "max_unsupported",
 686        "leading_comma",
 687        "max_text_width",
 688        "comments",
 689        "dialect",
 690        "unsupported_messages",
 691        "_escaped_quote_end",
 692        "_escaped_identifier_end",
 693        "_next_name",
 694        "_identifier_start",
 695        "_identifier_end",
 696        "_quote_json_path_key_using_brackets",
 697    )
 698
 699    def __init__(
 700        self,
 701        pretty: t.Optional[bool] = None,
 702        identify: str | bool = False,
 703        normalize: bool = False,
 704        pad: int = 2,
 705        indent: int = 2,
 706        normalize_functions: t.Optional[str | bool] = None,
 707        unsupported_level: ErrorLevel = ErrorLevel.WARN,
 708        max_unsupported: int = 3,
 709        leading_comma: bool = False,
 710        max_text_width: int = 80,
 711        comments: bool = True,
 712        dialect: DialectType = None,
 713    ):
 714        import sqlglot
 715        from sqlglot.dialects import Dialect
 716
 717        self.pretty = pretty if pretty is not None else sqlglot.pretty
 718        self.identify = identify
 719        self.normalize = normalize
 720        self.pad = pad
 721        self._indent = indent
 722        self.unsupported_level = unsupported_level
 723        self.max_unsupported = max_unsupported
 724        self.leading_comma = leading_comma
 725        self.max_text_width = max_text_width
 726        self.comments = comments
 727        self.dialect = Dialect.get_or_raise(dialect)
 728
 729        # This is both a Dialect property and a Generator argument, so we prioritize the latter
 730        self.normalize_functions = (
 731            self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions
 732        )
 733
 734        self.unsupported_messages: t.List[str] = []
 735        self._escaped_quote_end: str = (
 736            self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END
 737        )
 738        self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2
 739
 740        self._next_name = name_sequence("_t")
 741
 742        self._identifier_start = self.dialect.IDENTIFIER_START
 743        self._identifier_end = self.dialect.IDENTIFIER_END
 744
 745        self._quote_json_path_key_using_brackets = True
 746
 747    def generate(self, expression: exp.Expression, copy: bool = True) -> str:
 748        """
 749        Generates the SQL string corresponding to the given syntax tree.
 750
 751        Args:
 752            expression: The syntax tree.
 753            copy: Whether to copy the expression. The generator performs mutations so
 754                it is safer to copy.
 755
 756        Returns:
 757            The SQL string corresponding to `expression`.
 758        """
 759        if copy:
 760            expression = expression.copy()
 761
 762        expression = self.preprocess(expression)
 763
 764        self.unsupported_messages = []
 765        sql = self.sql(expression).strip()
 766
 767        if self.pretty:
 768            sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n")
 769
 770        if self.unsupported_level == ErrorLevel.IGNORE:
 771            return sql
 772
 773        if self.unsupported_level == ErrorLevel.WARN:
 774            for msg in self.unsupported_messages:
 775                logger.warning(msg)
 776        elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages:
 777            raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported))
 778
 779        return sql
 780
 781    def preprocess(self, expression: exp.Expression) -> exp.Expression:
 782        """Apply generic preprocessing transformations to a given expression."""
 783        expression = self._move_ctes_to_top_level(expression)
 784
 785        if self.ENSURE_BOOLS:
 786            from sqlglot.transforms import ensure_bools
 787
 788            expression = ensure_bools(expression)
 789
 790        return expression
 791
 792    def _move_ctes_to_top_level(self, expression: E) -> E:
 793        if (
 794            not expression.parent
 795            and type(expression) in self.EXPRESSIONS_WITHOUT_NESTED_CTES
 796            and any(node.parent is not expression for node in expression.find_all(exp.With))
 797        ):
 798            from sqlglot.transforms import move_ctes_to_top_level
 799
 800            expression = move_ctes_to_top_level(expression)
 801        return expression
 802
 803    def unsupported(self, message: str) -> None:
 804        if self.unsupported_level == ErrorLevel.IMMEDIATE:
 805            raise UnsupportedError(message)
 806        self.unsupported_messages.append(message)
 807
 808    def sep(self, sep: str = " ") -> str:
 809        return f"{sep.strip()}\n" if self.pretty else sep
 810
 811    def seg(self, sql: str, sep: str = " ") -> str:
 812        return f"{self.sep(sep)}{sql}"
 813
 814    def sanitize_comment(self, comment: str) -> str:
 815        comment = " " + comment if comment[0].strip() else comment
 816        comment = comment + " " if comment[-1].strip() else comment
 817
 818        if not self.dialect.tokenizer_class.NESTED_COMMENTS:
 819            # Necessary workaround to avoid syntax errors due to nesting: /* ... */ ... */
 820            comment = comment.replace("*/", "* /")
 821
 822        return comment
 823
 824    def maybe_comment(
 825        self,
 826        sql: str,
 827        expression: t.Optional[exp.Expression] = None,
 828        comments: t.Optional[t.List[str]] = None,
 829        separated: bool = False,
 830    ) -> str:
 831        comments = (
 832            ((expression and expression.comments) if comments is None else comments)  # type: ignore
 833            if self.comments
 834            else None
 835        )
 836
 837        if not comments or isinstance(expression, self.EXCLUDE_COMMENTS):
 838            return sql
 839
 840        comments_sql = " ".join(
 841            f"/*{self.sanitize_comment(comment)}*/" for comment in comments if comment
 842        )
 843
 844        if not comments_sql:
 845            return sql
 846
 847        comments_sql = self._replace_line_breaks(comments_sql)
 848
 849        if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS):
 850            return (
 851                f"{self.sep()}{comments_sql}{sql}"
 852                if not sql or sql[0].isspace()
 853                else f"{comments_sql}{self.sep()}{sql}"
 854            )
 855
 856        return f"{sql} {comments_sql}"
 857
 858    def wrap(self, expression: exp.Expression | str) -> str:
 859        this_sql = (
 860            self.sql(expression)
 861            if isinstance(expression, exp.UNWRAPPED_QUERIES)
 862            else self.sql(expression, "this")
 863        )
 864        if not this_sql:
 865            return "()"
 866
 867        this_sql = self.indent(this_sql, level=1, pad=0)
 868        return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"
 869
 870    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
 871        original = self.identify
 872        self.identify = False
 873        result = func(*args, **kwargs)
 874        self.identify = original
 875        return result
 876
 877    def normalize_func(self, name: str) -> str:
 878        if self.normalize_functions == "upper" or self.normalize_functions is True:
 879            return name.upper()
 880        if self.normalize_functions == "lower":
 881            return name.lower()
 882        return name
 883
 884    def indent(
 885        self,
 886        sql: str,
 887        level: int = 0,
 888        pad: t.Optional[int] = None,
 889        skip_first: bool = False,
 890        skip_last: bool = False,
 891    ) -> str:
 892        if not self.pretty or not sql:
 893            return sql
 894
 895        pad = self.pad if pad is None else pad
 896        lines = sql.split("\n")
 897
 898        return "\n".join(
 899            (
 900                line
 901                if (skip_first and i == 0) or (skip_last and i == len(lines) - 1)
 902                else f"{' ' * (level * self._indent + pad)}{line}"
 903            )
 904            for i, line in enumerate(lines)
 905        )
 906
 907    def sql(
 908        self,
 909        expression: t.Optional[str | exp.Expression],
 910        key: t.Optional[str] = None,
 911        comment: bool = True,
 912    ) -> str:
 913        if not expression:
 914            return ""
 915
 916        if isinstance(expression, str):
 917            return expression
 918
 919        if key:
 920            value = expression.args.get(key)
 921            if value:
 922                return self.sql(value)
 923            return ""
 924
 925        transform = self.TRANSFORMS.get(expression.__class__)
 926
 927        if callable(transform):
 928            sql = transform(self, expression)
 929        elif isinstance(expression, exp.Expression):
 930            exp_handler_name = f"{expression.key}_sql"
 931
 932            if hasattr(self, exp_handler_name):
 933                sql = getattr(self, exp_handler_name)(expression)
 934            elif isinstance(expression, exp.Func):
 935                sql = self.function_fallback_sql(expression)
 936            elif isinstance(expression, exp.Property):
 937                sql = self.property_sql(expression)
 938            else:
 939                raise ValueError(f"Unsupported expression type {expression.__class__.__name__}")
 940        else:
 941            raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}")
 942
 943        return self.maybe_comment(sql, expression) if self.comments and comment else sql
 944
 945    def uncache_sql(self, expression: exp.Uncache) -> str:
 946        table = self.sql(expression, "this")
 947        exists_sql = " IF EXISTS" if expression.args.get("exists") else ""
 948        return f"UNCACHE TABLE{exists_sql} {table}"
 949
 950    def cache_sql(self, expression: exp.Cache) -> str:
 951        lazy = " LAZY" if expression.args.get("lazy") else ""
 952        table = self.sql(expression, "this")
 953        options = expression.args.get("options")
 954        options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else ""
 955        sql = self.sql(expression, "expression")
 956        sql = f" AS{self.sep()}{sql}" if sql else ""
 957        sql = f"CACHE{lazy} TABLE {table}{options}{sql}"
 958        return self.prepend_ctes(expression, sql)
 959
 960    def characterset_sql(self, expression: exp.CharacterSet) -> str:
 961        if isinstance(expression.parent, exp.Cast):
 962            return f"CHAR CHARACTER SET {self.sql(expression, 'this')}"
 963        default = "DEFAULT " if expression.args.get("default") else ""
 964        return f"{default}CHARACTER SET={self.sql(expression, 'this')}"
 965
 966    def column_parts(self, expression: exp.Column) -> str:
 967        return ".".join(
 968            self.sql(part)
 969            for part in (
 970                expression.args.get("catalog"),
 971                expression.args.get("db"),
 972                expression.args.get("table"),
 973                expression.args.get("this"),
 974            )
 975            if part
 976        )
 977
 978    def column_sql(self, expression: exp.Column) -> str:
 979        join_mark = " (+)" if expression.args.get("join_mark") else ""
 980
 981        if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS:
 982            join_mark = ""
 983            self.unsupported("Outer join syntax using the (+) operator is not supported.")
 984
 985        return f"{self.column_parts(expression)}{join_mark}"
 986
 987    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
 988        this = self.sql(expression, "this")
 989        this = f" {this}" if this else ""
 990        position = self.sql(expression, "position")
 991        return f"{position}{this}"
 992
 993    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
 994        column = self.sql(expression, "this")
 995        kind = self.sql(expression, "kind")
 996        constraints = self.expressions(expression, key="constraints", sep=" ", flat=True)
 997        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
 998        kind = f"{sep}{kind}" if kind else ""
 999        constraints = f" {constraints}" if constraints else ""
1000        position = self.sql(expression, "position")
1001        position = f" {position}" if position else ""
1002
1003        if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE:
1004            kind = ""
1005
1006        return f"{exists}{column}{kind}{constraints}{position}"
1007
1008    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
1009        this = self.sql(expression, "this")
1010        kind_sql = self.sql(expression, "kind").strip()
1011        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql
1012
1013    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
1014        this = self.sql(expression, "this")
1015        if expression.args.get("not_null"):
1016            persisted = " PERSISTED NOT NULL"
1017        elif expression.args.get("persisted"):
1018            persisted = " PERSISTED"
1019        else:
1020            persisted = ""
1021
1022        return f"AS {this}{persisted}"
1023
1024    def autoincrementcolumnconstraint_sql(self, _) -> str:
1025        return self.token_sql(TokenType.AUTO_INCREMENT)
1026
1027    def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str:
1028        if isinstance(expression.this, list):
1029            this = self.wrap(self.expressions(expression, key="this", flat=True))
1030        else:
1031            this = self.sql(expression, "this")
1032
1033        return f"COMPRESS {this}"
1034
1035    def generatedasidentitycolumnconstraint_sql(
1036        self, expression: exp.GeneratedAsIdentityColumnConstraint
1037    ) -> str:
1038        this = ""
1039        if expression.this is not None:
1040            on_null = " ON NULL" if expression.args.get("on_null") else ""
1041            this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}"
1042
1043        start = expression.args.get("start")
1044        start = f"START WITH {start}" if start else ""
1045        increment = expression.args.get("increment")
1046        increment = f" INCREMENT BY {increment}" if increment else ""
1047        minvalue = expression.args.get("minvalue")
1048        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
1049        maxvalue = expression.args.get("maxvalue")
1050        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
1051        cycle = expression.args.get("cycle")
1052        cycle_sql = ""
1053
1054        if cycle is not None:
1055            cycle_sql = f"{' NO' if not cycle else ''} CYCLE"
1056            cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql
1057
1058        sequence_opts = ""
1059        if start or increment or cycle_sql:
1060            sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}"
1061            sequence_opts = f" ({sequence_opts.strip()})"
1062
1063        expr = self.sql(expression, "expression")
1064        expr = f"({expr})" if expr else "IDENTITY"
1065
1066        return f"GENERATED{this} AS {expr}{sequence_opts}"
1067
1068    def generatedasrowcolumnconstraint_sql(
1069        self, expression: exp.GeneratedAsRowColumnConstraint
1070    ) -> str:
1071        start = "START" if expression.args.get("start") else "END"
1072        hidden = " HIDDEN" if expression.args.get("hidden") else ""
1073        return f"GENERATED ALWAYS AS ROW {start}{hidden}"
1074
1075    def periodforsystemtimeconstraint_sql(
1076        self, expression: exp.PeriodForSystemTimeConstraint
1077    ) -> str:
1078        return f"PERIOD FOR SYSTEM_TIME ({self.sql(expression, 'this')}, {self.sql(expression, 'expression')})"
1079
1080    def notnullcolumnconstraint_sql(self, expression: exp.NotNullColumnConstraint) -> str:
1081        return f"{'' if expression.args.get('allow_null') else 'NOT '}NULL"
1082
1083    def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str:
1084        desc = expression.args.get("desc")
1085        if desc is not None:
1086            return f"PRIMARY KEY{' DESC' if desc else ' ASC'}"
1087        options = self.expressions(expression, key="options", flat=True, sep=" ")
1088        options = f" {options}" if options else ""
1089        return f"PRIMARY KEY{options}"
1090
1091    def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str:
1092        this = self.sql(expression, "this")
1093        this = f" {this}" if this else ""
1094        index_type = expression.args.get("index_type")
1095        index_type = f" USING {index_type}" if index_type else ""
1096        on_conflict = self.sql(expression, "on_conflict")
1097        on_conflict = f" {on_conflict}" if on_conflict else ""
1098        nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else ""
1099        options = self.expressions(expression, key="options", flat=True, sep=" ")
1100        options = f" {options}" if options else ""
1101        return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}{options}"
1102
1103    def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
1104        return self.sql(expression, "this")
1105
1106    def create_sql(self, expression: exp.Create) -> str:
1107        kind = self.sql(expression, "kind")
1108        kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind
1109        properties = expression.args.get("properties")
1110        properties_locs = self.locate_properties(properties) if properties else defaultdict()
1111
1112        this = self.createable_sql(expression, properties_locs)
1113
1114        properties_sql = ""
1115        if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get(
1116            exp.Properties.Location.POST_WITH
1117        ):
1118            properties_sql = self.sql(
1119                exp.Properties(
1120                    expressions=[
1121                        *properties_locs[exp.Properties.Location.POST_SCHEMA],
1122                        *properties_locs[exp.Properties.Location.POST_WITH],
1123                    ]
1124                )
1125            )
1126
1127            if properties_locs.get(exp.Properties.Location.POST_SCHEMA):
1128                properties_sql = self.sep() + properties_sql
1129            elif not self.pretty:
1130                # Standalone POST_WITH properties need a leading whitespace in non-pretty mode
1131                properties_sql = f" {properties_sql}"
1132
1133        begin = " BEGIN" if expression.args.get("begin") else ""
1134        end = " END" if expression.args.get("end") else ""
1135
1136        expression_sql = self.sql(expression, "expression")
1137        if expression_sql:
1138            expression_sql = f"{begin}{self.sep()}{expression_sql}{end}"
1139
1140            if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return):
1141                postalias_props_sql = ""
1142                if properties_locs.get(exp.Properties.Location.POST_ALIAS):
1143                    postalias_props_sql = self.properties(
1144                        exp.Properties(
1145                            expressions=properties_locs[exp.Properties.Location.POST_ALIAS]
1146                        ),
1147                        wrapped=False,
1148                    )
1149                postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else ""
1150                expression_sql = f" AS{postalias_props_sql}{expression_sql}"
1151
1152        postindex_props_sql = ""
1153        if properties_locs.get(exp.Properties.Location.POST_INDEX):
1154            postindex_props_sql = self.properties(
1155                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]),
1156                wrapped=False,
1157                prefix=" ",
1158            )
1159
1160        indexes = self.expressions(expression, key="indexes", indent=False, sep=" ")
1161        indexes = f" {indexes}" if indexes else ""
1162        index_sql = indexes + postindex_props_sql
1163
1164        replace = " OR REPLACE" if expression.args.get("replace") else ""
1165        refresh = " OR REFRESH" if expression.args.get("refresh") else ""
1166        unique = " UNIQUE" if expression.args.get("unique") else ""
1167
1168        clustered = expression.args.get("clustered")
1169        if clustered is None:
1170            clustered_sql = ""
1171        elif clustered:
1172            clustered_sql = " CLUSTERED COLUMNSTORE"
1173        else:
1174            clustered_sql = " NONCLUSTERED COLUMNSTORE"
1175
1176        postcreate_props_sql = ""
1177        if properties_locs.get(exp.Properties.Location.POST_CREATE):
1178            postcreate_props_sql = self.properties(
1179                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]),
1180                sep=" ",
1181                prefix=" ",
1182                wrapped=False,
1183            )
1184
1185        modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql))
1186
1187        postexpression_props_sql = ""
1188        if properties_locs.get(exp.Properties.Location.POST_EXPRESSION):
1189            postexpression_props_sql = self.properties(
1190                exp.Properties(
1191                    expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION]
1192                ),
1193                sep=" ",
1194                prefix=" ",
1195                wrapped=False,
1196            )
1197
1198        concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else ""
1199        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
1200        no_schema_binding = (
1201            " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else ""
1202        )
1203
1204        clone = self.sql(expression, "clone")
1205        clone = f" {clone}" if clone else ""
1206
1207        if kind in self.EXPRESSION_PRECEDES_PROPERTIES_CREATABLES:
1208            properties_expression = f"{expression_sql}{properties_sql}"
1209        else:
1210            properties_expression = f"{properties_sql}{expression_sql}"
1211
1212        expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_expression}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}"
1213        return self.prepend_ctes(expression, expression_sql)
1214
1215    def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str:
1216        start = self.sql(expression, "start")
1217        start = f"START WITH {start}" if start else ""
1218        increment = self.sql(expression, "increment")
1219        increment = f" INCREMENT BY {increment}" if increment else ""
1220        minvalue = self.sql(expression, "minvalue")
1221        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
1222        maxvalue = self.sql(expression, "maxvalue")
1223        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
1224        owned = self.sql(expression, "owned")
1225        owned = f" OWNED BY {owned}" if owned else ""
1226
1227        cache = expression.args.get("cache")
1228        if cache is None:
1229            cache_str = ""
1230        elif cache is True:
1231            cache_str = " CACHE"
1232        else:
1233            cache_str = f" CACHE {cache}"
1234
1235        options = self.expressions(expression, key="options", flat=True, sep=" ")
1236        options = f" {options}" if options else ""
1237
1238        return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip()
1239
1240    def clone_sql(self, expression: exp.Clone) -> str:
1241        this = self.sql(expression, "this")
1242        shallow = "SHALLOW " if expression.args.get("shallow") else ""
1243        keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE"
1244        return f"{shallow}{keyword} {this}"
1245
1246    def describe_sql(self, expression: exp.Describe) -> str:
1247        style = expression.args.get("style")
1248        style = f" {style}" if style else ""
1249        partition = self.sql(expression, "partition")
1250        partition = f" {partition}" if partition else ""
1251        format = self.sql(expression, "format")
1252        format = f" {format}" if format else ""
1253
1254        return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}"
1255
1256    def heredoc_sql(self, expression: exp.Heredoc) -> str:
1257        tag = self.sql(expression, "tag")
1258        return f"${tag}${self.sql(expression, 'this')}${tag}$"
1259
1260    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
1261        with_ = self.sql(expression, "with")
1262        if with_:
1263            sql = f"{with_}{self.sep()}{sql}"
1264        return sql
1265
1266    def with_sql(self, expression: exp.With) -> str:
1267        sql = self.expressions(expression, flat=True)
1268        recursive = (
1269            "RECURSIVE "
1270            if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive")
1271            else ""
1272        )
1273        search = self.sql(expression, "search")
1274        search = f" {search}" if search else ""
1275
1276        return f"WITH {recursive}{sql}{search}"
1277
1278    def cte_sql(self, expression: exp.CTE) -> str:
1279        alias = expression.args.get("alias")
1280        if alias:
1281            alias.add_comments(expression.pop_comments())
1282
1283        alias_sql = self.sql(expression, "alias")
1284
1285        materialized = expression.args.get("materialized")
1286        if materialized is False:
1287            materialized = "NOT MATERIALIZED "
1288        elif materialized:
1289            materialized = "MATERIALIZED "
1290
1291        return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}"
1292
1293    def tablealias_sql(self, expression: exp.TableAlias) -> str:
1294        alias = self.sql(expression, "this")
1295        columns = self.expressions(expression, key="columns", flat=True)
1296        columns = f"({columns})" if columns else ""
1297
1298        if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS:
1299            columns = ""
1300            self.unsupported("Named columns are not supported in table alias.")
1301
1302        if not alias and not self.dialect.UNNEST_COLUMN_ONLY:
1303            alias = self._next_name()
1304
1305        return f"{alias}{columns}"
1306
1307    def bitstring_sql(self, expression: exp.BitString) -> str:
1308        this = self.sql(expression, "this")
1309        if self.dialect.BIT_START:
1310            return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}"
1311        return f"{int(this, 2)}"
1312
1313    def hexstring_sql(
1314        self, expression: exp.HexString, binary_function_repr: t.Optional[str] = None
1315    ) -> str:
1316        this = self.sql(expression, "this")
1317        is_integer_type = expression.args.get("is_integer")
1318
1319        if (is_integer_type and not self.dialect.HEX_STRING_IS_INTEGER_TYPE) or (
1320            not self.dialect.HEX_START and not binary_function_repr
1321        ):
1322            # Integer representation will be returned if:
1323            # - The read dialect treats the hex value as integer literal but not the write
1324            # - The transpilation is not supported (write dialect hasn't set HEX_START or the param flag)
1325            return f"{int(this, 16)}"
1326
1327        if not is_integer_type:
1328            # Read dialect treats the hex value as BINARY/BLOB
1329            if binary_function_repr:
1330                # The write dialect supports the transpilation to its equivalent BINARY/BLOB
1331                return self.func(binary_function_repr, exp.Literal.string(this))
1332            if self.dialect.HEX_STRING_IS_INTEGER_TYPE:
1333                # The write dialect does not support the transpilation, it'll treat the hex value as INTEGER
1334                self.unsupported("Unsupported transpilation from BINARY/BLOB hex string")
1335
1336        return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"
1337
1338    def bytestring_sql(self, expression: exp.ByteString) -> str:
1339        this = self.sql(expression, "this")
1340        if self.dialect.BYTE_START:
1341            return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}"
1342        return this
1343
1344    def unicodestring_sql(self, expression: exp.UnicodeString) -> str:
1345        this = self.sql(expression, "this")
1346        escape = expression.args.get("escape")
1347
1348        if self.dialect.UNICODE_START:
1349            escape_substitute = r"\\\1"
1350            left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END
1351        else:
1352            escape_substitute = r"\\u\1"
1353            left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END
1354
1355        if escape:
1356            escape_pattern = re.compile(rf"{escape.name}(\d+)")
1357            escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else ""
1358        else:
1359            escape_pattern = ESCAPED_UNICODE_RE
1360            escape_sql = ""
1361
1362        if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE):
1363            this = escape_pattern.sub(escape_substitute, this)
1364
1365        return f"{left_quote}{this}{right_quote}{escape_sql}"
1366
1367    def rawstring_sql(self, expression: exp.RawString) -> str:
1368        string = expression.this
1369        if "\\" in self.dialect.tokenizer_class.STRING_ESCAPES:
1370            string = string.replace("\\", "\\\\")
1371
1372        string = self.escape_str(string, escape_backslash=False)
1373        return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}"
1374
1375    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
1376        this = self.sql(expression, "this")
1377        specifier = self.sql(expression, "expression")
1378        specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else ""
1379        return f"{this}{specifier}"
1380
1381    def datatype_sql(self, expression: exp.DataType) -> str:
1382        nested = ""
1383        values = ""
1384        interior = self.expressions(expression, flat=True)
1385
1386        type_value = expression.this
1387        if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"):
1388            type_sql = self.sql(expression, "kind")
1389        else:
1390            type_sql = (
1391                self.TYPE_MAPPING.get(type_value, type_value.value)
1392                if isinstance(type_value, exp.DataType.Type)
1393                else type_value
1394            )
1395
1396        if interior:
1397            if expression.args.get("nested"):
1398                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
1399                if expression.args.get("values") is not None:
1400                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
1401                    values = self.expressions(expression, key="values", flat=True)
1402                    values = f"{delimiters[0]}{values}{delimiters[1]}"
1403            elif type_value == exp.DataType.Type.INTERVAL:
1404                nested = f" {interior}"
1405            else:
1406                nested = f"({interior})"
1407
1408        type_sql = f"{type_sql}{nested}{values}"
1409        if self.TZ_TO_WITH_TIME_ZONE and type_value in (
1410            exp.DataType.Type.TIMETZ,
1411            exp.DataType.Type.TIMESTAMPTZ,
1412        ):
1413            type_sql = f"{type_sql} WITH TIME ZONE"
1414
1415        return type_sql
1416
1417    def directory_sql(self, expression: exp.Directory) -> str:
1418        local = "LOCAL " if expression.args.get("local") else ""
1419        row_format = self.sql(expression, "row_format")
1420        row_format = f" {row_format}" if row_format else ""
1421        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"
1422
1423    def delete_sql(self, expression: exp.Delete) -> str:
1424        this = self.sql(expression, "this")
1425        this = f" FROM {this}" if this else ""
1426        using = self.sql(expression, "using")
1427        using = f" USING {using}" if using else ""
1428        cluster = self.sql(expression, "cluster")
1429        cluster = f" {cluster}" if cluster else ""
1430        where = self.sql(expression, "where")
1431        returning = self.sql(expression, "returning")
1432        limit = self.sql(expression, "limit")
1433        tables = self.expressions(expression, key="tables")
1434        tables = f" {tables}" if tables else ""
1435        if self.RETURNING_END:
1436            expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}"
1437        else:
1438            expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}"
1439        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")
1440
1441    def drop_sql(self, expression: exp.Drop) -> str:
1442        this = self.sql(expression, "this")
1443        expressions = self.expressions(expression, flat=True)
1444        expressions = f" ({expressions})" if expressions else ""
1445        kind = expression.args["kind"]
1446        kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind
1447        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
1448        concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else ""
1449        on_cluster = self.sql(expression, "cluster")
1450        on_cluster = f" {on_cluster}" if on_cluster else ""
1451        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
1452        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
1453        cascade = " CASCADE" if expression.args.get("cascade") else ""
1454        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
1455        purge = " PURGE" if expression.args.get("purge") else ""
1456        return f"DROP{temporary}{materialized} {kind}{concurrently_sql}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}"
1457
1458    def set_operation(self, expression: exp.SetOperation) -> str:
1459        op_type = type(expression)
1460        op_name = op_type.key.upper()
1461
1462        distinct = expression.args.get("distinct")
1463        if (
1464            distinct is False
1465            and op_type in (exp.Except, exp.Intersect)
1466            and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE
1467        ):
1468            self.unsupported(f"{op_name} ALL is not supported")
1469
1470        default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type]
1471
1472        if distinct is None:
1473            distinct = default_distinct
1474            if distinct is None:
1475                self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified")
1476
1477        if distinct is default_distinct:
1478            distinct_or_all = ""
1479        else:
1480            distinct_or_all = " DISTINCT" if distinct else " ALL"
1481
1482        side_kind = " ".join(filter(None, [expression.side, expression.kind]))
1483        side_kind = f"{side_kind} " if side_kind else ""
1484
1485        by_name = " BY NAME" if expression.args.get("by_name") else ""
1486        on = self.expressions(expression, key="on", flat=True)
1487        on = f" ON ({on})" if on else ""
1488
1489        return f"{side_kind}{op_name}{distinct_or_all}{by_name}{on}"
1490
1491    def set_operations(self, expression: exp.SetOperation) -> str:
1492        if not self.SET_OP_MODIFIERS:
1493            limit = expression.args.get("limit")
1494            order = expression.args.get("order")
1495
1496            if limit or order:
1497                select = self._move_ctes_to_top_level(
1498                    exp.subquery(expression, "_l_0", copy=False).select("*", copy=False)
1499                )
1500
1501                if limit:
1502                    select = select.limit(limit.pop(), copy=False)
1503                if order:
1504                    select = select.order_by(order.pop(), copy=False)
1505                return self.sql(select)
1506
1507        sqls: t.List[str] = []
1508        stack: t.List[t.Union[str, exp.Expression]] = [expression]
1509
1510        while stack:
1511            node = stack.pop()
1512
1513            if isinstance(node, exp.SetOperation):
1514                stack.append(node.expression)
1515                stack.append(
1516                    self.maybe_comment(
1517                        self.set_operation(node), comments=node.comments, separated=True
1518                    )
1519                )
1520                stack.append(node.this)
1521            else:
1522                sqls.append(self.sql(node))
1523
1524        this = self.sep().join(sqls)
1525        this = self.query_modifiers(expression, this)
1526        return self.prepend_ctes(expression, this)
1527
1528    def fetch_sql(self, expression: exp.Fetch) -> str:
1529        direction = expression.args.get("direction")
1530        direction = f" {direction}" if direction else ""
1531        count = self.sql(expression, "count")
1532        count = f" {count}" if count else ""
1533        limit_options = self.sql(expression, "limit_options")
1534        limit_options = f"{limit_options}" if limit_options else " ROWS ONLY"
1535        return f"{self.seg('FETCH')}{direction}{count}{limit_options}"
1536
1537    def limitoptions_sql(self, expression: exp.LimitOptions) -> str:
1538        percent = " PERCENT" if expression.args.get("percent") else ""
1539        rows = " ROWS" if expression.args.get("rows") else ""
1540        with_ties = " WITH TIES" if expression.args.get("with_ties") else ""
1541        if not with_ties and rows:
1542            with_ties = " ONLY"
1543        return f"{percent}{rows}{with_ties}"
1544
1545    def filter_sql(self, expression: exp.Filter) -> str:
1546        if self.AGGREGATE_FILTER_SUPPORTED:
1547            this = self.sql(expression, "this")
1548            where = self.sql(expression, "expression").strip()
1549            return f"{this} FILTER({where})"
1550
1551        agg = expression.this
1552        agg_arg = agg.this
1553        cond = expression.expression.this
1554        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
1555        return self.sql(agg)
1556
1557    def hint_sql(self, expression: exp.Hint) -> str:
1558        if not self.QUERY_HINTS:
1559            self.unsupported("Hints are not supported")
1560            return ""
1561
1562        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"
1563
1564    def indexparameters_sql(self, expression: exp.IndexParameters) -> str:
1565        using = self.sql(expression, "using")
1566        using = f" USING {using}" if using else ""
1567        columns = self.expressions(expression, key="columns", flat=True)
1568        columns = f"({columns})" if columns else ""
1569        partition_by = self.expressions(expression, key="partition_by", flat=True)
1570        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
1571        where = self.sql(expression, "where")
1572        include = self.expressions(expression, key="include", flat=True)
1573        if include:
1574            include = f" INCLUDE ({include})"
1575        with_storage = self.expressions(expression, key="with_storage", flat=True)
1576        with_storage = f" WITH ({with_storage})" if with_storage else ""
1577        tablespace = self.sql(expression, "tablespace")
1578        tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else ""
1579        on = self.sql(expression, "on")
1580        on = f" ON {on}" if on else ""
1581
1582        return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"
1583
1584    def index_sql(self, expression: exp.Index) -> str:
1585        unique = "UNIQUE " if expression.args.get("unique") else ""
1586        primary = "PRIMARY " if expression.args.get("primary") else ""
1587        amp = "AMP " if expression.args.get("amp") else ""
1588        name = self.sql(expression, "this")
1589        name = f"{name} " if name else ""
1590        table = self.sql(expression, "table")
1591        table = f"{self.INDEX_ON} {table}" if table else ""
1592
1593        index = "INDEX " if not table else ""
1594
1595        params = self.sql(expression, "params")
1596        return f"{unique}{primary}{amp}{index}{name}{table}{params}"
1597
1598    def identifier_sql(self, expression: exp.Identifier) -> str:
1599        text = expression.name
1600        lower = text.lower()
1601        text = lower if self.normalize and not expression.quoted else text
1602        text = text.replace(self._identifier_end, self._escaped_identifier_end)
1603        if (
1604            expression.quoted
1605            or self.dialect.can_identify(text, self.identify)
1606            or lower in self.RESERVED_KEYWORDS
1607            or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
1608        ):
1609            text = f"{self._identifier_start}{text}{self._identifier_end}"
1610        return text
1611
1612    def hex_sql(self, expression: exp.Hex) -> str:
1613        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
1614        if self.dialect.HEX_LOWERCASE:
1615            text = self.func("LOWER", text)
1616
1617        return text
1618
1619    def lowerhex_sql(self, expression: exp.LowerHex) -> str:
1620        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
1621        if not self.dialect.HEX_LOWERCASE:
1622            text = self.func("LOWER", text)
1623        return text
1624
1625    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
1626        input_format = self.sql(expression, "input_format")
1627        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
1628        output_format = self.sql(expression, "output_format")
1629        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
1630        return self.sep().join((input_format, output_format))
1631
1632    def national_sql(self, expression: exp.National, prefix: str = "N") -> str:
1633        string = self.sql(exp.Literal.string(expression.name))
1634        return f"{prefix}{string}"
1635
1636    def partition_sql(self, expression: exp.Partition) -> str:
1637        partition_keyword = "SUBPARTITION" if expression.args.get("subpartition") else "PARTITION"
1638        return f"{partition_keyword}({self.expressions(expression, flat=True)})"
1639
1640    def properties_sql(self, expression: exp.Properties) -> str:
1641        root_properties = []
1642        with_properties = []
1643
1644        for p in expression.expressions:
1645            p_loc = self.PROPERTIES_LOCATION[p.__class__]
1646            if p_loc == exp.Properties.Location.POST_WITH:
1647                with_properties.append(p)
1648            elif p_loc == exp.Properties.Location.POST_SCHEMA:
1649                root_properties.append(p)
1650
1651        root_props = self.root_properties(exp.Properties(expressions=root_properties))
1652        with_props = self.with_properties(exp.Properties(expressions=with_properties))
1653
1654        if root_props and with_props and not self.pretty:
1655            with_props = " " + with_props
1656
1657        return root_props + with_props
1658
1659    def root_properties(self, properties: exp.Properties) -> str:
1660        if properties.expressions:
1661            return self.expressions(properties, indent=False, sep=" ")
1662        return ""
1663
1664    def properties(
1665        self,
1666        properties: exp.Properties,
1667        prefix: str = "",
1668        sep: str = ", ",
1669        suffix: str = "",
1670        wrapped: bool = True,
1671    ) -> str:
1672        if properties.expressions:
1673            expressions = self.expressions(properties, sep=sep, indent=False)
1674            if expressions:
1675                expressions = self.wrap(expressions) if wrapped else expressions
1676                return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}"
1677        return ""
1678
1679    def with_properties(self, properties: exp.Properties) -> str:
1680        return self.properties(properties, prefix=self.seg(self.WITH_PROPERTIES_PREFIX, sep=""))
1681
1682    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
1683        properties_locs = defaultdict(list)
1684        for p in properties.expressions:
1685            p_loc = self.PROPERTIES_LOCATION[p.__class__]
1686            if p_loc != exp.Properties.Location.UNSUPPORTED:
1687                properties_locs[p_loc].append(p)
1688            else:
1689                self.unsupported(f"Unsupported property {p.key}")
1690
1691        return properties_locs
1692
1693    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
1694        if isinstance(expression.this, exp.Dot):
1695            return self.sql(expression, "this")
1696        return f"'{expression.name}'" if string_key else expression.name
1697
1698    def property_sql(self, expression: exp.Property) -> str:
1699        property_cls = expression.__class__
1700        if property_cls == exp.Property:
1701            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
1702
1703        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
1704        if not property_name:
1705            self.unsupported(f"Unsupported property {expression.key}")
1706
1707        return f"{property_name}={self.sql(expression, 'this')}"
1708
1709    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
1710        if self.SUPPORTS_CREATE_TABLE_LIKE:
1711            options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
1712            options = f" {options}" if options else ""
1713
1714            like = f"LIKE {self.sql(expression, 'this')}{options}"
1715            if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema):
1716                like = f"({like})"
1717
1718            return like
1719
1720        if expression.expressions:
1721            self.unsupported("Transpilation of LIKE property options is unsupported")
1722
1723        select = exp.select("*").from_(expression.this).limit(0)
1724        return f"AS {self.sql(select)}"
1725
1726    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
1727        no = "NO " if expression.args.get("no") else ""
1728        protection = " PROTECTION" if expression.args.get("protection") else ""
1729        return f"{no}FALLBACK{protection}"
1730
1731    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
1732        no = "NO " if expression.args.get("no") else ""
1733        local = expression.args.get("local")
1734        local = f"{local} " if local else ""
1735        dual = "DUAL " if expression.args.get("dual") else ""
1736        before = "BEFORE " if expression.args.get("before") else ""
1737        after = "AFTER " if expression.args.get("after") else ""
1738        return f"{no}{local}{dual}{before}{after}JOURNAL"
1739
1740    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
1741        freespace = self.sql(expression, "this")
1742        percent = " PERCENT" if expression.args.get("percent") else ""
1743        return f"FREESPACE={freespace}{percent}"
1744
1745    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
1746        if expression.args.get("default"):
1747            property = "DEFAULT"
1748        elif expression.args.get("on"):
1749            property = "ON"
1750        else:
1751            property = "OFF"
1752        return f"CHECKSUM={property}"
1753
1754    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
1755        if expression.args.get("no"):
1756            return "NO MERGEBLOCKRATIO"
1757        if expression.args.get("default"):
1758            return "DEFAULT MERGEBLOCKRATIO"
1759
1760        percent = " PERCENT" if expression.args.get("percent") else ""
1761        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"
1762
1763    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
1764        default = expression.args.get("default")
1765        minimum = expression.args.get("minimum")
1766        maximum = expression.args.get("maximum")
1767        if default or minimum or maximum:
1768            if default:
1769                prop = "DEFAULT"
1770            elif minimum:
1771                prop = "MINIMUM"
1772            else:
1773                prop = "MAXIMUM"
1774            return f"{prop} DATABLOCKSIZE"
1775        units = expression.args.get("units")
1776        units = f" {units}" if units else ""
1777        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"
1778
1779    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
1780        autotemp = expression.args.get("autotemp")
1781        always = expression.args.get("always")
1782        default = expression.args.get("default")
1783        manual = expression.args.get("manual")
1784        never = expression.args.get("never")
1785
1786        if autotemp is not None:
1787            prop = f"AUTOTEMP({self.expressions(autotemp)})"
1788        elif always:
1789            prop = "ALWAYS"
1790        elif default:
1791            prop = "DEFAULT"
1792        elif manual:
1793            prop = "MANUAL"
1794        elif never:
1795            prop = "NEVER"
1796        return f"BLOCKCOMPRESSION={prop}"
1797
1798    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
1799        no = expression.args.get("no")
1800        no = " NO" if no else ""
1801        concurrent = expression.args.get("concurrent")
1802        concurrent = " CONCURRENT" if concurrent else ""
1803        target = self.sql(expression, "target")
1804        target = f" {target}" if target else ""
1805        return f"WITH{no}{concurrent} ISOLATED LOADING{target}"
1806
1807    def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str:
1808        if isinstance(expression.this, list):
1809            return f"IN ({self.expressions(expression, key='this', flat=True)})"
1810        if expression.this:
1811            modulus = self.sql(expression, "this")
1812            remainder = self.sql(expression, "expression")
1813            return f"WITH (MODULUS {modulus}, REMAINDER {remainder})"
1814
1815        from_expressions = self.expressions(expression, key="from_expressions", flat=True)
1816        to_expressions = self.expressions(expression, key="to_expressions", flat=True)
1817        return f"FROM ({from_expressions}) TO ({to_expressions})"
1818
1819    def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str:
1820        this = self.sql(expression, "this")
1821
1822        for_values_or_default = expression.expression
1823        if isinstance(for_values_or_default, exp.PartitionBoundSpec):
1824            for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}"
1825        else:
1826            for_values_or_default = " DEFAULT"
1827
1828        return f"PARTITION OF {this}{for_values_or_default}"
1829
1830    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
1831        kind = expression.args.get("kind")
1832        this = f" {self.sql(expression, 'this')}" if expression.this else ""
1833        for_or_in = expression.args.get("for_or_in")
1834        for_or_in = f" {for_or_in}" if for_or_in else ""
1835        lock_type = expression.args.get("lock_type")
1836        override = " OVERRIDE" if expression.args.get("override") else ""
1837        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"
1838
1839    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
1840        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
1841        statistics = expression.args.get("statistics")
1842        statistics_sql = ""
1843        if statistics is not None:
1844            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
1845        return f"{data_sql}{statistics_sql}"
1846
1847    def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str:
1848        this = self.sql(expression, "this")
1849        this = f"HISTORY_TABLE={this}" if this else ""
1850        data_consistency: t.Optional[str] = self.sql(expression, "data_consistency")
1851        data_consistency = (
1852            f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None
1853        )
1854        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
1855        retention_period = (
1856            f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None
1857        )
1858
1859        if this:
1860            on_sql = self.func("ON", this, data_consistency, retention_period)
1861        else:
1862            on_sql = "ON" if expression.args.get("on") else "OFF"
1863
1864        sql = f"SYSTEM_VERSIONING={on_sql}"
1865
1866        return f"WITH({sql})" if expression.args.get("with") else sql
1867
1868    def insert_sql(self, expression: exp.Insert) -> str:
1869        hint = self.sql(expression, "hint")
1870        overwrite = expression.args.get("overwrite")
1871
1872        if isinstance(expression.this, exp.Directory):
1873            this = " OVERWRITE" if overwrite else " INTO"
1874        else:
1875            this = self.INSERT_OVERWRITE if overwrite else " INTO"
1876
1877        stored = self.sql(expression, "stored")
1878        stored = f" {stored}" if stored else ""
1879        alternative = expression.args.get("alternative")
1880        alternative = f" OR {alternative}" if alternative else ""
1881        ignore = " IGNORE" if expression.args.get("ignore") else ""
1882        is_function = expression.args.get("is_function")
1883        if is_function:
1884            this = f"{this} FUNCTION"
1885        this = f"{this} {self.sql(expression, 'this')}"
1886
1887        exists = " IF EXISTS" if expression.args.get("exists") else ""
1888        where = self.sql(expression, "where")
1889        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
1890        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
1891        on_conflict = self.sql(expression, "conflict")
1892        on_conflict = f" {on_conflict}" if on_conflict else ""
1893        by_name = " BY NAME" if expression.args.get("by_name") else ""
1894        returning = self.sql(expression, "returning")
1895
1896        if self.RETURNING_END:
1897            expression_sql = f"{expression_sql}{on_conflict}{returning}"
1898        else:
1899            expression_sql = f"{returning}{expression_sql}{on_conflict}"
1900
1901        partition_by = self.sql(expression, "partition")
1902        partition_by = f" {partition_by}" if partition_by else ""
1903        settings = self.sql(expression, "settings")
1904        settings = f" {settings}" if settings else ""
1905
1906        source = self.sql(expression, "source")
1907        source = f"TABLE {source}" if source else ""
1908
1909        sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}"
1910        return self.prepend_ctes(expression, sql)
1911
1912    def introducer_sql(self, expression: exp.Introducer) -> str:
1913        return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}"
1914
1915    def kill_sql(self, expression: exp.Kill) -> str:
1916        kind = self.sql(expression, "kind")
1917        kind = f" {kind}" if kind else ""
1918        this = self.sql(expression, "this")
1919        this = f" {this}" if this else ""
1920        return f"KILL{kind}{this}"
1921
1922    def pseudotype_sql(self, expression: exp.PseudoType) -> str:
1923        return expression.name
1924
1925    def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str:
1926        return expression.name
1927
1928    def onconflict_sql(self, expression: exp.OnConflict) -> str:
1929        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
1930
1931        constraint = self.sql(expression, "constraint")
1932        constraint = f" ON CONSTRAINT {constraint}" if constraint else ""
1933
1934        conflict_keys = self.expressions(expression, key="conflict_keys", flat=True)
1935        conflict_keys = f"({conflict_keys}) " if conflict_keys else " "
1936        action = self.sql(expression, "action")
1937
1938        expressions = self.expressions(expression, flat=True)
1939        if expressions:
1940            set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
1941            expressions = f" {set_keyword}{expressions}"
1942
1943        where = self.sql(expression, "where")
1944        return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}"
1945
1946    def returning_sql(self, expression: exp.Returning) -> str:
1947        return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}"
1948
1949    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
1950        fields = self.sql(expression, "fields")
1951        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
1952        escaped = self.sql(expression, "escaped")
1953        escaped = f" ESCAPED BY {escaped}" if escaped else ""
1954        items = self.sql(expression, "collection_items")
1955        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
1956        keys = self.sql(expression, "map_keys")
1957        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
1958        lines = self.sql(expression, "lines")
1959        lines = f" LINES TERMINATED BY {lines}" if lines else ""
1960        null = self.sql(expression, "null")
1961        null = f" NULL DEFINED AS {null}" if null else ""
1962        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"
1963
1964    def withtablehint_sql(self, expression: exp.WithTableHint) -> str:
1965        return f"WITH ({self.expressions(expression, flat=True)})"
1966
1967    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
1968        this = f"{self.sql(expression, 'this')} INDEX"
1969        target = self.sql(expression, "target")
1970        target = f" FOR {target}" if target else ""
1971        return f"{this}{target} ({self.expressions(expression, flat=True)})"
1972
1973    def historicaldata_sql(self, expression: exp.HistoricalData) -> str:
1974        this = self.sql(expression, "this")
1975        kind = self.sql(expression, "kind")
1976        expr = self.sql(expression, "expression")
1977        return f"{this} ({kind} => {expr})"
1978
1979    def table_parts(self, expression: exp.Table) -> str:
1980        return ".".join(
1981            self.sql(part)
1982            for part in (
1983                expression.args.get("catalog"),
1984                expression.args.get("db"),
1985                expression.args.get("this"),
1986            )
1987            if part is not None
1988        )
1989
1990    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
1991        table = self.table_parts(expression)
1992        only = "ONLY " if expression.args.get("only") else ""
1993        partition = self.sql(expression, "partition")
1994        partition = f" {partition}" if partition else ""
1995        version = self.sql(expression, "version")
1996        version = f" {version}" if version else ""
1997        alias = self.sql(expression, "alias")
1998        alias = f"{sep}{alias}" if alias else ""
1999
2000        sample = self.sql(expression, "sample")
2001        if self.dialect.ALIAS_POST_TABLESAMPLE:
2002            sample_pre_alias = sample
2003            sample_post_alias = ""
2004        else:
2005            sample_pre_alias = ""
2006            sample_post_alias = sample
2007
2008        hints = self.expressions(expression, key="hints", sep=" ")
2009        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
2010        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
2011        joins = self.indent(
2012            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
2013        )
2014        laterals = self.expressions(expression, key="laterals", sep="")
2015
2016        file_format = self.sql(expression, "format")
2017        if file_format:
2018            pattern = self.sql(expression, "pattern")
2019            pattern = f", PATTERN => {pattern}" if pattern else ""
2020            file_format = f" (FILE_FORMAT => {file_format}{pattern})"
2021
2022        ordinality = expression.args.get("ordinality") or ""
2023        if ordinality:
2024            ordinality = f" WITH ORDINALITY{alias}"
2025            alias = ""
2026
2027        when = self.sql(expression, "when")
2028        if when:
2029            table = f"{table} {when}"
2030
2031        changes = self.sql(expression, "changes")
2032        changes = f" {changes}" if changes else ""
2033
2034        rows_from = self.expressions(expression, key="rows_from")
2035        if rows_from:
2036            table = f"ROWS FROM {self.wrap(rows_from)}"
2037
2038        return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}"
2039
2040    def tablefromrows_sql(self, expression: exp.TableFromRows) -> str:
2041        table = self.func("TABLE", expression.this)
2042        alias = self.sql(expression, "alias")
2043        alias = f" AS {alias}" if alias else ""
2044        sample = self.sql(expression, "sample")
2045        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
2046        joins = self.indent(
2047            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
2048        )
2049        return f"{table}{alias}{pivots}{sample}{joins}"
2050
2051    def tablesample_sql(
2052        self,
2053        expression: exp.TableSample,
2054        tablesample_keyword: t.Optional[str] = None,
2055    ) -> str:
2056        method = self.sql(expression, "method")
2057        method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else ""
2058        numerator = self.sql(expression, "bucket_numerator")
2059        denominator = self.sql(expression, "bucket_denominator")
2060        field = self.sql(expression, "bucket_field")
2061        field = f" ON {field}" if field else ""
2062        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
2063        seed = self.sql(expression, "seed")
2064        seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else ""
2065
2066        size = self.sql(expression, "size")
2067        if size and self.TABLESAMPLE_SIZE_IS_ROWS:
2068            size = f"{size} ROWS"
2069
2070        percent = self.sql(expression, "percent")
2071        if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT:
2072            percent = f"{percent} PERCENT"
2073
2074        expr = f"{bucket}{percent}{size}"
2075        if self.TABLESAMPLE_REQUIRES_PARENS:
2076            expr = f"({expr})"
2077
2078        return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}"
2079
2080    def pivot_sql(self, expression: exp.Pivot) -> str:
2081        expressions = self.expressions(expression, flat=True)
2082        direction = "UNPIVOT" if expression.unpivot else "PIVOT"
2083
2084        group = self.sql(expression, "group")
2085
2086        if expression.this:
2087            this = self.sql(expression, "this")
2088            if not expressions:
2089                return f"UNPIVOT {this}"
2090
2091            on = f"{self.seg('ON')} {expressions}"
2092            into = self.sql(expression, "into")
2093            into = f"{self.seg('INTO')} {into}" if into else ""
2094            using = self.expressions(expression, key="using", flat=True)
2095            using = f"{self.seg('USING')} {using}" if using else ""
2096            return f"{direction} {this}{on}{into}{using}{group}"
2097
2098        alias = self.sql(expression, "alias")
2099        alias = f" AS {alias}" if alias else ""
2100
2101        fields = self.expressions(
2102            expression,
2103            "fields",
2104            sep=" ",
2105            dynamic=True,
2106            new_line=True,
2107            skip_first=True,
2108            skip_last=True,
2109        )
2110
2111        include_nulls = expression.args.get("include_nulls")
2112        if include_nulls is not None:
2113            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
2114        else:
2115            nulls = ""
2116
2117        default_on_null = self.sql(expression, "default_on_null")
2118        default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else ""
2119        return f"{self.seg(direction)}{nulls}({expressions} FOR {fields}{default_on_null}{group}){alias}"
2120
2121    def version_sql(self, expression: exp.Version) -> str:
2122        this = f"FOR {expression.name}"
2123        kind = expression.text("kind")
2124        expr = self.sql(expression, "expression")
2125        return f"{this} {kind} {expr}"
2126
2127    def tuple_sql(self, expression: exp.Tuple) -> str:
2128        return f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})"
2129
2130    def update_sql(self, expression: exp.Update) -> str:
2131        this = self.sql(expression, "this")
2132        set_sql = self.expressions(expression, flat=True)
2133        from_sql = self.sql(expression, "from")
2134        where_sql = self.sql(expression, "where")
2135        returning = self.sql(expression, "returning")
2136        order = self.sql(expression, "order")
2137        limit = self.sql(expression, "limit")
2138        if self.RETURNING_END:
2139            expression_sql = f"{from_sql}{where_sql}{returning}"
2140        else:
2141            expression_sql = f"{returning}{from_sql}{where_sql}"
2142        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
2143        return self.prepend_ctes(expression, sql)
2144
2145    def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str:
2146        values_as_table = values_as_table and self.VALUES_AS_TABLE
2147
2148        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
2149        if values_as_table or not expression.find_ancestor(exp.From, exp.Join):
2150            args = self.expressions(expression)
2151            alias = self.sql(expression, "alias")
2152            values = f"VALUES{self.seg('')}{args}"
2153            values = (
2154                f"({values})"
2155                if self.WRAP_DERIVED_VALUES
2156                and (alias or isinstance(expression.parent, (exp.From, exp.Table)))
2157                else values
2158            )
2159            return f"{values} AS {alias}" if alias else values
2160
2161        # Converts `VALUES...` expression into a series of select unions.
2162        alias_node = expression.args.get("alias")
2163        column_names = alias_node and alias_node.columns
2164
2165        selects: t.List[exp.Query] = []
2166
2167        for i, tup in enumerate(expression.expressions):
2168            row = tup.expressions
2169
2170            if i == 0 and column_names:
2171                row = [
2172                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
2173                ]
2174
2175            selects.append(exp.Select(expressions=row))
2176
2177        if self.pretty:
2178            # This may result in poor performance for large-cardinality `VALUES` tables, due to
2179            # the deep nesting of the resulting exp.Unions. If this is a problem, either increase
2180            # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`.
2181            query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects)
2182            return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False))
2183
2184        alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else ""
2185        unions = " UNION ALL ".join(self.sql(select) for select in selects)
2186        return f"({unions}){alias}"
2187
2188    def var_sql(self, expression: exp.Var) -> str:
2189        return self.sql(expression, "this")
2190
2191    @unsupported_args("expressions")
2192    def into_sql(self, expression: exp.Into) -> str:
2193        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
2194        unlogged = " UNLOGGED" if expression.args.get("unlogged") else ""
2195        return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"
2196
2197    def from_sql(self, expression: exp.From) -> str:
2198        return f"{self.seg('FROM')} {self.sql(expression, 'this')}"
2199
2200    def groupingsets_sql(self, expression: exp.GroupingSets) -> str:
2201        grouping_sets = self.expressions(expression, indent=False)
2202        return f"GROUPING SETS {self.wrap(grouping_sets)}"
2203
2204    def rollup_sql(self, expression: exp.Rollup) -> str:
2205        expressions = self.expressions(expression, indent=False)
2206        return f"ROLLUP {self.wrap(expressions)}" if expressions else "WITH ROLLUP"
2207
2208    def cube_sql(self, expression: exp.Cube) -> str:
2209        expressions = self.expressions(expression, indent=False)
2210        return f"CUBE {self.wrap(expressions)}" if expressions else "WITH CUBE"
2211
2212    def group_sql(self, expression: exp.Group) -> str:
2213        group_by_all = expression.args.get("all")
2214        if group_by_all is True:
2215            modifier = " ALL"
2216        elif group_by_all is False:
2217            modifier = " DISTINCT"
2218        else:
2219            modifier = ""
2220
2221        group_by = self.op_expressions(f"GROUP BY{modifier}", expression)
2222
2223        grouping_sets = self.expressions(expression, key="grouping_sets")
2224        cube = self.expressions(expression, key="cube")
2225        rollup = self.expressions(expression, key="rollup")
2226
2227        groupings = csv(
2228            self.seg(grouping_sets) if grouping_sets else "",
2229            self.seg(cube) if cube else "",
2230            self.seg(rollup) if rollup else "",
2231            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
2232            sep=self.GROUPINGS_SEP,
2233        )
2234
2235        if (
2236            expression.expressions
2237            and groupings
2238            and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP")
2239        ):
2240            group_by = f"{group_by}{self.GROUPINGS_SEP}"
2241
2242        return f"{group_by}{groupings}"
2243
2244    def having_sql(self, expression: exp.Having) -> str:
2245        this = self.indent(self.sql(expression, "this"))
2246        return f"{self.seg('HAVING')}{self.sep()}{this}"
2247
2248    def connect_sql(self, expression: exp.Connect) -> str:
2249        start = self.sql(expression, "start")
2250        start = self.seg(f"START WITH {start}") if start else ""
2251        nocycle = " NOCYCLE" if expression.args.get("nocycle") else ""
2252        connect = self.sql(expression, "connect")
2253        connect = self.seg(f"CONNECT BY{nocycle} {connect}")
2254        return start + connect
2255
2256    def prior_sql(self, expression: exp.Prior) -> str:
2257        return f"PRIOR {self.sql(expression, 'this')}"
2258
2259    def join_sql(self, expression: exp.Join) -> str:
2260        if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"):
2261            side = None
2262        else:
2263            side = expression.side
2264
2265        op_sql = " ".join(
2266            op
2267            for op in (
2268                expression.method,
2269                "GLOBAL" if expression.args.get("global") else None,
2270                side,
2271                expression.kind,
2272                expression.hint if self.JOIN_HINTS else None,
2273            )
2274            if op
2275        )
2276        match_cond = self.sql(expression, "match_condition")
2277        match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else ""
2278        on_sql = self.sql(expression, "on")
2279        using = expression.args.get("using")
2280
2281        if not on_sql and using:
2282            on_sql = csv(*(self.sql(column) for column in using))
2283
2284        this = expression.this
2285        this_sql = self.sql(this)
2286
2287        exprs = self.expressions(expression)
2288        if exprs:
2289            this_sql = f"{this_sql},{self.seg(exprs)}"
2290
2291        if on_sql:
2292            on_sql = self.indent(on_sql, skip_first=True)
2293            space = self.seg(" " * self.pad) if self.pretty else " "
2294            if using:
2295                on_sql = f"{space}USING ({on_sql})"
2296            else:
2297                on_sql = f"{space}ON {on_sql}"
2298        elif not op_sql:
2299            if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None:
2300                return f" {this_sql}"
2301
2302            return f", {this_sql}"
2303
2304        if op_sql != "STRAIGHT_JOIN":
2305            op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
2306
2307        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
2308        return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}{pivots}"
2309
2310    def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->") -> str:
2311        args = self.expressions(expression, flat=True)
2312        args = f"({args})" if len(args.split(",")) > 1 else args
2313        return f"{args} {arrow_sep} {self.sql(expression, 'this')}"
2314
2315    def lateral_op(self, expression: exp.Lateral) -> str:
2316        cross_apply = expression.args.get("cross_apply")
2317
2318        # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/
2319        if cross_apply is True:
2320            op = "INNER JOIN "
2321        elif cross_apply is False:
2322            op = "LEFT JOIN "
2323        else:
2324            op = ""
2325
2326        return f"{op}LATERAL"
2327
2328    def lateral_sql(self, expression: exp.Lateral) -> str:
2329        this = self.sql(expression, "this")
2330
2331        if expression.args.get("view"):
2332            alias = expression.args["alias"]
2333            columns = self.expressions(alias, key="columns", flat=True)
2334            table = f" {alias.name}" if alias.name else ""
2335            columns = f" AS {columns}" if columns else ""
2336            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
2337            return f"{op_sql}{self.sep()}{this}{table}{columns}"
2338
2339        alias = self.sql(expression, "alias")
2340        alias = f" AS {alias}" if alias else ""
2341
2342        ordinality = expression.args.get("ordinality") or ""
2343        if ordinality:
2344            ordinality = f" WITH ORDINALITY{alias}"
2345            alias = ""
2346
2347        return f"{self.lateral_op(expression)} {this}{alias}{ordinality}"
2348
2349    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
2350        this = self.sql(expression, "this")
2351
2352        args = [
2353            self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e
2354            for e in (expression.args.get(k) for k in ("offset", "expression"))
2355            if e
2356        ]
2357
2358        args_sql = ", ".join(self.sql(e) for e in args)
2359        args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql
2360        expressions = self.expressions(expression, flat=True)
2361        limit_options = self.sql(expression, "limit_options")
2362        expressions = f" BY {expressions}" if expressions else ""
2363
2364        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{limit_options}{expressions}"
2365
2366    def offset_sql(self, expression: exp.Offset) -> str:
2367        this = self.sql(expression, "this")
2368        value = expression.expression
2369        value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value
2370        expressions = self.expressions(expression, flat=True)
2371        expressions = f" BY {expressions}" if expressions else ""
2372        return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"
2373
2374    def setitem_sql(self, expression: exp.SetItem) -> str:
2375        kind = self.sql(expression, "kind")
2376        kind = f"{kind} " if kind else ""
2377        this = self.sql(expression, "this")
2378        expressions = self.expressions(expression)
2379        collate = self.sql(expression, "collate")
2380        collate = f" COLLATE {collate}" if collate else ""
2381        global_ = "GLOBAL " if expression.args.get("global") else ""
2382        return f"{global_}{kind}{this}{expressions}{collate}"
2383
2384    def set_sql(self, expression: exp.Set) -> str:
2385        expressions = f" {self.expressions(expression, flat=True)}"
2386        tag = " TAG" if expression.args.get("tag") else ""
2387        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"
2388
2389    def pragma_sql(self, expression: exp.Pragma) -> str:
2390        return f"PRAGMA {self.sql(expression, 'this')}"
2391
2392    def lock_sql(self, expression: exp.Lock) -> str:
2393        if not self.LOCKING_READS_SUPPORTED:
2394            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
2395            return ""
2396
2397        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
2398        expressions = self.expressions(expression, flat=True)
2399        expressions = f" OF {expressions}" if expressions else ""
2400        wait = expression.args.get("wait")
2401
2402        if wait is not None:
2403            if isinstance(wait, exp.Literal):
2404                wait = f" WAIT {self.sql(wait)}"
2405            else:
2406                wait = " NOWAIT" if wait else " SKIP LOCKED"
2407
2408        return f"{lock_type}{expressions}{wait or ''}"
2409
2410    def literal_sql(self, expression: exp.Literal) -> str:
2411        text = expression.this or ""
2412        if expression.is_string:
2413            text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}"
2414        return text
2415
2416    def escape_str(self, text: str, escape_backslash: bool = True) -> str:
2417        if self.dialect.ESCAPED_SEQUENCES:
2418            to_escaped = self.dialect.ESCAPED_SEQUENCES
2419            text = "".join(
2420                to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text
2421            )
2422
2423        return self._replace_line_breaks(text).replace(
2424            self.dialect.QUOTE_END, self._escaped_quote_end
2425        )
2426
2427    def loaddata_sql(self, expression: exp.LoadData) -> str:
2428        local = " LOCAL" if expression.args.get("local") else ""
2429        inpath = f" INPATH {self.sql(expression, 'inpath')}"
2430        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
2431        this = f" INTO TABLE {self.sql(expression, 'this')}"
2432        partition = self.sql(expression, "partition")
2433        partition = f" {partition}" if partition else ""
2434        input_format = self.sql(expression, "input_format")
2435        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
2436        serde = self.sql(expression, "serde")
2437        serde = f" SERDE {serde}" if serde else ""
2438        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"
2439
2440    def null_sql(self, *_) -> str:
2441        return "NULL"
2442
2443    def boolean_sql(self, expression: exp.Boolean) -> str:
2444        return "TRUE" if expression.this else "FALSE"
2445
2446    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
2447        this = self.sql(expression, "this")
2448        this = f"{this} " if this else this
2449        siblings = "SIBLINGS " if expression.args.get("siblings") else ""
2450        return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat)  # type: ignore
2451
2452    def withfill_sql(self, expression: exp.WithFill) -> str:
2453        from_sql = self.sql(expression, "from")
2454        from_sql = f" FROM {from_sql}" if from_sql else ""
2455        to_sql = self.sql(expression, "to")
2456        to_sql = f" TO {to_sql}" if to_sql else ""
2457        step_sql = self.sql(expression, "step")
2458        step_sql = f" STEP {step_sql}" if step_sql else ""
2459        interpolated_values = [
2460            f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}"
2461            if isinstance(e, exp.Alias)
2462            else self.sql(e, "this")
2463            for e in expression.args.get("interpolate") or []
2464        ]
2465        interpolate = (
2466            f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else ""
2467        )
2468        return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}"
2469
2470    def cluster_sql(self, expression: exp.Cluster) -> str:
2471        return self.op_expressions("CLUSTER BY", expression)
2472
2473    def distribute_sql(self, expression: exp.Distribute) -> str:
2474        return self.op_expressions("DISTRIBUTE BY", expression)
2475
2476    def sort_sql(self, expression: exp.Sort) -> str:
2477        return self.op_expressions("SORT BY", expression)
2478
2479    def ordered_sql(self, expression: exp.Ordered) -> str:
2480        desc = expression.args.get("desc")
2481        asc = not desc
2482
2483        nulls_first = expression.args.get("nulls_first")
2484        nulls_last = not nulls_first
2485        nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large"
2486        nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small"
2487        nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last"
2488
2489        this = self.sql(expression, "this")
2490
2491        sort_order = " DESC" if desc else (" ASC" if desc is False else "")
2492        nulls_sort_change = ""
2493        if nulls_first and (
2494            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
2495        ):
2496            nulls_sort_change = " NULLS FIRST"
2497        elif (
2498            nulls_last
2499            and ((asc and nulls_are_small) or (desc and nulls_are_large))
2500            and not nulls_are_last
2501        ):
2502            nulls_sort_change = " NULLS LAST"
2503
2504        # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it
2505        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
2506            window = expression.find_ancestor(exp.Window, exp.Select)
2507            if isinstance(window, exp.Window) and window.args.get("spec"):
2508                self.unsupported(
2509                    f"'{nulls_sort_change.strip()}' translation not supported in window functions"
2510                )
2511                nulls_sort_change = ""
2512            elif self.NULL_ORDERING_SUPPORTED is False and (
2513                (asc and nulls_sort_change == " NULLS LAST")
2514                or (desc and nulls_sort_change == " NULLS FIRST")
2515            ):
2516                # BigQuery does not allow these ordering/nulls combinations when used under
2517                # an aggregation func or under a window containing one
2518                ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select)
2519
2520                if isinstance(ancestor, exp.Window):
2521                    ancestor = ancestor.this
2522                if isinstance(ancestor, exp.AggFunc):
2523                    self.unsupported(
2524                        f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order"
2525                    )
2526                    nulls_sort_change = ""
2527            elif self.NULL_ORDERING_SUPPORTED is None:
2528                if expression.this.is_int:
2529                    self.unsupported(
2530                        f"'{nulls_sort_change.strip()}' translation not supported with positional ordering"
2531                    )
2532                elif not isinstance(expression.this, exp.Rand):
2533                    null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else ""
2534                    this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}"
2535                nulls_sort_change = ""
2536
2537        with_fill = self.sql(expression, "with_fill")
2538        with_fill = f" {with_fill}" if with_fill else ""
2539
2540        return f"{this}{sort_order}{nulls_sort_change}{with_fill}"
2541
2542    def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str:
2543        window_frame = self.sql(expression, "window_frame")
2544        window_frame = f"{window_frame} " if window_frame else ""
2545
2546        this = self.sql(expression, "this")
2547
2548        return f"{window_frame}{this}"
2549
2550    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
2551        partition = self.partition_by_sql(expression)
2552        order = self.sql(expression, "order")
2553        measures = self.expressions(expression, key="measures")
2554        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
2555        rows = self.sql(expression, "rows")
2556        rows = self.seg(rows) if rows else ""
2557        after = self.sql(expression, "after")
2558        after = self.seg(after) if after else ""
2559        pattern = self.sql(expression, "pattern")
2560        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
2561        definition_sqls = [
2562            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
2563            for definition in expression.args.get("define", [])
2564        ]
2565        definitions = self.expressions(sqls=definition_sqls)
2566        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
2567        body = "".join(
2568            (
2569                partition,
2570                order,
2571                measures,
2572                rows,
2573                after,
2574                pattern,
2575                define,
2576            )
2577        )
2578        alias = self.sql(expression, "alias")
2579        alias = f" {alias}" if alias else ""
2580        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"
2581
2582    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
2583        limit = expression.args.get("limit")
2584
2585        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
2586            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
2587        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
2588            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
2589
2590        return csv(
2591            *sqls,
2592            *[self.sql(join) for join in expression.args.get("joins") or []],
2593            self.sql(expression, "match"),
2594            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
2595            self.sql(expression, "prewhere"),
2596            self.sql(expression, "where"),
2597            self.sql(expression, "connect"),
2598            self.sql(expression, "group"),
2599            self.sql(expression, "having"),
2600            *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()],
2601            self.sql(expression, "order"),
2602            *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit),
2603            *self.after_limit_modifiers(expression),
2604            self.options_modifier(expression),
2605            self.for_modifiers(expression),
2606            sep="",
2607        )
2608
2609    def options_modifier(self, expression: exp.Expression) -> str:
2610        options = self.expressions(expression, key="options")
2611        return f" {options}" if options else ""
2612
2613    def for_modifiers(self, expression: exp.Expression) -> str:
2614        for_modifiers = self.expressions(expression, key="for")
2615        return f"{self.sep()}FOR XML{self.seg(for_modifiers)}" if for_modifiers else ""
2616
2617    def queryoption_sql(self, expression: exp.QueryOption) -> str:
2618        self.unsupported("Unsupported query option.")
2619        return ""
2620
2621    def offset_limit_modifiers(
2622        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
2623    ) -> t.List[str]:
2624        return [
2625            self.sql(expression, "offset") if fetch else self.sql(limit),
2626            self.sql(limit) if fetch else self.sql(expression, "offset"),
2627        ]
2628
2629    def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]:
2630        locks = self.expressions(expression, key="locks", sep=" ")
2631        locks = f" {locks}" if locks else ""
2632        return [locks, self.sql(expression, "sample")]
2633
2634    def select_sql(self, expression: exp.Select) -> str:
2635        into = expression.args.get("into")
2636        if not self.SUPPORTS_SELECT_INTO and into:
2637            into.pop()
2638
2639        hint = self.sql(expression, "hint")
2640        distinct = self.sql(expression, "distinct")
2641        distinct = f" {distinct}" if distinct else ""
2642        kind = self.sql(expression, "kind")
2643
2644        limit = expression.args.get("limit")
2645        if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP:
2646            top = self.limit_sql(limit, top=True)
2647            limit.pop()
2648        else:
2649            top = ""
2650
2651        expressions = self.expressions(expression)
2652
2653        if kind:
2654            if kind in self.SELECT_KINDS:
2655                kind = f" AS {kind}"
2656            else:
2657                if kind == "STRUCT":
2658                    expressions = self.expressions(
2659                        sqls=[
2660                            self.sql(
2661                                exp.Struct(
2662                                    expressions=[
2663                                        exp.PropertyEQ(this=e.args.get("alias"), expression=e.this)
2664                                        if isinstance(e, exp.Alias)
2665                                        else e
2666                                        for e in expression.expressions
2667                                    ]
2668                                )
2669                            )
2670                        ]
2671                    )
2672                kind = ""
2673
2674        operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ")
2675        operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else ""
2676
2677        # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata
2678        # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first.
2679        top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}"
2680        expressions = f"{self.sep()}{expressions}" if expressions else expressions
2681        sql = self.query_modifiers(
2682            expression,
2683            f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}",
2684            self.sql(expression, "into", comment=False),
2685            self.sql(expression, "from", comment=False),
2686        )
2687
2688        # If both the CTE and SELECT clauses have comments, generate the latter earlier
2689        if expression.args.get("with"):
2690            sql = self.maybe_comment(sql, expression)
2691            expression.pop_comments()
2692
2693        sql = self.prepend_ctes(expression, sql)
2694
2695        if not self.SUPPORTS_SELECT_INTO and into:
2696            if into.args.get("temporary"):
2697                table_kind = " TEMPORARY"
2698            elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"):
2699                table_kind = " UNLOGGED"
2700            else:
2701                table_kind = ""
2702            sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}"
2703
2704        return sql
2705
2706    def schema_sql(self, expression: exp.Schema) -> str:
2707        this = self.sql(expression, "this")
2708        sql = self.schema_columns_sql(expression)
2709        return f"{this} {sql}" if this and sql else this or sql
2710
2711    def schema_columns_sql(self, expression: exp.Schema) -> str:
2712        if expression.expressions:
2713            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
2714        return ""
2715
2716    def star_sql(self, expression: exp.Star) -> str:
2717        except_ = self.expressions(expression, key="except", flat=True)
2718        except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else ""
2719        replace = self.expressions(expression, key="replace", flat=True)
2720        replace = f"{self.seg('REPLACE')} ({replace})" if replace else ""
2721        rename = self.expressions(expression, key="rename", flat=True)
2722        rename = f"{self.seg('RENAME')} ({rename})" if rename else ""
2723        return f"*{except_}{replace}{rename}"
2724
2725    def parameter_sql(self, expression: exp.Parameter) -> str:
2726        this = self.sql(expression, "this")
2727        return f"{self.PARAMETER_TOKEN}{this}"
2728
2729    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
2730        this = self.sql(expression, "this")
2731        kind = expression.text("kind")
2732        if kind:
2733            kind = f"{kind}."
2734        return f"@@{kind}{this}"
2735
2736    def placeholder_sql(self, expression: exp.Placeholder) -> str:
2737        return f"{self.NAMED_PLACEHOLDER_TOKEN}{expression.name}" if expression.this else "?"
2738
2739    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
2740        alias = self.sql(expression, "alias")
2741        alias = f"{sep}{alias}" if alias else ""
2742        sample = self.sql(expression, "sample")
2743        if self.dialect.ALIAS_POST_TABLESAMPLE and sample:
2744            alias = f"{sample}{alias}"
2745
2746            # Set to None so it's not generated again by self.query_modifiers()
2747            expression.set("sample", None)
2748
2749        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
2750        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
2751        return self.prepend_ctes(expression, sql)
2752
2753    def qualify_sql(self, expression: exp.Qualify) -> str:
2754        this = self.indent(self.sql(expression, "this"))
2755        return f"{self.seg('QUALIFY')}{self.sep()}{this}"
2756
2757    def unnest_sql(self, expression: exp.Unnest) -> str:
2758        args = self.expressions(expression, flat=True)
2759
2760        alias = expression.args.get("alias")
2761        offset = expression.args.get("offset")
2762
2763        if self.UNNEST_WITH_ORDINALITY:
2764            if alias and isinstance(offset, exp.Expression):
2765                alias.append("columns", offset)
2766
2767        if alias and self.dialect.UNNEST_COLUMN_ONLY:
2768            columns = alias.columns
2769            alias = self.sql(columns[0]) if columns else ""
2770        else:
2771            alias = self.sql(alias)
2772
2773        alias = f" AS {alias}" if alias else alias
2774        if self.UNNEST_WITH_ORDINALITY:
2775            suffix = f" WITH ORDINALITY{alias}" if offset else alias
2776        else:
2777            if isinstance(offset, exp.Expression):
2778                suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}"
2779            elif offset:
2780                suffix = f"{alias} WITH OFFSET"
2781            else:
2782                suffix = alias
2783
2784        return f"UNNEST({args}){suffix}"
2785
2786    def prewhere_sql(self, expression: exp.PreWhere) -> str:
2787        return ""
2788
2789    def where_sql(self, expression: exp.Where) -> str:
2790        this = self.indent(self.sql(expression, "this"))
2791        return f"{self.seg('WHERE')}{self.sep()}{this}"
2792
2793    def window_sql(self, expression: exp.Window) -> str:
2794        this = self.sql(expression, "this")
2795        partition = self.partition_by_sql(expression)
2796        order = expression.args.get("order")
2797        order = self.order_sql(order, flat=True) if order else ""
2798        spec = self.sql(expression, "spec")
2799        alias = self.sql(expression, "alias")
2800        over = self.sql(expression, "over") or "OVER"
2801
2802        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
2803
2804        first = expression.args.get("first")
2805        if first is None:
2806            first = ""
2807        else:
2808            first = "FIRST" if first else "LAST"
2809
2810        if not partition and not order and not spec and alias:
2811            return f"{this} {alias}"
2812
2813        args = self.format_args(
2814            *[arg for arg in (alias, first, partition, order, spec) if arg], sep=" "
2815        )
2816        return f"{this} ({args})"
2817
2818    def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str:
2819        partition = self.expressions(expression, key="partition_by", flat=True)
2820        return f"PARTITION BY {partition}" if partition else ""
2821
2822    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
2823        kind = self.sql(expression, "kind")
2824        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
2825        end = (
2826            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
2827            or "CURRENT ROW"
2828        )
2829
2830        window_spec = f"{kind} BETWEEN {start} AND {end}"
2831
2832        exclude = self.sql(expression, "exclude")
2833        if exclude:
2834            if self.SUPPORTS_WINDOW_EXCLUDE:
2835                window_spec += f" EXCLUDE {exclude}"
2836            else:
2837                self.unsupported("EXCLUDE clause is not supported in the WINDOW clause")
2838
2839        return window_spec
2840
2841    def withingroup_sql(self, expression: exp.WithinGroup) -> str:
2842        this = self.sql(expression, "this")
2843        expression_sql = self.sql(expression, "expression")[1:]  # order has a leading space
2844        return f"{this} WITHIN GROUP ({expression_sql})"
2845
2846    def between_sql(self, expression: exp.Between) -> str:
2847        this = self.sql(expression, "this")
2848        low = self.sql(expression, "low")
2849        high = self.sql(expression, "high")
2850        return f"{this} BETWEEN {low} AND {high}"
2851
2852    def bracket_offset_expressions(
2853        self, expression: exp.Bracket, index_offset: t.Optional[int] = None
2854    ) -> t.List[exp.Expression]:
2855        return apply_index_offset(
2856            expression.this,
2857            expression.expressions,
2858            (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0),
2859            dialect=self.dialect,
2860        )
2861
2862    def bracket_sql(self, expression: exp.Bracket) -> str:
2863        expressions = self.bracket_offset_expressions(expression)
2864        expressions_sql = ", ".join(self.sql(e) for e in expressions)
2865        return f"{self.sql(expression, 'this')}[{expressions_sql}]"
2866
2867    def all_sql(self, expression: exp.All) -> str:
2868        return f"ALL {self.wrap(expression)}"
2869
2870    def any_sql(self, expression: exp.Any) -> str:
2871        this = self.sql(expression, "this")
2872        if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)):
2873            if isinstance(expression.this, exp.UNWRAPPED_QUERIES):
2874                this = self.wrap(this)
2875            return f"ANY{this}"
2876        return f"ANY {this}"
2877
2878    def exists_sql(self, expression: exp.Exists) -> str:
2879        return f"EXISTS{self.wrap(expression)}"
2880
2881    def case_sql(self, expression: exp.Case) -> str:
2882        this = self.sql(expression, "this")
2883        statements = [f"CASE {this}" if this else "CASE"]
2884
2885        for e in expression.args["ifs"]:
2886            statements.append(f"WHEN {self.sql(e, 'this')}")
2887            statements.append(f"THEN {self.sql(e, 'true')}")
2888
2889        default = self.sql(expression, "default")
2890
2891        if default:
2892            statements.append(f"ELSE {default}")
2893
2894        statements.append("END")
2895
2896        if self.pretty and self.too_wide(statements):
2897            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
2898
2899        return " ".join(statements)
2900
2901    def constraint_sql(self, expression: exp.Constraint) -> str:
2902        this = self.sql(expression, "this")
2903        expressions = self.expressions(expression, flat=True)
2904        return f"CONSTRAINT {this} {expressions}"
2905
2906    def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str:
2907        order = expression.args.get("order")
2908        order = f" OVER ({self.order_sql(order, flat=True)})" if order else ""
2909        return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}"
2910
2911    def extract_sql(self, expression: exp.Extract) -> str:
2912        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
2913        expression_sql = self.sql(expression, "expression")
2914        return f"EXTRACT({this} FROM {expression_sql})"
2915
2916    def trim_sql(self, expression: exp.Trim) -> str:
2917        trim_type = self.sql(expression, "position")
2918
2919        if trim_type == "LEADING":
2920            func_name = "LTRIM"
2921        elif trim_type == "TRAILING":
2922            func_name = "RTRIM"
2923        else:
2924            func_name = "TRIM"
2925
2926        return self.func(func_name, expression.this, expression.expression)
2927
2928    def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]:
2929        args = expression.expressions
2930        if isinstance(expression, exp.ConcatWs):
2931            args = args[1:]  # Skip the delimiter
2932
2933        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
2934            args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args]
2935
2936        if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"):
2937            args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args]
2938
2939        return args
2940
2941    def concat_sql(self, expression: exp.Concat) -> str:
2942        expressions = self.convert_concat_args(expression)
2943
2944        # Some dialects don't allow a single-argument CONCAT call
2945        if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1:
2946            return self.sql(expressions[0])
2947
2948        return self.func("CONCAT", *expressions)
2949
2950    def concatws_sql(self, expression: exp.ConcatWs) -> str:
2951        return self.func(
2952            "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression)
2953        )
2954
2955    def check_sql(self, expression: exp.Check) -> str:
2956        this = self.sql(expression, key="this")
2957        return f"CHECK ({this})"
2958
2959    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
2960        expressions = self.expressions(expression, flat=True)
2961        expressions = f" ({expressions})" if expressions else ""
2962        reference = self.sql(expression, "reference")
2963        reference = f" {reference}" if reference else ""
2964        delete = self.sql(expression, "delete")
2965        delete = f" ON DELETE {delete}" if delete else ""
2966        update = self.sql(expression, "update")
2967        update = f" ON UPDATE {update}" if update else ""
2968        options = self.expressions(expression, key="options", flat=True, sep=" ")
2969        options = f" {options}" if options else ""
2970        return f"FOREIGN KEY{expressions}{reference}{delete}{update}{options}"
2971
2972    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
2973        expressions = self.expressions(expression, flat=True)
2974        options = self.expressions(expression, key="options", flat=True, sep=" ")
2975        options = f" {options}" if options else ""
2976        return f"PRIMARY KEY ({expressions}){options}"
2977
2978    def if_sql(self, expression: exp.If) -> str:
2979        return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false")))
2980
2981    def matchagainst_sql(self, expression: exp.MatchAgainst) -> str:
2982        modifier = expression.args.get("modifier")
2983        modifier = f" {modifier}" if modifier else ""
2984        return f"{self.func('MATCH', *expression.expressions)} AGAINST({self.sql(expression, 'this')}{modifier})"
2985
2986    def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str:
2987        return f"{self.sql(expression, 'this')}{self.JSON_KEY_VALUE_PAIR_SEP} {self.sql(expression, 'expression')}"
2988
2989    def jsonpath_sql(self, expression: exp.JSONPath) -> str:
2990        path = self.expressions(expression, sep="", flat=True).lstrip(".")
2991
2992        if expression.args.get("escape"):
2993            path = self.escape_str(path)
2994
2995        if self.QUOTE_JSON_PATH:
2996            path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"
2997
2998        return path
2999
3000    def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str:
3001        if isinstance(expression, exp.JSONPathPart):
3002            transform = self.TRANSFORMS.get(expression.__class__)
3003            if not callable(transform):
3004                self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}")
3005                return ""
3006
3007            return transform(self, expression)
3008
3009        if isinstance(expression, int):
3010            return str(expression)
3011
3012        if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE:
3013            escaped = expression.replace("'", "\\'")
3014            escaped = f"\\'{expression}\\'"
3015        else:
3016            escaped = expression.replace('"', '\\"')
3017            escaped = f'"{escaped}"'
3018
3019        return escaped
3020
3021    def formatjson_sql(self, expression: exp.FormatJson) -> str:
3022        return f"{self.sql(expression, 'this')} FORMAT JSON"
3023
3024    def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str:
3025        null_handling = expression.args.get("null_handling")
3026        null_handling = f" {null_handling}" if null_handling else ""
3027
3028        unique_keys = expression.args.get("unique_keys")
3029        if unique_keys is not None:
3030            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
3031        else:
3032            unique_keys = ""
3033
3034        return_type = self.sql(expression, "return_type")
3035        return_type = f" RETURNING {return_type}" if return_type else ""
3036        encoding = self.sql(expression, "encoding")
3037        encoding = f" ENCODING {encoding}" if encoding else ""
3038
3039        return self.func(
3040            "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG",
3041            *expression.expressions,
3042            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
3043        )
3044
3045    def jsonobjectagg_sql(self, expression: exp.JSONObjectAgg) -> str:
3046        return self.jsonobject_sql(expression)
3047
3048    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
3049        null_handling = expression.args.get("null_handling")
3050        null_handling = f" {null_handling}" if null_handling else ""
3051        return_type = self.sql(expression, "return_type")
3052        return_type = f" RETURNING {return_type}" if return_type else ""
3053        strict = " STRICT" if expression.args.get("strict") else ""
3054        return self.func(
3055            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
3056        )
3057
3058    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
3059        this = self.sql(expression, "this")
3060        order = self.sql(expression, "order")
3061        null_handling = expression.args.get("null_handling")
3062        null_handling = f" {null_handling}" if null_handling else ""
3063        return_type = self.sql(expression, "return_type")
3064        return_type = f" RETURNING {return_type}" if return_type else ""
3065        strict = " STRICT" if expression.args.get("strict") else ""
3066        return self.func(
3067            "JSON_ARRAYAGG",
3068            this,
3069            suffix=f"{order}{null_handling}{return_type}{strict})",
3070        )
3071
3072    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
3073        path = self.sql(expression, "path")
3074        path = f" PATH {path}" if path else ""
3075        nested_schema = self.sql(expression, "nested_schema")
3076
3077        if nested_schema:
3078            return f"NESTED{path} {nested_schema}"
3079
3080        this = self.sql(expression, "this")
3081        kind = self.sql(expression, "kind")
3082        kind = f" {kind}" if kind else ""
3083        return f"{this}{kind}{path}"
3084
3085    def jsonschema_sql(self, expression: exp.JSONSchema) -> str:
3086        return self.func("COLUMNS", *expression.expressions)
3087
3088    def jsontable_sql(self, expression: exp.JSONTable) -> str:
3089        this = self.sql(expression, "this")
3090        path = self.sql(expression, "path")
3091        path = f", {path}" if path else ""
3092        error_handling = expression.args.get("error_handling")
3093        error_handling = f" {error_handling}" if error_handling else ""
3094        empty_handling = expression.args.get("empty_handling")
3095        empty_handling = f" {empty_handling}" if empty_handling else ""
3096        schema = self.sql(expression, "schema")
3097        return self.func(
3098            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
3099        )
3100
3101    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
3102        this = self.sql(expression, "this")
3103        kind = self.sql(expression, "kind")
3104        path = self.sql(expression, "path")
3105        path = f" {path}" if path else ""
3106        as_json = " AS JSON" if expression.args.get("as_json") else ""
3107        return f"{this} {kind}{path}{as_json}"
3108
3109    def openjson_sql(self, expression: exp.OpenJSON) -> str:
3110        this = self.sql(expression, "this")
3111        path = self.sql(expression, "path")
3112        path = f", {path}" if path else ""
3113        expressions = self.expressions(expression)
3114        with_ = (
3115            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
3116            if expressions
3117            else ""
3118        )
3119        return f"OPENJSON({this}{path}){with_}"
3120
3121    def in_sql(self, expression: exp.In) -> str:
3122        query = expression.args.get("query")
3123        unnest = expression.args.get("unnest")
3124        field = expression.args.get("field")
3125        is_global = " GLOBAL" if expression.args.get("is_global") else ""
3126
3127        if query:
3128            in_sql = self.sql(query)
3129        elif unnest:
3130            in_sql = self.in_unnest_op(unnest)
3131        elif field:
3132            in_sql = self.sql(field)
3133        else:
3134            in_sql = f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})"
3135
3136        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"
3137
3138    def in_unnest_op(self, unnest: exp.Unnest) -> str:
3139        return f"(SELECT {self.sql(unnest)})"
3140
3141    def interval_sql(self, expression: exp.Interval) -> str:
3142        unit = self.sql(expression, "unit")
3143        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
3144            unit = self.TIME_PART_SINGULARS.get(unit, unit)
3145        unit = f" {unit}" if unit else ""
3146
3147        if self.SINGLE_STRING_INTERVAL:
3148            this = expression.this.name if expression.this else ""
3149            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
3150
3151        this = self.sql(expression, "this")
3152        if this:
3153            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
3154            this = f" {this}" if unwrapped else f" ({this})"
3155
3156        return f"INTERVAL{this}{unit}"
3157
3158    def return_sql(self, expression: exp.Return) -> str:
3159        return f"RETURN {self.sql(expression, 'this')}"
3160
3161    def reference_sql(self, expression: exp.Reference) -> str:
3162        this = self.sql(expression, "this")
3163        expressions = self.expressions(expression, flat=True)
3164        expressions = f"({expressions})" if expressions else ""
3165        options = self.expressions(expression, key="options", flat=True, sep=" ")
3166        options = f" {options}" if options else ""
3167        return f"REFERENCES {this}{expressions}{options}"
3168
3169    def anonymous_sql(self, expression: exp.Anonymous) -> str:
3170        # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive
3171        parent = expression.parent
3172        is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression
3173        return self.func(
3174            self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified
3175        )
3176
3177    def paren_sql(self, expression: exp.Paren) -> str:
3178        sql = self.seg(self.indent(self.sql(expression, "this")), sep="")
3179        return f"({sql}{self.seg(')', sep='')}"
3180
3181    def neg_sql(self, expression: exp.Neg) -> str:
3182        # This makes sure we don't convert "- - 5" to "--5", which is a comment
3183        this_sql = self.sql(expression, "this")
3184        sep = " " if this_sql[0] == "-" else ""
3185        return f"-{sep}{this_sql}"
3186
3187    def not_sql(self, expression: exp.Not) -> str:
3188        return f"NOT {self.sql(expression, 'this')}"
3189
3190    def alias_sql(self, expression: exp.Alias) -> str:
3191        alias = self.sql(expression, "alias")
3192        alias = f" AS {alias}" if alias else ""
3193        return f"{self.sql(expression, 'this')}{alias}"
3194
3195    def pivotalias_sql(self, expression: exp.PivotAlias) -> str:
3196        alias = expression.args["alias"]
3197
3198        parent = expression.parent
3199        pivot = parent and parent.parent
3200
3201        if isinstance(pivot, exp.Pivot) and pivot.unpivot:
3202            identifier_alias = isinstance(alias, exp.Identifier)
3203            literal_alias = isinstance(alias, exp.Literal)
3204
3205            if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
3206                alias.replace(exp.Literal.string(alias.output_name))
3207            elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
3208                alias.replace(exp.to_identifier(alias.output_name))
3209
3210        return self.alias_sql(expression)
3211
3212    def aliases_sql(self, expression: exp.Aliases) -> str:
3213        return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})"
3214
3215    def atindex_sql(self, expression: exp.AtTimeZone) -> str:
3216        this = self.sql(expression, "this")
3217        index = self.sql(expression, "expression")
3218        return f"{this} AT {index}"
3219
3220    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
3221        this = self.sql(expression, "this")
3222        zone = self.sql(expression, "zone")
3223        return f"{this} AT TIME ZONE {zone}"
3224
3225    def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str:
3226        this = self.sql(expression, "this")
3227        zone = self.sql(expression, "zone")
3228        return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'"
3229
3230    def add_sql(self, expression: exp.Add) -> str:
3231        return self.binary(expression, "+")
3232
3233    def and_sql(
3234        self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None
3235    ) -> str:
3236        return self.connector_sql(expression, "AND", stack)
3237
3238    def or_sql(
3239        self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None
3240    ) -> str:
3241        return self.connector_sql(expression, "OR", stack)
3242
3243    def xor_sql(
3244        self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None
3245    ) -> str:
3246        return self.connector_sql(expression, "XOR", stack)
3247
3248    def connector_sql(
3249        self,
3250        expression: exp.Connector,
3251        op: str,
3252        stack: t.Optional[t.List[str | exp.Expression]] = None,
3253    ) -> str:
3254        if stack is not None:
3255            if expression.expressions:
3256                stack.append(self.expressions(expression, sep=f" {op} "))
3257            else:
3258                stack.append(expression.right)
3259                if expression.comments and self.comments:
3260                    for comment in expression.comments:
3261                        if comment:
3262                            op += f" /*{self.sanitize_comment(comment)}*/"
3263                stack.extend((op, expression.left))
3264            return op
3265
3266        stack = [expression]
3267        sqls: t.List[str] = []
3268        ops = set()
3269
3270        while stack:
3271            node = stack.pop()
3272            if isinstance(node, exp.Connector):
3273                ops.add(getattr(self, f"{node.key}_sql")(node, stack))
3274            else:
3275                sql = self.sql(node)
3276                if sqls and sqls[-1] in ops:
3277                    sqls[-1] += f" {sql}"
3278                else:
3279                    sqls.append(sql)
3280
3281        sep = "\n" if self.pretty and self.too_wide(sqls) else " "
3282        return sep.join(sqls)
3283
3284    def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str:
3285        return self.binary(expression, "&")
3286
3287    def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str:
3288        return self.binary(expression, "<<")
3289
3290    def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str:
3291        return f"~{self.sql(expression, 'this')}"
3292
3293    def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str:
3294        return self.binary(expression, "|")
3295
3296    def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str:
3297        return self.binary(expression, ">>")
3298
3299    def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str:
3300        return self.binary(expression, "^")
3301
3302    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
3303        format_sql = self.sql(expression, "format")
3304        format_sql = f" FORMAT {format_sql}" if format_sql else ""
3305        to_sql = self.sql(expression, "to")
3306        to_sql = f" {to_sql}" if to_sql else ""
3307        action = self.sql(expression, "action")
3308        action = f" {action}" if action else ""
3309        default = self.sql(expression, "default")
3310        default = f" DEFAULT {default} ON CONVERSION ERROR" if default else ""
3311        return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{default}{format_sql}{action})"
3312
3313    def currentdate_sql(self, expression: exp.CurrentDate) -> str:
3314        zone = self.sql(expression, "this")
3315        return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE"
3316
3317    def collate_sql(self, expression: exp.Collate) -> str:
3318        if self.COLLATE_IS_FUNC:
3319            return self.function_fallback_sql(expression)
3320        return self.binary(expression, "COLLATE")
3321
3322    def command_sql(self, expression: exp.Command) -> str:
3323        return f"{self.sql(expression, 'this')} {expression.text('expression').strip()}"
3324
3325    def comment_sql(self, expression: exp.Comment) -> str:
3326        this = self.sql(expression, "this")
3327        kind = expression.args["kind"]
3328        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
3329        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
3330        expression_sql = self.sql(expression, "expression")
3331        return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"
3332
3333    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
3334        this = self.sql(expression, "this")
3335        delete = " DELETE" if expression.args.get("delete") else ""
3336        recompress = self.sql(expression, "recompress")
3337        recompress = f" RECOMPRESS {recompress}" if recompress else ""
3338        to_disk = self.sql(expression, "to_disk")
3339        to_disk = f" TO DISK {to_disk}" if to_disk else ""
3340        to_volume = self.sql(expression, "to_volume")
3341        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
3342        return f"{this}{delete}{recompress}{to_disk}{to_volume}"
3343
3344    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
3345        where = self.sql(expression, "where")
3346        group = self.sql(expression, "group")
3347        aggregates = self.expressions(expression, key="aggregates")
3348        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
3349
3350        if not (where or group or aggregates) and len(expression.expressions) == 1:
3351            return f"TTL {self.expressions(expression, flat=True)}"
3352
3353        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"
3354
3355    def transaction_sql(self, expression: exp.Transaction) -> str:
3356        return "BEGIN"
3357
3358    def commit_sql(self, expression: exp.Commit) -> str:
3359        chain = expression.args.get("chain")
3360        if chain is not None:
3361            chain = " AND CHAIN" if chain else " AND NO CHAIN"
3362
3363        return f"COMMIT{chain or ''}"
3364
3365    def rollback_sql(self, expression: exp.Rollback) -> str:
3366        savepoint = expression.args.get("savepoint")
3367        savepoint = f" TO {savepoint}" if savepoint else ""
3368        return f"ROLLBACK{savepoint}"
3369
3370    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
3371        this = self.sql(expression, "this")
3372
3373        dtype = self.sql(expression, "dtype")
3374        if dtype:
3375            collate = self.sql(expression, "collate")
3376            collate = f" COLLATE {collate}" if collate else ""
3377            using = self.sql(expression, "using")
3378            using = f" USING {using}" if using else ""
3379            alter_set_type = self.ALTER_SET_TYPE + " " if self.ALTER_SET_TYPE else ""
3380            return f"ALTER COLUMN {this} {alter_set_type}{dtype}{collate}{using}"
3381
3382        default = self.sql(expression, "default")
3383        if default:
3384            return f"ALTER COLUMN {this} SET DEFAULT {default}"
3385
3386        comment = self.sql(expression, "comment")
3387        if comment:
3388            return f"ALTER COLUMN {this} COMMENT {comment}"
3389
3390        visible = expression.args.get("visible")
3391        if visible:
3392            return f"ALTER COLUMN {this} SET {visible}"
3393
3394        allow_null = expression.args.get("allow_null")
3395        drop = expression.args.get("drop")
3396
3397        if not drop and not allow_null:
3398            self.unsupported("Unsupported ALTER COLUMN syntax")
3399
3400        if allow_null is not None:
3401            keyword = "DROP" if drop else "SET"
3402            return f"ALTER COLUMN {this} {keyword} NOT NULL"
3403
3404        return f"ALTER COLUMN {this} DROP DEFAULT"
3405
3406    def alterindex_sql(self, expression: exp.AlterIndex) -> str:
3407        this = self.sql(expression, "this")
3408
3409        visible = expression.args.get("visible")
3410        visible_sql = "VISIBLE" if visible else "INVISIBLE"
3411
3412        return f"ALTER INDEX {this} {visible_sql}"
3413
3414    def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str:
3415        this = self.sql(expression, "this")
3416        if not isinstance(expression.this, exp.Var):
3417            this = f"KEY DISTKEY {this}"
3418        return f"ALTER DISTSTYLE {this}"
3419
3420    def altersortkey_sql(self, expression: exp.AlterSortKey) -> str:
3421        compound = " COMPOUND" if expression.args.get("compound") else ""
3422        this = self.sql(expression, "this")
3423        expressions = self.expressions(expression, flat=True)
3424        expressions = f"({expressions})" if expressions else ""
3425        return f"ALTER{compound} SORTKEY {this or expressions}"
3426
3427    def alterrename_sql(self, expression: exp.AlterRename) -> str:
3428        if not self.RENAME_TABLE_WITH_DB:
3429            # Remove db from tables
3430            expression = expression.transform(
3431                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
3432            ).assert_is(exp.AlterRename)
3433        this = self.sql(expression, "this")
3434        return f"RENAME TO {this}"
3435
3436    def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
3437        exists = " IF EXISTS" if expression.args.get("exists") else ""
3438        old_column = self.sql(expression, "this")
3439        new_column = self.sql(expression, "to")
3440        return f"RENAME COLUMN{exists} {old_column} TO {new_column}"
3441
3442    def alterset_sql(self, expression: exp.AlterSet) -> str:
3443        exprs = self.expressions(expression, flat=True)
3444        if self.ALTER_SET_WRAPPED:
3445            exprs = f"({exprs})"
3446
3447        return f"SET {exprs}"
3448
3449    def alter_sql(self, expression: exp.Alter) -> str:
3450        actions = expression.args["actions"]
3451
3452        if not self.dialect.ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN and isinstance(
3453            actions[0], exp.ColumnDef
3454        ):
3455            actions_sql = self.expressions(expression, key="actions", flat=True)
3456            actions_sql = f"ADD {actions_sql}"
3457        else:
3458            actions_list = []
3459            for action in actions:
3460                if isinstance(action, (exp.ColumnDef, exp.Schema)):
3461                    action_sql = self.add_column_sql(action)
3462                else:
3463                    action_sql = self.sql(action)
3464                    if isinstance(action, exp.Query):
3465                        action_sql = f"AS {action_sql}"
3466
3467                actions_list.append(action_sql)
3468
3469            actions_sql = self.format_args(*actions_list)
3470
3471        exists = " IF EXISTS" if expression.args.get("exists") else ""
3472        on_cluster = self.sql(expression, "cluster")
3473        on_cluster = f" {on_cluster}" if on_cluster else ""
3474        only = " ONLY" if expression.args.get("only") else ""
3475        options = self.expressions(expression, key="options")
3476        options = f", {options}" if options else ""
3477        kind = self.sql(expression, "kind")
3478        not_valid = " NOT VALID" if expression.args.get("not_valid") else ""
3479
3480        return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions_sql}{not_valid}{options}"
3481
3482    def add_column_sql(self, expression: exp.Expression) -> str:
3483        sql = self.sql(expression)
3484        if isinstance(expression, exp.Schema):
3485            column_text = " COLUMNS"
3486        elif isinstance(expression, exp.ColumnDef) and self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD:
3487            column_text = " COLUMN"
3488        else:
3489            column_text = ""
3490
3491        return f"ADD{column_text} {sql}"
3492
3493    def droppartition_sql(self, expression: exp.DropPartition) -> str:
3494        expressions = self.expressions(expression)
3495        exists = " IF EXISTS " if expression.args.get("exists") else " "
3496        return f"DROP{exists}{expressions}"
3497
3498    def addconstraint_sql(self, expression: exp.AddConstraint) -> str:
3499        return f"ADD {self.expressions(expression)}"
3500
3501    def addpartition_sql(self, expression: exp.AddPartition) -> str:
3502        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
3503        return f"ADD {exists}{self.sql(expression.this)}"
3504
3505    def distinct_sql(self, expression: exp.Distinct) -> str:
3506        this = self.expressions(expression, flat=True)
3507
3508        if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1:
3509            case = exp.case()
3510            for arg in expression.expressions:
3511                case = case.when(arg.is_(exp.null()), exp.null())
3512            this = self.sql(case.else_(f"({this})"))
3513
3514        this = f" {this}" if this else ""
3515
3516        on = self.sql(expression, "on")
3517        on = f" ON {on}" if on else ""
3518        return f"DISTINCT{this}{on}"
3519
3520    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
3521        return self._embed_ignore_nulls(expression, "IGNORE NULLS")
3522
3523    def respectnulls_sql(self, expression: exp.RespectNulls) -> str:
3524        return self._embed_ignore_nulls(expression, "RESPECT NULLS")
3525
3526    def havingmax_sql(self, expression: exp.HavingMax) -> str:
3527        this_sql = self.sql(expression, "this")
3528        expression_sql = self.sql(expression, "expression")
3529        kind = "MAX" if expression.args.get("max") else "MIN"
3530        return f"{this_sql} HAVING {kind} {expression_sql}"
3531
3532    def intdiv_sql(self, expression: exp.IntDiv) -> str:
3533        return self.sql(
3534            exp.Cast(
3535                this=exp.Div(this=expression.this, expression=expression.expression),
3536                to=exp.DataType(this=exp.DataType.Type.INT),
3537            )
3538        )
3539
3540    def dpipe_sql(self, expression: exp.DPipe) -> str:
3541        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
3542            return self.func(
3543                "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten())
3544            )
3545        return self.binary(expression, "||")
3546
3547    def div_sql(self, expression: exp.Div) -> str:
3548        l, r = expression.left, expression.right
3549
3550        if not self.dialect.SAFE_DIVISION and expression.args.get("safe"):
3551            r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0)))
3552
3553        if self.dialect.TYPED_DIVISION and not expression.args.get("typed"):
3554            if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES):
3555                l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE))
3556
3557        elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"):
3558            if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES):
3559                return self.sql(
3560                    exp.cast(
3561                        l / r,
3562                        to=exp.DataType.Type.BIGINT,
3563                    )
3564                )
3565
3566        return self.binary(expression, "/")
3567
3568    def safedivide_sql(self, expression: exp.SafeDivide) -> str:
3569        n = exp._wrap(expression.this, exp.Binary)
3570        d = exp._wrap(expression.expression, exp.Binary)
3571        return self.sql(exp.If(this=d.neq(0), true=n / d, false=exp.Null()))
3572
3573    def overlaps_sql(self, expression: exp.Overlaps) -> str:
3574        return self.binary(expression, "OVERLAPS")
3575
3576    def distance_sql(self, expression: exp.Distance) -> str:
3577        return self.binary(expression, "<->")
3578
3579    def dot_sql(self, expression: exp.Dot) -> str:
3580        return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}"
3581
3582    def eq_sql(self, expression: exp.EQ) -> str:
3583        return self.binary(expression, "=")
3584
3585    def propertyeq_sql(self, expression: exp.PropertyEQ) -> str:
3586        return self.binary(expression, ":=")
3587
3588    def escape_sql(self, expression: exp.Escape) -> str:
3589        return self.binary(expression, "ESCAPE")
3590
3591    def glob_sql(self, expression: exp.Glob) -> str:
3592        return self.binary(expression, "GLOB")
3593
3594    def gt_sql(self, expression: exp.GT) -> str:
3595        return self.binary(expression, ">")
3596
3597    def gte_sql(self, expression: exp.GTE) -> str:
3598        return self.binary(expression, ">=")
3599
3600    def ilike_sql(self, expression: exp.ILike) -> str:
3601        return self.binary(expression, "ILIKE")
3602
3603    def ilikeany_sql(self, expression: exp.ILikeAny) -> str:
3604        return self.binary(expression, "ILIKE ANY")
3605
3606    def is_sql(self, expression: exp.Is) -> str:
3607        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
3608            return self.sql(
3609                expression.this if expression.expression.this else exp.not_(expression.this)
3610            )
3611        return self.binary(expression, "IS")
3612
3613    def like_sql(self, expression: exp.Like) -> str:
3614        return self.binary(expression, "LIKE")
3615
3616    def likeany_sql(self, expression: exp.LikeAny) -> str:
3617        return self.binary(expression, "LIKE ANY")
3618
3619    def similarto_sql(self, expression: exp.SimilarTo) -> str:
3620        return self.binary(expression, "SIMILAR TO")
3621
3622    def lt_sql(self, expression: exp.LT) -> str:
3623        return self.binary(expression, "<")
3624
3625    def lte_sql(self, expression: exp.LTE) -> str:
3626        return self.binary(expression, "<=")
3627
3628    def mod_sql(self, expression: exp.Mod) -> str:
3629        return self.binary(expression, "%")
3630
3631    def mul_sql(self, expression: exp.Mul) -> str:
3632        return self.binary(expression, "*")
3633
3634    def neq_sql(self, expression: exp.NEQ) -> str:
3635        return self.binary(expression, "<>")
3636
3637    def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str:
3638        return self.binary(expression, "IS NOT DISTINCT FROM")
3639
3640    def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str:
3641        return self.binary(expression, "IS DISTINCT FROM")
3642
3643    def slice_sql(self, expression: exp.Slice) -> str:
3644        return self.binary(expression, ":")
3645
3646    def sub_sql(self, expression: exp.Sub) -> str:
3647        return self.binary(expression, "-")
3648
3649    def trycast_sql(self, expression: exp.TryCast) -> str:
3650        return self.cast_sql(expression, safe_prefix="TRY_")
3651
3652    def jsoncast_sql(self, expression: exp.JSONCast) -> str:
3653        return self.cast_sql(expression)
3654
3655    def try_sql(self, expression: exp.Try) -> str:
3656        if not self.TRY_SUPPORTED:
3657            self.unsupported("Unsupported TRY function")
3658            return self.sql(expression, "this")
3659
3660        return self.func("TRY", expression.this)
3661
3662    def log_sql(self, expression: exp.Log) -> str:
3663        this = expression.this
3664        expr = expression.expression
3665
3666        if self.dialect.LOG_BASE_FIRST is False:
3667            this, expr = expr, this
3668        elif self.dialect.LOG_BASE_FIRST is None and expr:
3669            if this.name in ("2", "10"):
3670                return self.func(f"LOG{this.name}", expr)
3671
3672            self.unsupported(f"Unsupported logarithm with base {self.sql(this)}")
3673
3674        return self.func("LOG", this, expr)
3675
3676    def use_sql(self, expression: exp.Use) -> str:
3677        kind = self.sql(expression, "kind")
3678        kind = f" {kind}" if kind else ""
3679        this = self.sql(expression, "this") or self.expressions(expression, flat=True)
3680        this = f" {this}" if this else ""
3681        return f"USE{kind}{this}"
3682
3683    def binary(self, expression: exp.Binary, op: str) -> str:
3684        sqls: t.List[str] = []
3685        stack: t.List[t.Union[str, exp.Expression]] = [expression]
3686        binary_type = type(expression)
3687
3688        while stack:
3689            node = stack.pop()
3690
3691            if type(node) is binary_type:
3692                op_func = node.args.get("operator")
3693                if op_func:
3694                    op = f"OPERATOR({self.sql(op_func)})"
3695
3696                stack.append(node.right)
3697                stack.append(f" {self.maybe_comment(op, comments=node.comments)} ")
3698                stack.append(node.left)
3699            else:
3700                sqls.append(self.sql(node))
3701
3702        return "".join(sqls)
3703
3704    def ceil_floor(self, expression: exp.Ceil | exp.Floor) -> str:
3705        to_clause = self.sql(expression, "to")
3706        if to_clause:
3707            return f"{expression.sql_name()}({self.sql(expression, 'this')} TO {to_clause})"
3708
3709        return self.function_fallback_sql(expression)
3710
3711    def function_fallback_sql(self, expression: exp.Func) -> str:
3712        args = []
3713
3714        for key in expression.arg_types:
3715            arg_value = expression.args.get(key)
3716
3717            if isinstance(arg_value, list):
3718                for value in arg_value:
3719                    args.append(value)
3720            elif arg_value is not None:
3721                args.append(arg_value)
3722
3723        if self.dialect.PRESERVE_ORIGINAL_NAMES:
3724            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
3725        else:
3726            name = expression.sql_name()
3727
3728        return self.func(name, *args)
3729
3730    def func(
3731        self,
3732        name: str,
3733        *args: t.Optional[exp.Expression | str],
3734        prefix: str = "(",
3735        suffix: str = ")",
3736        normalize: bool = True,
3737    ) -> str:
3738        name = self.normalize_func(name) if normalize else name
3739        return f"{name}{prefix}{self.format_args(*args)}{suffix}"
3740
3741    def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str:
3742        arg_sqls = tuple(
3743            self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool)
3744        )
3745        if self.pretty and self.too_wide(arg_sqls):
3746            return self.indent(
3747                "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True
3748            )
3749        return sep.join(arg_sqls)
3750
3751    def too_wide(self, args: t.Iterable) -> bool:
3752        return sum(len(arg) for arg in args) > self.max_text_width
3753
3754    def format_time(
3755        self,
3756        expression: exp.Expression,
3757        inverse_time_mapping: t.Optional[t.Dict[str, str]] = None,
3758        inverse_time_trie: t.Optional[t.Dict] = None,
3759    ) -> t.Optional[str]:
3760        return format_time(
3761            self.sql(expression, "format"),
3762            inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING,
3763            inverse_time_trie or self.dialect.INVERSE_TIME_TRIE,
3764        )
3765
3766    def expressions(
3767        self,
3768        expression: t.Optional[exp.Expression] = None,
3769        key: t.Optional[str] = None,
3770        sqls: t.Optional[t.Collection[str | exp.Expression]] = None,
3771        flat: bool = False,
3772        indent: bool = True,
3773        skip_first: bool = False,
3774        skip_last: bool = False,
3775        sep: str = ", ",
3776        prefix: str = "",
3777        dynamic: bool = False,
3778        new_line: bool = False,
3779    ) -> str:
3780        expressions = expression.args.get(key or "expressions") if expression else sqls
3781
3782        if not expressions:
3783            return ""
3784
3785        if flat:
3786            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
3787
3788        num_sqls = len(expressions)
3789        result_sqls = []
3790
3791        for i, e in enumerate(expressions):
3792            sql = self.sql(e, comment=False)
3793            if not sql:
3794                continue
3795
3796            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
3797
3798            if self.pretty:
3799                if self.leading_comma:
3800                    result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}")
3801                else:
3802                    result_sqls.append(
3803                        f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}"
3804                    )
3805            else:
3806                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
3807
3808        if self.pretty and (not dynamic or self.too_wide(result_sqls)):
3809            if new_line:
3810                result_sqls.insert(0, "")
3811                result_sqls.append("")
3812            result_sql = "\n".join(s.rstrip() for s in result_sqls)
3813        else:
3814            result_sql = "".join(result_sqls)
3815
3816        return (
3817            self.indent(result_sql, skip_first=skip_first, skip_last=skip_last)
3818            if indent
3819            else result_sql
3820        )
3821
3822    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
3823        flat = flat or isinstance(expression.parent, exp.Properties)
3824        expressions_sql = self.expressions(expression, flat=flat)
3825        if flat:
3826            return f"{op} {expressions_sql}"
3827        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"
3828
3829    def naked_property(self, expression: exp.Property) -> str:
3830        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
3831        if not property_name:
3832            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
3833        return f"{property_name} {self.sql(expression, 'this')}"
3834
3835    def tag_sql(self, expression: exp.Tag) -> str:
3836        return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}"
3837
3838    def token_sql(self, token_type: TokenType) -> str:
3839        return self.TOKEN_MAPPING.get(token_type, token_type.name)
3840
3841    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
3842        this = self.sql(expression, "this")
3843        expressions = self.no_identify(self.expressions, expression)
3844        expressions = (
3845            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
3846        )
3847        return f"{this}{expressions}" if expressions.strip() != "" else this
3848
3849    def joinhint_sql(self, expression: exp.JoinHint) -> str:
3850        this = self.sql(expression, "this")
3851        expressions = self.expressions(expression, flat=True)
3852        return f"{this}({expressions})"
3853
3854    def kwarg_sql(self, expression: exp.Kwarg) -> str:
3855        return self.binary(expression, "=>")
3856
3857    def when_sql(self, expression: exp.When) -> str:
3858        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
3859        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
3860        condition = self.sql(expression, "condition")
3861        condition = f" AND {condition}" if condition else ""
3862
3863        then_expression = expression.args.get("then")
3864        if isinstance(then_expression, exp.Insert):
3865            this = self.sql(then_expression, "this")
3866            this = f"INSERT {this}" if this else "INSERT"
3867            then = self.sql(then_expression, "expression")
3868            then = f"{this} VALUES {then}" if then else this
3869        elif isinstance(then_expression, exp.Update):
3870            if isinstance(then_expression.args.get("expressions"), exp.Star):
3871                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
3872            else:
3873                then = f"UPDATE SET{self.sep()}{self.expressions(then_expression)}"
3874        else:
3875            then = self.sql(then_expression)
3876        return f"WHEN {matched}{source}{condition} THEN {then}"
3877
3878    def whens_sql(self, expression: exp.Whens) -> str:
3879        return self.expressions(expression, sep=" ", indent=False)
3880
3881    def merge_sql(self, expression: exp.Merge) -> str:
3882        table = expression.this
3883        table_alias = ""
3884
3885        hints = table.args.get("hints")
3886        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
3887            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
3888            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
3889
3890        this = self.sql(table)
3891        using = f"USING {self.sql(expression, 'using')}"
3892        on = f"ON {self.sql(expression, 'on')}"
3893        whens = self.sql(expression, "whens")
3894
3895        returning = self.sql(expression, "returning")
3896        if returning:
3897            whens = f"{whens}{returning}"
3898
3899        sep = self.sep()
3900
3901        return self.prepend_ctes(
3902            expression,
3903            f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}",
3904        )
3905
3906    @unsupported_args("format")
3907    def tochar_sql(self, expression: exp.ToChar) -> str:
3908        return self.sql(exp.cast(expression.this, exp.DataType.Type.TEXT))
3909
3910    def tonumber_sql(self, expression: exp.ToNumber) -> str:
3911        if not self.SUPPORTS_TO_NUMBER:
3912            self.unsupported("Unsupported TO_NUMBER function")
3913            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
3914
3915        fmt = expression.args.get("format")
3916        if not fmt:
3917            self.unsupported("Conversion format is required for TO_NUMBER")
3918            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
3919
3920        return self.func("TO_NUMBER", expression.this, fmt)
3921
3922    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
3923        this = self.sql(expression, "this")
3924        kind = self.sql(expression, "kind")
3925        settings_sql = self.expressions(expression, key="settings", sep=" ")
3926        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
3927        return f"{this}({kind}{args})"
3928
3929    def dictrange_sql(self, expression: exp.DictRange) -> str:
3930        this = self.sql(expression, "this")
3931        max = self.sql(expression, "max")
3932        min = self.sql(expression, "min")
3933        return f"{this}(MIN {min} MAX {max})"
3934
3935    def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str:
3936        return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}"
3937
3938    def duplicatekeyproperty_sql(self, expression: exp.DuplicateKeyProperty) -> str:
3939        return f"DUPLICATE KEY ({self.expressions(expression, flat=True)})"
3940
3941    # https://docs.starrocks.io/docs/sql-reference/sql-statements/table_bucket_part_index/CREATE_TABLE/
3942    def uniquekeyproperty_sql(self, expression: exp.UniqueKeyProperty) -> str:
3943        return f"UNIQUE KEY ({self.expressions(expression, flat=True)})"
3944
3945    # https://docs.starrocks.io/docs/sql-reference/sql-statements/data-definition/CREATE_TABLE/#distribution_desc
3946    def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str:
3947        expressions = self.expressions(expression, flat=True)
3948        expressions = f" {self.wrap(expressions)}" if expressions else ""
3949        buckets = self.sql(expression, "buckets")
3950        kind = self.sql(expression, "kind")
3951        buckets = f" BUCKETS {buckets}" if buckets else ""
3952        order = self.sql(expression, "order")
3953        return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}"
3954
3955    def oncluster_sql(self, expression: exp.OnCluster) -> str:
3956        return ""
3957
3958    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
3959        expressions = self.expressions(expression, key="expressions", flat=True)
3960        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
3961        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
3962        buckets = self.sql(expression, "buckets")
3963        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"
3964
3965    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
3966        this = self.sql(expression, "this")
3967        having = self.sql(expression, "having")
3968
3969        if having:
3970            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
3971
3972        return self.func("ANY_VALUE", this)
3973
3974    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
3975        transform = self.func("TRANSFORM", *expression.expressions)
3976        row_format_before = self.sql(expression, "row_format_before")
3977        row_format_before = f" {row_format_before}" if row_format_before else ""
3978        record_writer = self.sql(expression, "record_writer")
3979        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
3980        using = f" USING {self.sql(expression, 'command_script')}"
3981        schema = self.sql(expression, "schema")
3982        schema = f" AS {schema}" if schema else ""
3983        row_format_after = self.sql(expression, "row_format_after")
3984        row_format_after = f" {row_format_after}" if row_format_after else ""
3985        record_reader = self.sql(expression, "record_reader")
3986        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
3987        return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}"
3988
3989    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
3990        key_block_size = self.sql(expression, "key_block_size")
3991        if key_block_size:
3992            return f"KEY_BLOCK_SIZE = {key_block_size}"
3993
3994        using = self.sql(expression, "using")
3995        if using:
3996            return f"USING {using}"
3997
3998        parser = self.sql(expression, "parser")
3999        if parser:
4000            return f"WITH PARSER {parser}"
4001
4002        comment = self.sql(expression, "comment")
4003        if comment:
4004            return f"COMMENT {comment}"
4005
4006        visible = expression.args.get("visible")
4007        if visible is not None:
4008            return "VISIBLE" if visible else "INVISIBLE"
4009
4010        engine_attr = self.sql(expression, "engine_attr")
4011        if engine_attr:
4012            return f"ENGINE_ATTRIBUTE = {engine_attr}"
4013
4014        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
4015        if secondary_engine_attr:
4016            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
4017
4018        self.unsupported("Unsupported index constraint option.")
4019        return ""
4020
4021    def checkcolumnconstraint_sql(self, expression: exp.CheckColumnConstraint) -> str:
4022        enforced = " ENFORCED" if expression.args.get("enforced") else ""
4023        return f"CHECK ({self.sql(expression, 'this')}){enforced}"
4024
4025    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
4026        kind = self.sql(expression, "kind")
4027        kind = f"{kind} INDEX" if kind else "INDEX"
4028        this = self.sql(expression, "this")
4029        this = f" {this}" if this else ""
4030        index_type = self.sql(expression, "index_type")
4031        index_type = f" USING {index_type}" if index_type else ""
4032        expressions = self.expressions(expression, flat=True)
4033        expressions = f" ({expressions})" if expressions else ""
4034        options = self.expressions(expression, key="options", sep=" ")
4035        options = f" {options}" if options else ""
4036        return f"{kind}{this}{index_type}{expressions}{options}"
4037
4038    def nvl2_sql(self, expression: exp.Nvl2) -> str:
4039        if self.NVL2_SUPPORTED:
4040            return self.function_fallback_sql(expression)
4041
4042        case = exp.Case().when(
4043            expression.this.is_(exp.null()).not_(copy=False),
4044            expression.args["true"],
4045            copy=False,
4046        )
4047        else_cond = expression.args.get("false")
4048        if else_cond:
4049            case.else_(else_cond, copy=False)
4050
4051        return self.sql(case)
4052
4053    def comprehension_sql(self, expression: exp.Comprehension) -> str:
4054        this = self.sql(expression, "this")
4055        expr = self.sql(expression, "expression")
4056        iterator = self.sql(expression, "iterator")
4057        condition = self.sql(expression, "condition")
4058        condition = f" IF {condition}" if condition else ""
4059        return f"{this} FOR {expr} IN {iterator}{condition}"
4060
4061    def columnprefix_sql(self, expression: exp.ColumnPrefix) -> str:
4062        return f"{self.sql(expression, 'this')}({self.sql(expression, 'expression')})"
4063
4064    def opclass_sql(self, expression: exp.Opclass) -> str:
4065        return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}"
4066
4067    def predict_sql(self, expression: exp.Predict) -> str:
4068        model = self.sql(expression, "this")
4069        model = f"MODEL {model}"
4070        table = self.sql(expression, "expression")
4071        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
4072        parameters = self.sql(expression, "params_struct")
4073        return self.func("PREDICT", model, table, parameters or None)
4074
4075    def forin_sql(self, expression: exp.ForIn) -> str:
4076        this = self.sql(expression, "this")
4077        expression_sql = self.sql(expression, "expression")
4078        return f"FOR {this} DO {expression_sql}"
4079
4080    def refresh_sql(self, expression: exp.Refresh) -> str:
4081        this = self.sql(expression, "this")
4082        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
4083        return f"REFRESH {table}{this}"
4084
4085    def toarray_sql(self, expression: exp.ToArray) -> str:
4086        arg = expression.this
4087        if not arg.type:
4088            from sqlglot.optimizer.annotate_types import annotate_types
4089
4090            arg = annotate_types(arg, dialect=self.dialect)
4091
4092        if arg.is_type(exp.DataType.Type.ARRAY):
4093            return self.sql(arg)
4094
4095        cond_for_null = arg.is_(exp.null())
4096        return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False)))
4097
4098    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
4099        this = expression.this
4100        time_format = self.format_time(expression)
4101
4102        if time_format:
4103            return self.sql(
4104                exp.cast(
4105                    exp.StrToTime(this=this, format=expression.args["format"]),
4106                    exp.DataType.Type.TIME,
4107                )
4108            )
4109
4110        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
4111            return self.sql(this)
4112
4113        return self.sql(exp.cast(this, exp.DataType.Type.TIME))
4114
4115    def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str:
4116        this = expression.this
4117        if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP):
4118            return self.sql(this)
4119
4120        return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect))
4121
4122    def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str:
4123        this = expression.this
4124        if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME):
4125            return self.sql(this)
4126
4127        return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect))
4128
4129    def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:
4130        this = expression.this
4131        time_format = self.format_time(expression)
4132
4133        if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT):
4134            return self.sql(
4135                exp.cast(
4136                    exp.StrToTime(this=this, format=expression.args["format"]),
4137                    exp.DataType.Type.DATE,
4138                )
4139            )
4140
4141        if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE):
4142            return self.sql(this)
4143
4144        return self.sql(exp.cast(this, exp.DataType.Type.DATE))
4145
4146    def unixdate_sql(self, expression: exp.UnixDate) -> str:
4147        return self.sql(
4148            exp.func(
4149                "DATEDIFF",
4150                expression.this,
4151                exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE),
4152                "day",
4153            )
4154        )
4155
4156    def lastday_sql(self, expression: exp.LastDay) -> str:
4157        if self.LAST_DAY_SUPPORTS_DATE_PART:
4158            return self.function_fallback_sql(expression)
4159
4160        unit = expression.text("unit")
4161        if unit and unit != "MONTH":
4162            self.unsupported("Date parts are not supported in LAST_DAY.")
4163
4164        return self.func("LAST_DAY", expression.this)
4165
4166    def dateadd_sql(self, expression: exp.DateAdd) -> str:
4167        from sqlglot.dialects.dialect import unit_to_str
4168
4169        return self.func(
4170            "DATE_ADD", expression.this, expression.expression, unit_to_str(expression)
4171        )
4172
4173    def arrayany_sql(self, expression: exp.ArrayAny) -> str:
4174        if self.CAN_IMPLEMENT_ARRAY_ANY:
4175            filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression)
4176            filtered_not_empty = exp.ArraySize(this=filtered).neq(0)
4177            original_is_empty = exp.ArraySize(this=expression.this).eq(0)
4178            return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty)))
4179
4180        from sqlglot.dialects import Dialect
4181
4182        # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect
4183        if self.dialect.__class__ != Dialect:
4184            self.unsupported("ARRAY_ANY is unsupported")
4185
4186        return self.function_fallback_sql(expression)
4187
4188    def struct_sql(self, expression: exp.Struct) -> str:
4189        expression.set(
4190            "expressions",
4191            [
4192                exp.alias_(e.expression, e.name if e.this.is_string else e.this)
4193                if isinstance(e, exp.PropertyEQ)
4194                else e
4195                for e in expression.expressions
4196            ],
4197        )
4198
4199        return self.function_fallback_sql(expression)
4200
4201    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
4202        low = self.sql(expression, "this")
4203        high = self.sql(expression, "expression")
4204
4205        return f"{low} TO {high}"
4206
4207    def truncatetable_sql(self, expression: exp.TruncateTable) -> str:
4208        target = "DATABASE" if expression.args.get("is_database") else "TABLE"
4209        tables = f" {self.expressions(expression)}"
4210
4211        exists = " IF EXISTS" if expression.args.get("exists") else ""
4212
4213        on_cluster = self.sql(expression, "cluster")
4214        on_cluster = f" {on_cluster}" if on_cluster else ""
4215
4216        identity = self.sql(expression, "identity")
4217        identity = f" {identity} IDENTITY" if identity else ""
4218
4219        option = self.sql(expression, "option")
4220        option = f" {option}" if option else ""
4221
4222        partition = self.sql(expression, "partition")
4223        partition = f" {partition}" if partition else ""
4224
4225        return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"
4226
4227    # This transpiles T-SQL's CONVERT function
4228    # https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16
4229    def convert_sql(self, expression: exp.Convert) -> str:
4230        to = expression.this
4231        value = expression.expression
4232        style = expression.args.get("style")
4233        safe = expression.args.get("safe")
4234        strict = expression.args.get("strict")
4235
4236        if not to or not value:
4237            return ""
4238
4239        # Retrieve length of datatype and override to default if not specified
4240        if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES:
4241            to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
4242
4243        transformed: t.Optional[exp.Expression] = None
4244        cast = exp.Cast if strict else exp.TryCast
4245
4246        # Check whether a conversion with format (T-SQL calls this 'style') is applicable
4247        if isinstance(style, exp.Literal) and style.is_int:
4248            from sqlglot.dialects.tsql import TSQL
4249
4250            style_value = style.name
4251            converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value)
4252            if not converted_style:
4253                self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}")
4254
4255            fmt = exp.Literal.string(converted_style)
4256
4257            if to.this == exp.DataType.Type.DATE:
4258                transformed = exp.StrToDate(this=value, format=fmt)
4259            elif to.this in (exp.DataType.Type.DATETIME, exp.DataType.Type.DATETIME2):
4260                transformed = exp.StrToTime(this=value, format=fmt)
4261            elif to.this in self.PARAMETERIZABLE_TEXT_TYPES:
4262                transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe)
4263            elif to.this == exp.DataType.Type.TEXT:
4264                transformed = exp.TimeToStr(this=value, format=fmt)
4265
4266        if not transformed:
4267            transformed = cast(this=value, to=to, safe=safe)
4268
4269        return self.sql(transformed)
4270
4271    def _jsonpathkey_sql(self, expression: exp.JSONPathKey) -> str:
4272        this = expression.this
4273        if isinstance(this, exp.JSONPathWildcard):
4274            this = self.json_path_part(this)
4275            return f".{this}" if this else ""
4276
4277        if exp.SAFE_IDENTIFIER_RE.match(this):
4278            return f".{this}"
4279
4280        this = self.json_path_part(this)
4281        return (
4282            f"[{this}]"
4283            if self._quote_json_path_key_using_brackets and self.JSON_PATH_BRACKETED_KEY_SUPPORTED
4284            else f".{this}"
4285        )
4286
4287    def _jsonpathsubscript_sql(self, expression: exp.JSONPathSubscript) -> str:
4288        this = self.json_path_part(expression.this)
4289        return f"[{this}]" if this else ""
4290
4291    def _simplify_unless_literal(self, expression: E) -> E:
4292        if not isinstance(expression, exp.Literal):
4293            from sqlglot.optimizer.simplify import simplify
4294
4295            expression = simplify(expression, dialect=self.dialect)
4296
4297        return expression
4298
4299    def _embed_ignore_nulls(self, expression: exp.IgnoreNulls | exp.RespectNulls, text: str) -> str:
4300        this = expression.this
4301        if isinstance(this, self.RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS):
4302            self.unsupported(
4303                f"RESPECT/IGNORE NULLS is not supported for {type(this).key} in {self.dialect.__class__.__name__}"
4304            )
4305            return self.sql(this)
4306
4307        if self.IGNORE_NULLS_IN_FUNC and not expression.meta.get("inline"):
4308            # The first modifier here will be the one closest to the AggFunc's arg
4309            mods = sorted(
4310                expression.find_all(exp.HavingMax, exp.Order, exp.Limit),
4311                key=lambda x: 0
4312                if isinstance(x, exp.HavingMax)
4313                else (1 if isinstance(x, exp.Order) else 2),
4314            )
4315
4316            if mods:
4317                mod = mods[0]
4318                this = expression.__class__(this=mod.this.copy())
4319                this.meta["inline"] = True
4320                mod.this.replace(this)
4321                return self.sql(expression.this)
4322
4323            agg_func = expression.find(exp.AggFunc)
4324
4325            if agg_func:
4326                agg_func_sql = self.sql(agg_func, comment=False)[:-1] + f" {text})"
4327                return self.maybe_comment(agg_func_sql, comments=agg_func.comments)
4328
4329        return f"{self.sql(expression, 'this')} {text}"
4330
4331    def _replace_line_breaks(self, string: str) -> str:
4332        """We don't want to extra indent line breaks so we temporarily replace them with sentinels."""
4333        if self.pretty:
4334            return string.replace("\n", self.SENTINEL_LINE_BREAK)
4335        return string
4336
4337    def copyparameter_sql(self, expression: exp.CopyParameter) -> str:
4338        option = self.sql(expression, "this")
4339
4340        if expression.expressions:
4341            upper = option.upper()
4342
4343            # Snowflake FILE_FORMAT options are separated by whitespace
4344            sep = " " if upper == "FILE_FORMAT" else ", "
4345
4346            # Databricks copy/format options do not set their list of values with EQ
4347            op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = "
4348            values = self.expressions(expression, flat=True, sep=sep)
4349            return f"{option}{op}({values})"
4350
4351        value = self.sql(expression, "expression")
4352
4353        if not value:
4354            return option
4355
4356        op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " "
4357
4358        return f"{option}{op}{value}"
4359
4360    def credentials_sql(self, expression: exp.Credentials) -> str:
4361        cred_expr = expression.args.get("credentials")
4362        if isinstance(cred_expr, exp.Literal):
4363            # Redshift case: CREDENTIALS <string>
4364            credentials = self.sql(expression, "credentials")
4365            credentials = f"CREDENTIALS {credentials}" if credentials else ""
4366        else:
4367            # Snowflake case: CREDENTIALS = (...)
4368            credentials = self.expressions(expression, key="credentials", flat=True, sep=" ")
4369            credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else ""
4370
4371        storage = self.sql(expression, "storage")
4372        storage = f"STORAGE_INTEGRATION = {storage}" if storage else ""
4373
4374        encryption = self.expressions(expression, key="encryption", flat=True, sep=" ")
4375        encryption = f" ENCRYPTION = ({encryption})" if encryption else ""
4376
4377        iam_role = self.sql(expression, "iam_role")
4378        iam_role = f"IAM_ROLE {iam_role}" if iam_role else ""
4379
4380        region = self.sql(expression, "region")
4381        region = f" REGION {region}" if region else ""
4382
4383        return f"{credentials}{storage}{encryption}{iam_role}{region}"
4384
4385    def copy_sql(self, expression: exp.Copy) -> str:
4386        this = self.sql(expression, "this")
4387        this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}"
4388
4389        credentials = self.sql(expression, "credentials")
4390        credentials = self.seg(credentials) if credentials else ""
4391        kind = self.seg("FROM" if expression.args.get("kind") else "TO")
4392        files = self.expressions(expression, key="files", flat=True)
4393
4394        sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " "
4395        params = self.expressions(
4396            expression,
4397            key="params",
4398            sep=sep,
4399            new_line=True,
4400            skip_last=True,
4401            skip_first=True,
4402            indent=self.COPY_PARAMS_ARE_WRAPPED,
4403        )
4404
4405        if params:
4406            if self.COPY_PARAMS_ARE_WRAPPED:
4407                params = f" WITH ({params})"
4408            elif not self.pretty:
4409                params = f" {params}"
4410
4411        return f"COPY{this}{kind} {files}{credentials}{params}"
4412
4413    def semicolon_sql(self, expression: exp.Semicolon) -> str:
4414        return ""
4415
4416    def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str:
4417        on_sql = "ON" if expression.args.get("on") else "OFF"
4418        filter_col: t.Optional[str] = self.sql(expression, "filter_column")
4419        filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None
4420        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
4421        retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None
4422
4423        if filter_col or retention_period:
4424            on_sql = self.func("ON", filter_col, retention_period)
4425
4426        return f"DATA_DELETION={on_sql}"
4427
4428    def maskingpolicycolumnconstraint_sql(
4429        self, expression: exp.MaskingPolicyColumnConstraint
4430    ) -> str:
4431        this = self.sql(expression, "this")
4432        expressions = self.expressions(expression, flat=True)
4433        expressions = f" USING ({expressions})" if expressions else ""
4434        return f"MASKING POLICY {this}{expressions}"
4435
4436    def gapfill_sql(self, expression: exp.GapFill) -> str:
4437        this = self.sql(expression, "this")
4438        this = f"TABLE {this}"
4439        return self.func("GAP_FILL", this, *[v for k, v in expression.args.items() if k != "this"])
4440
4441    def scope_resolution(self, rhs: str, scope_name: str) -> str:
4442        return self.func("SCOPE_RESOLUTION", scope_name or None, rhs)
4443
4444    def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str:
4445        this = self.sql(expression, "this")
4446        expr = expression.expression
4447
4448        if isinstance(expr, exp.Func):
4449            # T-SQL's CLR functions are case sensitive
4450            expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})"
4451        else:
4452            expr = self.sql(expression, "expression")
4453
4454        return self.scope_resolution(expr, this)
4455
4456    def parsejson_sql(self, expression: exp.ParseJSON) -> str:
4457        if self.PARSE_JSON_NAME is None:
4458            return self.sql(expression.this)
4459
4460        return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression)
4461
4462    def rand_sql(self, expression: exp.Rand) -> str:
4463        lower = self.sql(expression, "lower")
4464        upper = self.sql(expression, "upper")
4465
4466        if lower and upper:
4467            return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}"
4468        return self.func("RAND", expression.this)
4469
4470    def changes_sql(self, expression: exp.Changes) -> str:
4471        information = self.sql(expression, "information")
4472        information = f"INFORMATION => {information}"
4473        at_before = self.sql(expression, "at_before")
4474        at_before = f"{self.seg('')}{at_before}" if at_before else ""
4475        end = self.sql(expression, "end")
4476        end = f"{self.seg('')}{end}" if end else ""
4477
4478        return f"CHANGES ({information}){at_before}{end}"
4479
4480    def pad_sql(self, expression: exp.Pad) -> str:
4481        prefix = "L" if expression.args.get("is_left") else "R"
4482
4483        fill_pattern = self.sql(expression, "fill_pattern") or None
4484        if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED:
4485            fill_pattern = "' '"
4486
4487        return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)
4488
4489    def summarize_sql(self, expression: exp.Summarize) -> str:
4490        table = " TABLE" if expression.args.get("table") else ""
4491        return f"SUMMARIZE{table} {self.sql(expression.this)}"
4492
4493    def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str:
4494        generate_series = exp.GenerateSeries(**expression.args)
4495
4496        parent = expression.parent
4497        if isinstance(parent, (exp.Alias, exp.TableAlias)):
4498            parent = parent.parent
4499
4500        if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)):
4501            return self.sql(exp.Unnest(expressions=[generate_series]))
4502
4503        if isinstance(parent, exp.Select):
4504            self.unsupported("GenerateSeries projection unnesting is not supported.")
4505
4506        return self.sql(generate_series)
4507
4508    def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str:
4509        exprs = expression.expressions
4510        if not self.ARRAY_CONCAT_IS_VAR_LEN:
4511            rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs)
4512        else:
4513            rhs = self.expressions(expression)
4514
4515        return self.func(name, expression.this, rhs or None)
4516
4517    def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str:
4518        if self.SUPPORTS_CONVERT_TIMEZONE:
4519            return self.function_fallback_sql(expression)
4520
4521        source_tz = expression.args.get("source_tz")
4522        target_tz = expression.args.get("target_tz")
4523        timestamp = expression.args.get("timestamp")
4524
4525        if source_tz and timestamp:
4526            timestamp = exp.AtTimeZone(
4527                this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz
4528            )
4529
4530        expr = exp.AtTimeZone(this=timestamp, zone=target_tz)
4531
4532        return self.sql(expr)
4533
4534    def json_sql(self, expression: exp.JSON) -> str:
4535        this = self.sql(expression, "this")
4536        this = f" {this}" if this else ""
4537
4538        _with = expression.args.get("with")
4539
4540        if _with is None:
4541            with_sql = ""
4542        elif not _with:
4543            with_sql = " WITHOUT"
4544        else:
4545            with_sql = " WITH"
4546
4547        unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else ""
4548
4549        return f"JSON{this}{with_sql}{unique_sql}"
4550
4551    def jsonvalue_sql(self, expression: exp.JSONValue) -> str:
4552        def _generate_on_options(arg: t.Any) -> str:
4553            return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}"
4554
4555        path = self.sql(expression, "path")
4556        returning = self.sql(expression, "returning")
4557        returning = f" RETURNING {returning}" if returning else ""
4558
4559        on_condition = self.sql(expression, "on_condition")
4560        on_condition = f" {on_condition}" if on_condition else ""
4561
4562        return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}")
4563
4564    def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str:
4565        else_ = "ELSE " if expression.args.get("else_") else ""
4566        condition = self.sql(expression, "expression")
4567        condition = f"WHEN {condition} THEN " if condition else else_
4568        insert = self.sql(expression, "this")[len("INSERT") :].strip()
4569        return f"{condition}{insert}"
4570
4571    def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str:
4572        kind = self.sql(expression, "kind")
4573        expressions = self.seg(self.expressions(expression, sep=" "))
4574        res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}"
4575        return res
4576
4577    def oncondition_sql(self, expression: exp.OnCondition) -> str:
4578        # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR"
4579        empty = expression.args.get("empty")
4580        empty = (
4581            f"DEFAULT {empty} ON EMPTY"
4582            if isinstance(empty, exp.Expression)
4583            else self.sql(expression, "empty")
4584        )
4585
4586        error = expression.args.get("error")
4587        error = (
4588            f"DEFAULT {error} ON ERROR"
4589            if isinstance(error, exp.Expression)
4590            else self.sql(expression, "error")
4591        )
4592
4593        if error and empty:
4594            error = (
4595                f"{empty} {error}"
4596                if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR
4597                else f"{error} {empty}"
4598            )
4599            empty = ""
4600
4601        null = self.sql(expression, "null")
4602
4603        return f"{empty}{error}{null}"
4604
4605    def jsonextractquote_sql(self, expression: exp.JSONExtractQuote) -> str:
4606        scalar = " ON SCALAR STRING" if expression.args.get("scalar") else ""
4607        return f"{self.sql(expression, 'option')} QUOTES{scalar}"
4608
4609    def jsonexists_sql(self, expression: exp.JSONExists) -> str:
4610        this = self.sql(expression, "this")
4611        path = self.sql(expression, "path")
4612
4613        passing = self.expressions(expression, "passing")
4614        passing = f" PASSING {passing}" if passing else ""
4615
4616        on_condition = self.sql(expression, "on_condition")
4617        on_condition = f" {on_condition}" if on_condition else ""
4618
4619        path = f"{path}{passing}{on_condition}"
4620
4621        return self.func("JSON_EXISTS", this, path)
4622
4623    def arrayagg_sql(self, expression: exp.ArrayAgg) -> str:
4624        array_agg = self.function_fallback_sql(expression)
4625
4626        # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls
4627        # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB)
4628        if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"):
4629            parent = expression.parent
4630            if isinstance(parent, exp.Filter):
4631                parent_cond = parent.expression.this
4632                parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_()))
4633            else:
4634                this = expression.this
4635                # Do not add the filter if the input is not a column (e.g. literal, struct etc)
4636                if this.find(exp.Column):
4637                    # DISTINCT is already present in the agg function, do not propagate it to FILTER as well
4638                    this_sql = (
4639                        self.expressions(this)
4640                        if isinstance(this, exp.Distinct)
4641                        else self.sql(expression, "this")
4642                    )
4643
4644                    array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)"
4645
4646        return array_agg
4647
4648    def apply_sql(self, expression: exp.Apply) -> str:
4649        this = self.sql(expression, "this")
4650        expr = self.sql(expression, "expression")
4651
4652        return f"{this} APPLY({expr})"
4653
4654    def grant_sql(self, expression: exp.Grant) -> str:
4655        privileges_sql = self.expressions(expression, key="privileges", flat=True)
4656
4657        kind = self.sql(expression, "kind")
4658        kind = f" {kind}" if kind else ""
4659
4660        securable = self.sql(expression, "securable")
4661        securable = f" {securable}" if securable else ""
4662
4663        principals = self.expressions(expression, key="principals", flat=True)
4664
4665        grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else ""
4666
4667        return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}"
4668
4669    def grantprivilege_sql(self, expression: exp.GrantPrivilege):
4670        this = self.sql(expression, "this")
4671        columns = self.expressions(expression, flat=True)
4672        columns = f"({columns})" if columns else ""
4673
4674        return f"{this}{columns}"
4675
4676    def grantprincipal_sql(self, expression: exp.GrantPrincipal):
4677        this = self.sql(expression, "this")
4678
4679        kind = self.sql(expression, "kind")
4680        kind = f"{kind} " if kind else ""
4681
4682        return f"{kind}{this}"
4683
4684    def columns_sql(self, expression: exp.Columns):
4685        func = self.function_fallback_sql(expression)
4686        if expression.args.get("unpack"):
4687            func = f"*{func}"
4688
4689        return func
4690
4691    def overlay_sql(self, expression: exp.Overlay):
4692        this = self.sql(expression, "this")
4693        expr = self.sql(expression, "expression")
4694        from_sql = self.sql(expression, "from")
4695        for_sql = self.sql(expression, "for")
4696        for_sql = f" FOR {for_sql}" if for_sql else ""
4697
4698        return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})"
4699
4700    @unsupported_args("format")
4701    def todouble_sql(self, expression: exp.ToDouble) -> str:
4702        return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
4703
4704    def string_sql(self, expression: exp.String) -> str:
4705        this = expression.this
4706        zone = expression.args.get("zone")
4707
4708        if zone:
4709            # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>)
4710            # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC
4711            # set for source_tz to transpile the time conversion before the STRING cast
4712            this = exp.ConvertTimezone(
4713                source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this
4714            )
4715
4716        return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR))
4717
4718    def median_sql(self, expression: exp.Median):
4719        if not self.SUPPORTS_MEDIAN:
4720            return self.sql(
4721                exp.PercentileCont(this=expression.this, expression=exp.Literal.number(0.5))
4722            )
4723
4724        return self.function_fallback_sql(expression)
4725
4726    def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str:
4727        filler = self.sql(expression, "this")
4728        filler = f" {filler}" if filler else ""
4729        with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT"
4730        return f"TRUNCATE{filler} {with_count}"
4731
4732    def unixseconds_sql(self, expression: exp.UnixSeconds) -> str:
4733        if self.SUPPORTS_UNIX_SECONDS:
4734            return self.function_fallback_sql(expression)
4735
4736        start_ts = exp.cast(
4737            exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ
4738        )
4739
4740        return self.sql(
4741            exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS"))
4742        )
4743
4744    def arraysize_sql(self, expression: exp.ArraySize) -> str:
4745        dim = expression.expression
4746
4747        # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension)
4748        if dim and self.ARRAY_SIZE_DIM_REQUIRED is None:
4749            if not (dim.is_int and dim.name == "1"):
4750                self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH")
4751            dim = None
4752
4753        # If dimension is required but not specified, default initialize it
4754        if self.ARRAY_SIZE_DIM_REQUIRED and not dim:
4755            dim = exp.Literal.number(1)
4756
4757        return self.func(self.ARRAY_SIZE_NAME, expression.this, dim)
4758
4759    def attach_sql(self, expression: exp.Attach) -> str:
4760        this = self.sql(expression, "this")
4761        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
4762        expressions = self.expressions(expression)
4763        expressions = f" ({expressions})" if expressions else ""
4764
4765        return f"ATTACH{exists_sql} {this}{expressions}"
4766
4767    def detach_sql(self, expression: exp.Detach) -> str:
4768        this = self.sql(expression, "this")
4769        exists_sql = " IF EXISTS" if expression.args.get("exists") else ""
4770
4771        return f"DETACH{exists_sql} {this}"
4772
4773    def attachoption_sql(self, expression: exp.AttachOption) -> str:
4774        this = self.sql(expression, "this")
4775        value = self.sql(expression, "expression")
4776        value = f" {value}" if value else ""
4777        return f"{this}{value}"
4778
4779    def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str:
4780        this_sql = self.sql(expression, "this")
4781        if isinstance(expression.this, exp.Table):
4782            this_sql = f"TABLE {this_sql}"
4783
4784        return self.func(
4785            "FEATURES_AT_TIME",
4786            this_sql,
4787            expression.args.get("time"),
4788            expression.args.get("num_rows"),
4789            expression.args.get("ignore_feature_nulls"),
4790        )
4791
4792    def watermarkcolumnconstraint_sql(self, expression: exp.WatermarkColumnConstraint) -> str:
4793        return (
4794            f"WATERMARK FOR {self.sql(expression, 'this')} AS {self.sql(expression, 'expression')}"
4795        )
4796
4797    def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str:
4798        encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE"
4799        encode = f"{encode} {self.sql(expression, 'this')}"
4800
4801        properties = expression.args.get("properties")
4802        if properties:
4803            encode = f"{encode} {self.properties(properties)}"
4804
4805        return encode
4806
4807    def includeproperty_sql(self, expression: exp.IncludeProperty) -> str:
4808        this = self.sql(expression, "this")
4809        include = f"INCLUDE {this}"
4810
4811        column_def = self.sql(expression, "column_def")
4812        if column_def:
4813            include = f"{include} {column_def}"
4814
4815        alias = self.sql(expression, "alias")
4816        if alias:
4817            include = f"{include} AS {alias}"
4818
4819        return include
4820
4821    def xmlelement_sql(self, expression: exp.XMLElement) -> str:
4822        name = f"NAME {self.sql(expression, 'this')}"
4823        return self.func("XMLELEMENT", name, *expression.expressions)
4824
4825    def xmlkeyvalueoption_sql(self, expression: exp.XMLKeyValueOption) -> str:
4826        this = self.sql(expression, "this")
4827        expr = self.sql(expression, "expression")
4828        expr = f"({expr})" if expr else ""
4829        return f"{this}{expr}"
4830
4831    def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str:
4832        partitions = self.expressions(expression, "partition_expressions")
4833        create = self.expressions(expression, "create_expressions")
4834        return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}"
4835
4836    def partitionbyrangepropertydynamic_sql(
4837        self, expression: exp.PartitionByRangePropertyDynamic
4838    ) -> str:
4839        start = self.sql(expression, "start")
4840        end = self.sql(expression, "end")
4841
4842        every = expression.args["every"]
4843        if isinstance(every, exp.Interval) and every.this.is_string:
4844            every.this.replace(exp.Literal.number(every.name))
4845
4846        return f"START {self.wrap(start)} END {self.wrap(end)} EVERY {self.wrap(self.sql(every))}"
4847
4848    def unpivotcolumns_sql(self, expression: exp.UnpivotColumns) -> str:
4849        name = self.sql(expression, "this")
4850        values = self.expressions(expression, flat=True)
4851
4852        return f"NAME {name} VALUE {values}"
4853
4854    def analyzesample_sql(self, expression: exp.AnalyzeSample) -> str:
4855        kind = self.sql(expression, "kind")
4856        sample = self.sql(expression, "sample")
4857        return f"SAMPLE {sample} {kind}"
4858
4859    def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str:
4860        kind = self.sql(expression, "kind")
4861        option = self.sql(expression, "option")
4862        option = f" {option}" if option else ""
4863        this = self.sql(expression, "this")
4864        this = f" {this}" if this else ""
4865        columns = self.expressions(expression)
4866        columns = f" {columns}" if columns else ""
4867        return f"{kind}{option} STATISTICS{this}{columns}"
4868
4869    def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str:
4870        this = self.sql(expression, "this")
4871        columns = self.expressions(expression)
4872        inner_expression = self.sql(expression, "expression")
4873        inner_expression = f" {inner_expression}" if inner_expression else ""
4874        update_options = self.sql(expression, "update_options")
4875        update_options = f" {update_options} UPDATE" if update_options else ""
4876        return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}"
4877
4878    def analyzedelete_sql(self, expression: exp.AnalyzeDelete) -> str:
4879        kind = self.sql(expression, "kind")
4880        kind = f" {kind}" if kind else ""
4881        return f"DELETE{kind} STATISTICS"
4882
4883    def analyzelistchainedrows_sql(self, expression: exp.AnalyzeListChainedRows) -> str:
4884        inner_expression = self.sql(expression, "expression")
4885        return f"LIST CHAINED ROWS{inner_expression}"
4886
4887    def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str:
4888        kind = self.sql(expression, "kind")
4889        this = self.sql(expression, "this")
4890        this = f" {this}" if this else ""
4891        inner_expression = self.sql(expression, "expression")
4892        return f"VALIDATE {kind}{this}{inner_expression}"
4893
4894    def analyze_sql(self, expression: exp.Analyze) -> str:
4895        options = self.expressions(expression, key="options", sep=" ")
4896        options = f" {options}" if options else ""
4897        kind = self.sql(expression, "kind")
4898        kind = f" {kind}" if kind else ""
4899        this = self.sql(expression, "this")
4900        this = f" {this}" if this else ""
4901        mode = self.sql(expression, "mode")
4902        mode = f" {mode}" if mode else ""
4903        properties = self.sql(expression, "properties")
4904        properties = f" {properties}" if properties else ""
4905        partition = self.sql(expression, "partition")
4906        partition = f" {partition}" if partition else ""
4907        inner_expression = self.sql(expression, "expression")
4908        inner_expression = f" {inner_expression}" if inner_expression else ""
4909        return f"ANALYZE{options}{kind}{this}{partition}{mode}{inner_expression}{properties}"
4910
4911    def xmltable_sql(self, expression: exp.XMLTable) -> str:
4912        this = self.sql(expression, "this")
4913        namespaces = self.expressions(expression, key="namespaces")
4914        namespaces = f"XMLNAMESPACES({namespaces}), " if namespaces else ""
4915        passing = self.expressions(expression, key="passing")
4916        passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else ""
4917        columns = self.expressions(expression, key="columns")
4918        columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else ""
4919        by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else ""
4920        return f"XMLTABLE({self.sep('')}{self.indent(namespaces + this + passing + by_ref + columns)}{self.seg(')', sep='')}"
4921
4922    def xmlnamespace_sql(self, expression: exp.XMLNamespace) -> str:
4923        this = self.sql(expression, "this")
4924        return this if isinstance(expression.this, exp.Alias) else f"DEFAULT {this}"
4925
4926    def export_sql(self, expression: exp.Export) -> str:
4927        this = self.sql(expression, "this")
4928        connection = self.sql(expression, "connection")
4929        connection = f"WITH CONNECTION {connection} " if connection else ""
4930        options = self.sql(expression, "options")
4931        return f"EXPORT DATA {connection}{options} AS {this}"
4932
4933    def declare_sql(self, expression: exp.Declare) -> str:
4934        return f"DECLARE {self.expressions(expression, flat=True)}"
4935
4936    def declareitem_sql(self, expression: exp.DeclareItem) -> str:
4937        variable = self.sql(expression, "this")
4938        default = self.sql(expression, "default")
4939        default = f" = {default}" if default else ""
4940
4941        kind = self.sql(expression, "kind")
4942        if isinstance(expression.args.get("kind"), exp.Schema):
4943            kind = f"TABLE {kind}"
4944
4945        return f"{variable} AS {kind}{default}"
4946
4947    def recursivewithsearch_sql(self, expression: exp.RecursiveWithSearch) -> str:
4948        kind = self.sql(expression, "kind")
4949        this = self.sql(expression, "this")
4950        set = self.sql(expression, "expression")
4951        using = self.sql(expression, "using")
4952        using = f" USING {using}" if using else ""
4953
4954        kind_sql = kind if kind == "CYCLE" else f"SEARCH {kind} FIRST BY"
4955
4956        return f"{kind_sql} {this} SET {set}{using}"
4957
4958    def parameterizedagg_sql(self, expression: exp.ParameterizedAgg) -> str:
4959        params = self.expressions(expression, key="params", flat=True)
4960        return self.func(expression.name, *expression.expressions) + f"({params})"
4961
4962    def anonymousaggfunc_sql(self, expression: exp.AnonymousAggFunc) -> str:
4963        return self.func(expression.name, *expression.expressions)
4964
4965    def combinedaggfunc_sql(self, expression: exp.CombinedAggFunc) -> str:
4966        return self.anonymousaggfunc_sql(expression)
4967
4968    def combinedparameterizedagg_sql(self, expression: exp.CombinedParameterizedAgg) -> str:
4969        return self.parameterizedagg_sql(expression)
4970
4971    def show_sql(self, expression: exp.Show) -> str:
4972        self.unsupported("Unsupported SHOW statement")
4973        return ""
4974
4975    def get_put_sql(self, expression: exp.Put | exp.Get) -> str:
4976        # Snowflake GET/PUT statements:
4977        #   PUT <file> <internalStage> <properties>
4978        #   GET <internalStage> <file> <properties>
4979        props = expression.args.get("properties")
4980        props_sql = self.properties(props, prefix=" ", sep=" ", wrapped=False) if props else ""
4981        this = self.sql(expression, "this")
4982        target = self.sql(expression, "target")
4983
4984        if isinstance(expression, exp.Put):
4985            return f"PUT {this} {target}{props_sql}"
4986        else:
4987            return f"GET {target} {this}{props_sql}"
4988
4989    def translatecharacters_sql(self, expression: exp.TranslateCharacters):
4990        this = self.sql(expression, "this")
4991        expr = self.sql(expression, "expression")
4992        with_error = " WITH ERROR" if expression.args.get("with_error") else ""
4993        return f"TRANSLATE({this} USING {expr}{with_error})"
logger = <Logger sqlglot (WARNING)>
ESCAPED_UNICODE_RE = re.compile('\\\\(\\d+)')
UNSUPPORTED_TEMPLATE = "Argument '{}' is not supported for expression '{}' when targeting {}."
def unsupported_args( *args: Union[str, Tuple[str, str]]) -> Callable[[Callable[[~G, ~E], str]], Callable[[~G, ~E], str]]:
30def unsupported_args(
31    *args: t.Union[str, t.Tuple[str, str]],
32) -> t.Callable[[GeneratorMethod], GeneratorMethod]:
33    """
34    Decorator that can be used to mark certain args of an `Expression` subclass as unsupported.
35    It expects a sequence of argument names or pairs of the form (argument_name, diagnostic_msg).
36    """
37    diagnostic_by_arg: t.Dict[str, t.Optional[str]] = {}
38    for arg in args:
39        if isinstance(arg, str):
40            diagnostic_by_arg[arg] = None
41        else:
42            diagnostic_by_arg[arg[0]] = arg[1]
43
44    def decorator(func: GeneratorMethod) -> GeneratorMethod:
45        @wraps(func)
46        def _func(generator: G, expression: E) -> str:
47            expression_name = expression.__class__.__name__
48            dialect_name = generator.dialect.__class__.__name__
49
50            for arg_name, diagnostic in diagnostic_by_arg.items():
51                if expression.args.get(arg_name):
52                    diagnostic = diagnostic or UNSUPPORTED_TEMPLATE.format(
53                        arg_name, expression_name, dialect_name
54                    )
55                    generator.unsupported(diagnostic)
56
57            return func(generator, expression)
58
59        return _func
60
61    return decorator

Decorator that can be used to mark certain args of an Expression subclass as unsupported. It expects a sequence of argument names or pairs of the form (argument_name, diagnostic_msg).

class Generator:
  75class Generator(metaclass=_Generator):
  76    """
  77    Generator converts a given syntax tree to the corresponding SQL string.
  78
  79    Args:
  80        pretty: Whether to format the produced SQL string.
  81            Default: False.
  82        identify: Determines when an identifier should be quoted. Possible values are:
  83            False (default): Never quote, except in cases where it's mandatory by the dialect.
  84            True or 'always': Always quote.
  85            'safe': Only quote identifiers that are case insensitive.
  86        normalize: Whether to normalize identifiers to lowercase.
  87            Default: False.
  88        pad: The pad size in a formatted string. For example, this affects the indentation of
  89            a projection in a query, relative to its nesting level.
  90            Default: 2.
  91        indent: The indentation size in a formatted string. For example, this affects the
  92            indentation of subqueries and filters under a `WHERE` clause.
  93            Default: 2.
  94        normalize_functions: How to normalize function names. Possible values are:
  95            "upper" or True (default): Convert names to uppercase.
  96            "lower": Convert names to lowercase.
  97            False: Disables function name normalization.
  98        unsupported_level: Determines the generator's behavior when it encounters unsupported expressions.
  99            Default ErrorLevel.WARN.
 100        max_unsupported: Maximum number of unsupported messages to include in a raised UnsupportedError.
 101            This is only relevant if unsupported_level is ErrorLevel.RAISE.
 102            Default: 3
 103        leading_comma: Whether the comma is leading or trailing in select expressions.
 104            This is only relevant when generating in pretty mode.
 105            Default: False
 106        max_text_width: The max number of characters in a segment before creating new lines in pretty mode.
 107            The default is on the smaller end because the length only represents a segment and not the true
 108            line length.
 109            Default: 80
 110        comments: Whether to preserve comments in the output SQL code.
 111            Default: True
 112    """
 113
 114    TRANSFORMS: t.Dict[t.Type[exp.Expression], t.Callable[..., str]] = {
 115        **JSON_PATH_PART_TRANSFORMS,
 116        exp.AllowedValuesProperty: lambda self,
 117        e: f"ALLOWED_VALUES {self.expressions(e, flat=True)}",
 118        exp.AnalyzeColumns: lambda self, e: self.sql(e, "this"),
 119        exp.AnalyzeWith: lambda self, e: self.expressions(e, prefix="WITH ", sep=" "),
 120        exp.ArrayContainsAll: lambda self, e: self.binary(e, "@>"),
 121        exp.ArrayOverlaps: lambda self, e: self.binary(e, "&&"),
 122        exp.AutoRefreshProperty: lambda self, e: f"AUTO REFRESH {self.sql(e, 'this')}",
 123        exp.BackupProperty: lambda self, e: f"BACKUP {self.sql(e, 'this')}",
 124        exp.CaseSpecificColumnConstraint: lambda _,
 125        e: f"{'NOT ' if e.args.get('not_') else ''}CASESPECIFIC",
 126        exp.Ceil: lambda self, e: self.ceil_floor(e),
 127        exp.CharacterSetColumnConstraint: lambda self, e: f"CHARACTER SET {self.sql(e, 'this')}",
 128        exp.CharacterSetProperty: lambda self,
 129        e: f"{'DEFAULT ' if e.args.get('default') else ''}CHARACTER SET={self.sql(e, 'this')}",
 130        exp.ClusteredColumnConstraint: lambda self,
 131        e: f"CLUSTERED ({self.expressions(e, 'this', indent=False)})",
 132        exp.CollateColumnConstraint: lambda self, e: f"COLLATE {self.sql(e, 'this')}",
 133        exp.CommentColumnConstraint: lambda self, e: f"COMMENT {self.sql(e, 'this')}",
 134        exp.ConnectByRoot: lambda self, e: f"CONNECT_BY_ROOT {self.sql(e, 'this')}",
 135        exp.ConvertToCharset: lambda self, e: self.func(
 136            "CONVERT", e.this, e.args["dest"], e.args.get("source")
 137        ),
 138        exp.CopyGrantsProperty: lambda *_: "COPY GRANTS",
 139        exp.CredentialsProperty: lambda self,
 140        e: f"CREDENTIALS=({self.expressions(e, 'expressions', sep=' ')})",
 141        exp.DateFormatColumnConstraint: lambda self, e: f"FORMAT {self.sql(e, 'this')}",
 142        exp.DefaultColumnConstraint: lambda self, e: f"DEFAULT {self.sql(e, 'this')}",
 143        exp.DynamicProperty: lambda *_: "DYNAMIC",
 144        exp.EmptyProperty: lambda *_: "EMPTY",
 145        exp.EncodeColumnConstraint: lambda self, e: f"ENCODE {self.sql(e, 'this')}",
 146        exp.EnviromentProperty: lambda self, e: f"ENVIRONMENT ({self.expressions(e, flat=True)})",
 147        exp.EphemeralColumnConstraint: lambda self,
 148        e: f"EPHEMERAL{(' ' + self.sql(e, 'this')) if e.this else ''}",
 149        exp.ExcludeColumnConstraint: lambda self, e: f"EXCLUDE {self.sql(e, 'this').lstrip()}",
 150        exp.ExecuteAsProperty: lambda self, e: self.naked_property(e),
 151        exp.Except: lambda self, e: self.set_operations(e),
 152        exp.ExternalProperty: lambda *_: "EXTERNAL",
 153        exp.Floor: lambda self, e: self.ceil_floor(e),
 154        exp.Get: lambda self, e: self.get_put_sql(e),
 155        exp.GlobalProperty: lambda *_: "GLOBAL",
 156        exp.HeapProperty: lambda *_: "HEAP",
 157        exp.IcebergProperty: lambda *_: "ICEBERG",
 158        exp.InheritsProperty: lambda self, e: f"INHERITS ({self.expressions(e, flat=True)})",
 159        exp.InlineLengthColumnConstraint: lambda self, e: f"INLINE LENGTH {self.sql(e, 'this')}",
 160        exp.InputModelProperty: lambda self, e: f"INPUT{self.sql(e, 'this')}",
 161        exp.Intersect: lambda self, e: self.set_operations(e),
 162        exp.IntervalSpan: lambda self, e: f"{self.sql(e, 'this')} TO {self.sql(e, 'expression')}",
 163        exp.Int64: lambda self, e: self.sql(exp.cast(e.this, exp.DataType.Type.BIGINT)),
 164        exp.LanguageProperty: lambda self, e: self.naked_property(e),
 165        exp.LocationProperty: lambda self, e: self.naked_property(e),
 166        exp.LogProperty: lambda _, e: f"{'NO ' if e.args.get('no') else ''}LOG",
 167        exp.MaterializedProperty: lambda *_: "MATERIALIZED",
 168        exp.NonClusteredColumnConstraint: lambda self,
 169        e: f"NONCLUSTERED ({self.expressions(e, 'this', indent=False)})",
 170        exp.NoPrimaryIndexProperty: lambda *_: "NO PRIMARY INDEX",
 171        exp.NotForReplicationColumnConstraint: lambda *_: "NOT FOR REPLICATION",
 172        exp.OnCommitProperty: lambda _,
 173        e: f"ON COMMIT {'DELETE' if e.args.get('delete') else 'PRESERVE'} ROWS",
 174        exp.OnProperty: lambda self, e: f"ON {self.sql(e, 'this')}",
 175        exp.OnUpdateColumnConstraint: lambda self, e: f"ON UPDATE {self.sql(e, 'this')}",
 176        exp.Operator: lambda self, e: self.binary(e, ""),  # The operator is produced in `binary`
 177        exp.OutputModelProperty: lambda self, e: f"OUTPUT{self.sql(e, 'this')}",
 178        exp.PathColumnConstraint: lambda self, e: f"PATH {self.sql(e, 'this')}",
 179        exp.PartitionedByBucket: lambda self, e: self.func("BUCKET", e.this, e.expression),
 180        exp.PartitionByTruncate: lambda self, e: self.func("TRUNCATE", e.this, e.expression),
 181        exp.PivotAny: lambda self, e: f"ANY{self.sql(e, 'this')}",
 182        exp.ProjectionPolicyColumnConstraint: lambda self,
 183        e: f"PROJECTION POLICY {self.sql(e, 'this')}",
 184        exp.Put: lambda self, e: self.get_put_sql(e),
 185        exp.RemoteWithConnectionModelProperty: lambda self,
 186        e: f"REMOTE WITH CONNECTION {self.sql(e, 'this')}",
 187        exp.ReturnsProperty: lambda self, e: (
 188            "RETURNS NULL ON NULL INPUT" if e.args.get("null") else self.naked_property(e)
 189        ),
 190        exp.SampleProperty: lambda self, e: f"SAMPLE BY {self.sql(e, 'this')}",
 191        exp.SecureProperty: lambda *_: "SECURE",
 192        exp.SecurityProperty: lambda self, e: f"SECURITY {self.sql(e, 'this')}",
 193        exp.SetConfigProperty: lambda self, e: self.sql(e, "this"),
 194        exp.SetProperty: lambda _, e: f"{'MULTI' if e.args.get('multi') else ''}SET",
 195        exp.SettingsProperty: lambda self, e: f"SETTINGS{self.seg('')}{(self.expressions(e))}",
 196        exp.SharingProperty: lambda self, e: f"SHARING={self.sql(e, 'this')}",
 197        exp.SqlReadWriteProperty: lambda _, e: e.name,
 198        exp.SqlSecurityProperty: lambda _,
 199        e: f"SQL SECURITY {'DEFINER' if e.args.get('definer') else 'INVOKER'}",
 200        exp.StabilityProperty: lambda _, e: e.name,
 201        exp.Stream: lambda self, e: f"STREAM {self.sql(e, 'this')}",
 202        exp.StreamingTableProperty: lambda *_: "STREAMING",
 203        exp.StrictProperty: lambda *_: "STRICT",
 204        exp.SwapTable: lambda self, e: f"SWAP WITH {self.sql(e, 'this')}",
 205        exp.Tags: lambda self, e: f"TAG ({self.expressions(e, flat=True)})",
 206        exp.TemporaryProperty: lambda *_: "TEMPORARY",
 207        exp.TitleColumnConstraint: lambda self, e: f"TITLE {self.sql(e, 'this')}",
 208        exp.ToMap: lambda self, e: f"MAP {self.sql(e, 'this')}",
 209        exp.ToTableProperty: lambda self, e: f"TO {self.sql(e.this)}",
 210        exp.TransformModelProperty: lambda self, e: self.func("TRANSFORM", *e.expressions),
 211        exp.TransientProperty: lambda *_: "TRANSIENT",
 212        exp.Union: lambda self, e: self.set_operations(e),
 213        exp.UnloggedProperty: lambda *_: "UNLOGGED",
 214        exp.UsingTemplateProperty: lambda self, e: f"USING TEMPLATE {self.sql(e, 'this')}",
 215        exp.UsingData: lambda self, e: f"USING DATA {self.sql(e, 'this')}",
 216        exp.Uuid: lambda *_: "UUID()",
 217        exp.UppercaseColumnConstraint: lambda *_: "UPPERCASE",
 218        exp.VarMap: lambda self, e: self.func("MAP", e.args["keys"], e.args["values"]),
 219        exp.ViewAttributeProperty: lambda self, e: f"WITH {self.sql(e, 'this')}",
 220        exp.VolatileProperty: lambda *_: "VOLATILE",
 221        exp.WithJournalTableProperty: lambda self, e: f"WITH JOURNAL TABLE={self.sql(e, 'this')}",
 222        exp.WithProcedureOptions: lambda self, e: f"WITH {self.expressions(e, flat=True)}",
 223        exp.WithSchemaBindingProperty: lambda self, e: f"WITH SCHEMA {self.sql(e, 'this')}",
 224        exp.WithOperator: lambda self, e: f"{self.sql(e, 'this')} WITH {self.sql(e, 'op')}",
 225        exp.ForceProperty: lambda *_: "FORCE",
 226    }
 227
 228    # Whether null ordering is supported in order by
 229    # True: Full Support, None: No support, False: No support for certain cases
 230    # such as window specifications, aggregate functions etc
 231    NULL_ORDERING_SUPPORTED: t.Optional[bool] = True
 232
 233    # Whether ignore nulls is inside the agg or outside.
 234    # FIRST(x IGNORE NULLS) OVER vs FIRST (x) IGNORE NULLS OVER
 235    IGNORE_NULLS_IN_FUNC = False
 236
 237    # Whether locking reads (i.e. SELECT ... FOR UPDATE/SHARE) are supported
 238    LOCKING_READS_SUPPORTED = False
 239
 240    # Whether the EXCEPT and INTERSECT operations can return duplicates
 241    EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = True
 242
 243    # Wrap derived values in parens, usually standard but spark doesn't support it
 244    WRAP_DERIVED_VALUES = True
 245
 246    # Whether create function uses an AS before the RETURN
 247    CREATE_FUNCTION_RETURN_AS = True
 248
 249    # Whether MERGE ... WHEN MATCHED BY SOURCE is allowed
 250    MATCHED_BY_SOURCE = True
 251
 252    # Whether the INTERVAL expression works only with values like '1 day'
 253    SINGLE_STRING_INTERVAL = False
 254
 255    # Whether the plural form of date parts like day (i.e. "days") is supported in INTERVALs
 256    INTERVAL_ALLOWS_PLURAL_FORM = True
 257
 258    # Whether limit and fetch are supported (possible values: "ALL", "LIMIT", "FETCH")
 259    LIMIT_FETCH = "ALL"
 260
 261    # Whether limit and fetch allows expresions or just limits
 262    LIMIT_ONLY_LITERALS = False
 263
 264    # Whether a table is allowed to be renamed with a db
 265    RENAME_TABLE_WITH_DB = True
 266
 267    # The separator for grouping sets and rollups
 268    GROUPINGS_SEP = ","
 269
 270    # The string used for creating an index on a table
 271    INDEX_ON = "ON"
 272
 273    # Whether join hints should be generated
 274    JOIN_HINTS = True
 275
 276    # Whether table hints should be generated
 277    TABLE_HINTS = True
 278
 279    # Whether query hints should be generated
 280    QUERY_HINTS = True
 281
 282    # What kind of separator to use for query hints
 283    QUERY_HINT_SEP = ", "
 284
 285    # Whether comparing against booleans (e.g. x IS TRUE) is supported
 286    IS_BOOL_ALLOWED = True
 287
 288    # Whether to include the "SET" keyword in the "INSERT ... ON DUPLICATE KEY UPDATE" statement
 289    DUPLICATE_KEY_UPDATE_WITH_SET = True
 290
 291    # Whether to generate the limit as TOP <value> instead of LIMIT <value>
 292    LIMIT_IS_TOP = False
 293
 294    # Whether to generate INSERT INTO ... RETURNING or INSERT INTO RETURNING ...
 295    RETURNING_END = True
 296
 297    # Whether to generate an unquoted value for EXTRACT's date part argument
 298    EXTRACT_ALLOWS_QUOTES = True
 299
 300    # Whether TIMETZ / TIMESTAMPTZ will be generated using the "WITH TIME ZONE" syntax
 301    TZ_TO_WITH_TIME_ZONE = False
 302
 303    # Whether the NVL2 function is supported
 304    NVL2_SUPPORTED = True
 305
 306    # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax
 307    SELECT_KINDS: t.Tuple[str, ...] = ("STRUCT", "VALUE")
 308
 309    # Whether VALUES statements can be used as derived tables.
 310    # MySQL 5 and Redshift do not allow this, so when False, it will convert
 311    # SELECT * VALUES into SELECT UNION
 312    VALUES_AS_TABLE = True
 313
 314    # Whether the word COLUMN is included when adding a column with ALTER TABLE
 315    ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = True
 316
 317    # UNNEST WITH ORDINALITY (presto) instead of UNNEST WITH OFFSET (bigquery)
 318    UNNEST_WITH_ORDINALITY = True
 319
 320    # Whether FILTER (WHERE cond) can be used for conditional aggregation
 321    AGGREGATE_FILTER_SUPPORTED = True
 322
 323    # Whether JOIN sides (LEFT, RIGHT) are supported in conjunction with SEMI/ANTI join kinds
 324    SEMI_ANTI_JOIN_WITH_SIDE = True
 325
 326    # Whether to include the type of a computed column in the CREATE DDL
 327    COMPUTED_COLUMN_WITH_TYPE = True
 328
 329    # Whether CREATE TABLE .. COPY .. is supported. False means we'll generate CLONE instead of COPY
 330    SUPPORTS_TABLE_COPY = True
 331
 332    # Whether parentheses are required around the table sample's expression
 333    TABLESAMPLE_REQUIRES_PARENS = True
 334
 335    # Whether a table sample clause's size needs to be followed by the ROWS keyword
 336    TABLESAMPLE_SIZE_IS_ROWS = True
 337
 338    # The keyword(s) to use when generating a sample clause
 339    TABLESAMPLE_KEYWORDS = "TABLESAMPLE"
 340
 341    # Whether the TABLESAMPLE clause supports a method name, like BERNOULLI
 342    TABLESAMPLE_WITH_METHOD = True
 343
 344    # The keyword to use when specifying the seed of a sample clause
 345    TABLESAMPLE_SEED_KEYWORD = "SEED"
 346
 347    # Whether COLLATE is a function instead of a binary operator
 348    COLLATE_IS_FUNC = False
 349
 350    # Whether data types support additional specifiers like e.g. CHAR or BYTE (oracle)
 351    DATA_TYPE_SPECIFIERS_ALLOWED = False
 352
 353    # Whether conditions require booleans WHERE x = 0 vs WHERE x
 354    ENSURE_BOOLS = False
 355
 356    # Whether the "RECURSIVE" keyword is required when defining recursive CTEs
 357    CTE_RECURSIVE_KEYWORD_REQUIRED = True
 358
 359    # Whether CONCAT requires >1 arguments
 360    SUPPORTS_SINGLE_ARG_CONCAT = True
 361
 362    # Whether LAST_DAY function supports a date part argument
 363    LAST_DAY_SUPPORTS_DATE_PART = True
 364
 365    # Whether named columns are allowed in table aliases
 366    SUPPORTS_TABLE_ALIAS_COLUMNS = True
 367
 368    # Whether UNPIVOT aliases are Identifiers (False means they're Literals)
 369    UNPIVOT_ALIASES_ARE_IDENTIFIERS = True
 370
 371    # What delimiter to use for separating JSON key/value pairs
 372    JSON_KEY_VALUE_PAIR_SEP = ":"
 373
 374    # INSERT OVERWRITE TABLE x override
 375    INSERT_OVERWRITE = " OVERWRITE TABLE"
 376
 377    # Whether the SELECT .. INTO syntax is used instead of CTAS
 378    SUPPORTS_SELECT_INTO = False
 379
 380    # Whether UNLOGGED tables can be created
 381    SUPPORTS_UNLOGGED_TABLES = False
 382
 383    # Whether the CREATE TABLE LIKE statement is supported
 384    SUPPORTS_CREATE_TABLE_LIKE = True
 385
 386    # Whether the LikeProperty needs to be specified inside of the schema clause
 387    LIKE_PROPERTY_INSIDE_SCHEMA = False
 388
 389    # Whether DISTINCT can be followed by multiple args in an AggFunc. If not, it will be
 390    # transpiled into a series of CASE-WHEN-ELSE, ultimately using a tuple conseisting of the args
 391    MULTI_ARG_DISTINCT = True
 392
 393    # Whether the JSON extraction operators expect a value of type JSON
 394    JSON_TYPE_REQUIRED_FOR_EXTRACTION = False
 395
 396    # Whether bracketed keys like ["foo"] are supported in JSON paths
 397    JSON_PATH_BRACKETED_KEY_SUPPORTED = True
 398
 399    # Whether to escape keys using single quotes in JSON paths
 400    JSON_PATH_SINGLE_QUOTE_ESCAPE = False
 401
 402    # The JSONPathPart expressions supported by this dialect
 403    SUPPORTED_JSON_PATH_PARTS = ALL_JSON_PATH_PARTS.copy()
 404
 405    # Whether any(f(x) for x in array) can be implemented by this dialect
 406    CAN_IMPLEMENT_ARRAY_ANY = False
 407
 408    # Whether the function TO_NUMBER is supported
 409    SUPPORTS_TO_NUMBER = True
 410
 411    # Whether EXCLUDE in window specification is supported
 412    SUPPORTS_WINDOW_EXCLUDE = False
 413
 414    # Whether or not set op modifiers apply to the outer set op or select.
 415    # SELECT * FROM x UNION SELECT * FROM y LIMIT 1
 416    # True means limit 1 happens after the set op, False means it it happens on y.
 417    SET_OP_MODIFIERS = True
 418
 419    # Whether parameters from COPY statement are wrapped in parentheses
 420    COPY_PARAMS_ARE_WRAPPED = True
 421
 422    # Whether values of params are set with "=" token or empty space
 423    COPY_PARAMS_EQ_REQUIRED = False
 424
 425    # Whether COPY statement has INTO keyword
 426    COPY_HAS_INTO_KEYWORD = True
 427
 428    # Whether the conditional TRY(expression) function is supported
 429    TRY_SUPPORTED = True
 430
 431    # Whether the UESCAPE syntax in unicode strings is supported
 432    SUPPORTS_UESCAPE = True
 433
 434    # The keyword to use when generating a star projection with excluded columns
 435    STAR_EXCEPT = "EXCEPT"
 436
 437    # The HEX function name
 438    HEX_FUNC = "HEX"
 439
 440    # The keywords to use when prefixing & separating WITH based properties
 441    WITH_PROPERTIES_PREFIX = "WITH"
 442
 443    # Whether to quote the generated expression of exp.JsonPath
 444    QUOTE_JSON_PATH = True
 445
 446    # Whether the text pattern/fill (3rd) parameter of RPAD()/LPAD() is optional (defaults to space)
 447    PAD_FILL_PATTERN_IS_REQUIRED = False
 448
 449    # Whether a projection can explode into multiple rows, e.g. by unnesting an array.
 450    SUPPORTS_EXPLODING_PROJECTIONS = True
 451
 452    # Whether ARRAY_CONCAT can be generated with varlen args or if it should be reduced to 2-arg version
 453    ARRAY_CONCAT_IS_VAR_LEN = True
 454
 455    # Whether CONVERT_TIMEZONE() is supported; if not, it will be generated as exp.AtTimeZone
 456    SUPPORTS_CONVERT_TIMEZONE = False
 457
 458    # Whether MEDIAN(expr) is supported; if not, it will be generated as PERCENTILE_CONT(expr, 0.5)
 459    SUPPORTS_MEDIAN = True
 460
 461    # Whether UNIX_SECONDS(timestamp) is supported
 462    SUPPORTS_UNIX_SECONDS = False
 463
 464    # Whether to wrap <props> in `AlterSet`, e.g., ALTER ... SET (<props>)
 465    ALTER_SET_WRAPPED = False
 466
 467    # The name to generate for the JSONPath expression. If `None`, only `this` will be generated
 468    PARSE_JSON_NAME: t.Optional[str] = "PARSE_JSON"
 469
 470    # The function name of the exp.ArraySize expression
 471    ARRAY_SIZE_NAME: str = "ARRAY_LENGTH"
 472
 473    # The syntax to use when altering the type of a column
 474    ALTER_SET_TYPE = "SET DATA TYPE"
 475
 476    # Whether exp.ArraySize should generate the dimension arg too (valid for Postgres & DuckDB)
 477    # None -> Doesn't support it at all
 478    # False (DuckDB) -> Has backwards-compatible support, but preferably generated without
 479    # True (Postgres) -> Explicitly requires it
 480    ARRAY_SIZE_DIM_REQUIRED: t.Optional[bool] = None
 481
 482    TYPE_MAPPING = {
 483        exp.DataType.Type.DATETIME2: "TIMESTAMP",
 484        exp.DataType.Type.NCHAR: "CHAR",
 485        exp.DataType.Type.NVARCHAR: "VARCHAR",
 486        exp.DataType.Type.MEDIUMTEXT: "TEXT",
 487        exp.DataType.Type.LONGTEXT: "TEXT",
 488        exp.DataType.Type.TINYTEXT: "TEXT",
 489        exp.DataType.Type.BLOB: "VARBINARY",
 490        exp.DataType.Type.MEDIUMBLOB: "BLOB",
 491        exp.DataType.Type.LONGBLOB: "BLOB",
 492        exp.DataType.Type.TINYBLOB: "BLOB",
 493        exp.DataType.Type.INET: "INET",
 494        exp.DataType.Type.ROWVERSION: "VARBINARY",
 495        exp.DataType.Type.SMALLDATETIME: "TIMESTAMP",
 496    }
 497
 498    TIME_PART_SINGULARS = {
 499        "MICROSECONDS": "MICROSECOND",
 500        "SECONDS": "SECOND",
 501        "MINUTES": "MINUTE",
 502        "HOURS": "HOUR",
 503        "DAYS": "DAY",
 504        "WEEKS": "WEEK",
 505        "MONTHS": "MONTH",
 506        "QUARTERS": "QUARTER",
 507        "YEARS": "YEAR",
 508    }
 509
 510    AFTER_HAVING_MODIFIER_TRANSFORMS = {
 511        "cluster": lambda self, e: self.sql(e, "cluster"),
 512        "distribute": lambda self, e: self.sql(e, "distribute"),
 513        "sort": lambda self, e: self.sql(e, "sort"),
 514        "windows": lambda self, e: (
 515            self.seg("WINDOW ") + self.expressions(e, key="windows", flat=True)
 516            if e.args.get("windows")
 517            else ""
 518        ),
 519        "qualify": lambda self, e: self.sql(e, "qualify"),
 520    }
 521
 522    TOKEN_MAPPING: t.Dict[TokenType, str] = {}
 523
 524    STRUCT_DELIMITER = ("<", ">")
 525
 526    PARAMETER_TOKEN = "@"
 527    NAMED_PLACEHOLDER_TOKEN = ":"
 528
 529    EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: t.Set[str] = set()
 530
 531    PROPERTIES_LOCATION = {
 532        exp.AllowedValuesProperty: exp.Properties.Location.POST_SCHEMA,
 533        exp.AlgorithmProperty: exp.Properties.Location.POST_CREATE,
 534        exp.AutoIncrementProperty: exp.Properties.Location.POST_SCHEMA,
 535        exp.AutoRefreshProperty: exp.Properties.Location.POST_SCHEMA,
 536        exp.BackupProperty: exp.Properties.Location.POST_SCHEMA,
 537        exp.BlockCompressionProperty: exp.Properties.Location.POST_NAME,
 538        exp.CharacterSetProperty: exp.Properties.Location.POST_SCHEMA,
 539        exp.ChecksumProperty: exp.Properties.Location.POST_NAME,
 540        exp.CollateProperty: exp.Properties.Location.POST_SCHEMA,
 541        exp.CopyGrantsProperty: exp.Properties.Location.POST_SCHEMA,
 542        exp.Cluster: exp.Properties.Location.POST_SCHEMA,
 543        exp.ClusteredByProperty: exp.Properties.Location.POST_SCHEMA,
 544        exp.DistributedByProperty: exp.Properties.Location.POST_SCHEMA,
 545        exp.DuplicateKeyProperty: exp.Properties.Location.POST_SCHEMA,
 546        exp.DataBlocksizeProperty: exp.Properties.Location.POST_NAME,
 547        exp.DataDeletionProperty: exp.Properties.Location.POST_SCHEMA,
 548        exp.DefinerProperty: exp.Properties.Location.POST_CREATE,
 549        exp.DictRange: exp.Properties.Location.POST_SCHEMA,
 550        exp.DictProperty: exp.Properties.Location.POST_SCHEMA,
 551        exp.DynamicProperty: exp.Properties.Location.POST_CREATE,
 552        exp.DistKeyProperty: exp.Properties.Location.POST_SCHEMA,
 553        exp.DistStyleProperty: exp.Properties.Location.POST_SCHEMA,
 554        exp.EmptyProperty: exp.Properties.Location.POST_SCHEMA,
 555        exp.EncodeProperty: exp.Properties.Location.POST_EXPRESSION,
 556        exp.EngineProperty: exp.Properties.Location.POST_SCHEMA,
 557        exp.EnviromentProperty: exp.Properties.Location.POST_SCHEMA,
 558        exp.ExecuteAsProperty: exp.Properties.Location.POST_SCHEMA,
 559        exp.ExternalProperty: exp.Properties.Location.POST_CREATE,
 560        exp.FallbackProperty: exp.Properties.Location.POST_NAME,
 561        exp.FileFormatProperty: exp.Properties.Location.POST_WITH,
 562        exp.FreespaceProperty: exp.Properties.Location.POST_NAME,
 563        exp.GlobalProperty: exp.Properties.Location.POST_CREATE,
 564        exp.HeapProperty: exp.Properties.Location.POST_WITH,
 565        exp.InheritsProperty: exp.Properties.Location.POST_SCHEMA,
 566        exp.IcebergProperty: exp.Properties.Location.POST_CREATE,
 567        exp.IncludeProperty: exp.Properties.Location.POST_SCHEMA,
 568        exp.InputModelProperty: exp.Properties.Location.POST_SCHEMA,
 569        exp.IsolatedLoadingProperty: exp.Properties.Location.POST_NAME,
 570        exp.JournalProperty: exp.Properties.Location.POST_NAME,
 571        exp.LanguageProperty: exp.Properties.Location.POST_SCHEMA,
 572        exp.LikeProperty: exp.Properties.Location.POST_SCHEMA,
 573        exp.LocationProperty: exp.Properties.Location.POST_SCHEMA,
 574        exp.LockProperty: exp.Properties.Location.POST_SCHEMA,
 575        exp.LockingProperty: exp.Properties.Location.POST_ALIAS,
 576        exp.LogProperty: exp.Properties.Location.POST_NAME,
 577        exp.MaterializedProperty: exp.Properties.Location.POST_CREATE,
 578        exp.MergeBlockRatioProperty: exp.Properties.Location.POST_NAME,
 579        exp.NoPrimaryIndexProperty: exp.Properties.Location.POST_EXPRESSION,
 580        exp.OnProperty: exp.Properties.Location.POST_SCHEMA,
 581        exp.OnCommitProperty: exp.Properties.Location.POST_EXPRESSION,
 582        exp.Order: exp.Properties.Location.POST_SCHEMA,
 583        exp.OutputModelProperty: exp.Properties.Location.POST_SCHEMA,
 584        exp.PartitionedByProperty: exp.Properties.Location.POST_WITH,
 585        exp.PartitionedOfProperty: exp.Properties.Location.POST_SCHEMA,
 586        exp.PrimaryKey: exp.Properties.Location.POST_SCHEMA,
 587        exp.Property: exp.Properties.Location.POST_WITH,
 588        exp.RemoteWithConnectionModelProperty: exp.Properties.Location.POST_SCHEMA,
 589        exp.ReturnsProperty: exp.Properties.Location.POST_SCHEMA,
 590        exp.RowFormatProperty: exp.Properties.Location.POST_SCHEMA,
 591        exp.RowFormatDelimitedProperty: exp.Properties.Location.POST_SCHEMA,
 592        exp.RowFormatSerdeProperty: exp.Properties.Location.POST_SCHEMA,
 593        exp.SampleProperty: exp.Properties.Location.POST_SCHEMA,
 594        exp.SchemaCommentProperty: exp.Properties.Location.POST_SCHEMA,
 595        exp.SecureProperty: exp.Properties.Location.POST_CREATE,
 596        exp.SecurityProperty: exp.Properties.Location.POST_SCHEMA,
 597        exp.SerdeProperties: exp.Properties.Location.POST_SCHEMA,
 598        exp.Set: exp.Properties.Location.POST_SCHEMA,
 599        exp.SettingsProperty: exp.Properties.Location.POST_SCHEMA,
 600        exp.SetProperty: exp.Properties.Location.POST_CREATE,
 601        exp.SetConfigProperty: exp.Properties.Location.POST_SCHEMA,
 602        exp.SharingProperty: exp.Properties.Location.POST_EXPRESSION,
 603        exp.SequenceProperties: exp.Properties.Location.POST_EXPRESSION,
 604        exp.SortKeyProperty: exp.Properties.Location.POST_SCHEMA,
 605        exp.SqlReadWriteProperty: exp.Properties.Location.POST_SCHEMA,
 606        exp.SqlSecurityProperty: exp.Properties.Location.POST_CREATE,
 607        exp.StabilityProperty: exp.Properties.Location.POST_SCHEMA,
 608        exp.StorageHandlerProperty: exp.Properties.Location.POST_SCHEMA,
 609        exp.StreamingTableProperty: exp.Properties.Location.POST_CREATE,
 610        exp.StrictProperty: exp.Properties.Location.POST_SCHEMA,
 611        exp.Tags: exp.Properties.Location.POST_WITH,
 612        exp.TemporaryProperty: exp.Properties.Location.POST_CREATE,
 613        exp.ToTableProperty: exp.Properties.Location.POST_SCHEMA,
 614        exp.TransientProperty: exp.Properties.Location.POST_CREATE,
 615        exp.TransformModelProperty: exp.Properties.Location.POST_SCHEMA,
 616        exp.MergeTreeTTL: exp.Properties.Location.POST_SCHEMA,
 617        exp.UnloggedProperty: exp.Properties.Location.POST_CREATE,
 618        exp.UsingTemplateProperty: exp.Properties.Location.POST_SCHEMA,
 619        exp.ViewAttributeProperty: exp.Properties.Location.POST_SCHEMA,
 620        exp.VolatileProperty: exp.Properties.Location.POST_CREATE,
 621        exp.WithDataProperty: exp.Properties.Location.POST_EXPRESSION,
 622        exp.WithJournalTableProperty: exp.Properties.Location.POST_NAME,
 623        exp.WithProcedureOptions: exp.Properties.Location.POST_SCHEMA,
 624        exp.WithSchemaBindingProperty: exp.Properties.Location.POST_SCHEMA,
 625        exp.WithSystemVersioningProperty: exp.Properties.Location.POST_SCHEMA,
 626        exp.ForceProperty: exp.Properties.Location.POST_CREATE,
 627    }
 628
 629    # Keywords that can't be used as unquoted identifier names
 630    RESERVED_KEYWORDS: t.Set[str] = set()
 631
 632    # Expressions whose comments are separated from them for better formatting
 633    WITH_SEPARATED_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = (
 634        exp.Command,
 635        exp.Create,
 636        exp.Describe,
 637        exp.Delete,
 638        exp.Drop,
 639        exp.From,
 640        exp.Insert,
 641        exp.Join,
 642        exp.MultitableInserts,
 643        exp.Select,
 644        exp.SetOperation,
 645        exp.Update,
 646        exp.Where,
 647        exp.With,
 648    )
 649
 650    # Expressions that should not have their comments generated in maybe_comment
 651    EXCLUDE_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = (
 652        exp.Binary,
 653        exp.SetOperation,
 654    )
 655
 656    # Expressions that can remain unwrapped when appearing in the context of an INTERVAL
 657    UNWRAPPED_INTERVAL_VALUES: t.Tuple[t.Type[exp.Expression], ...] = (
 658        exp.Column,
 659        exp.Literal,
 660        exp.Neg,
 661        exp.Paren,
 662    )
 663
 664    PARAMETERIZABLE_TEXT_TYPES = {
 665        exp.DataType.Type.NVARCHAR,
 666        exp.DataType.Type.VARCHAR,
 667        exp.DataType.Type.CHAR,
 668        exp.DataType.Type.NCHAR,
 669    }
 670
 671    # Expressions that need to have all CTEs under them bubbled up to them
 672    EXPRESSIONS_WITHOUT_NESTED_CTES: t.Set[t.Type[exp.Expression]] = set()
 673
 674    RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS: t.Tuple[t.Type[exp.Expression], ...] = ()
 675
 676    SENTINEL_LINE_BREAK = "__SQLGLOT__LB__"
 677
 678    __slots__ = (
 679        "pretty",
 680        "identify",
 681        "normalize",
 682        "pad",
 683        "_indent",
 684        "normalize_functions",
 685        "unsupported_level",
 686        "max_unsupported",
 687        "leading_comma",
 688        "max_text_width",
 689        "comments",
 690        "dialect",
 691        "unsupported_messages",
 692        "_escaped_quote_end",
 693        "_escaped_identifier_end",
 694        "_next_name",
 695        "_identifier_start",
 696        "_identifier_end",
 697        "_quote_json_path_key_using_brackets",
 698    )
 699
 700    def __init__(
 701        self,
 702        pretty: t.Optional[bool] = None,
 703        identify: str | bool = False,
 704        normalize: bool = False,
 705        pad: int = 2,
 706        indent: int = 2,
 707        normalize_functions: t.Optional[str | bool] = None,
 708        unsupported_level: ErrorLevel = ErrorLevel.WARN,
 709        max_unsupported: int = 3,
 710        leading_comma: bool = False,
 711        max_text_width: int = 80,
 712        comments: bool = True,
 713        dialect: DialectType = None,
 714    ):
 715        import sqlglot
 716        from sqlglot.dialects import Dialect
 717
 718        self.pretty = pretty if pretty is not None else sqlglot.pretty
 719        self.identify = identify
 720        self.normalize = normalize
 721        self.pad = pad
 722        self._indent = indent
 723        self.unsupported_level = unsupported_level
 724        self.max_unsupported = max_unsupported
 725        self.leading_comma = leading_comma
 726        self.max_text_width = max_text_width
 727        self.comments = comments
 728        self.dialect = Dialect.get_or_raise(dialect)
 729
 730        # This is both a Dialect property and a Generator argument, so we prioritize the latter
 731        self.normalize_functions = (
 732            self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions
 733        )
 734
 735        self.unsupported_messages: t.List[str] = []
 736        self._escaped_quote_end: str = (
 737            self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END
 738        )
 739        self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2
 740
 741        self._next_name = name_sequence("_t")
 742
 743        self._identifier_start = self.dialect.IDENTIFIER_START
 744        self._identifier_end = self.dialect.IDENTIFIER_END
 745
 746        self._quote_json_path_key_using_brackets = True
 747
 748    def generate(self, expression: exp.Expression, copy: bool = True) -> str:
 749        """
 750        Generates the SQL string corresponding to the given syntax tree.
 751
 752        Args:
 753            expression: The syntax tree.
 754            copy: Whether to copy the expression. The generator performs mutations so
 755                it is safer to copy.
 756
 757        Returns:
 758            The SQL string corresponding to `expression`.
 759        """
 760        if copy:
 761            expression = expression.copy()
 762
 763        expression = self.preprocess(expression)
 764
 765        self.unsupported_messages = []
 766        sql = self.sql(expression).strip()
 767
 768        if self.pretty:
 769            sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n")
 770
 771        if self.unsupported_level == ErrorLevel.IGNORE:
 772            return sql
 773
 774        if self.unsupported_level == ErrorLevel.WARN:
 775            for msg in self.unsupported_messages:
 776                logger.warning(msg)
 777        elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages:
 778            raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported))
 779
 780        return sql
 781
 782    def preprocess(self, expression: exp.Expression) -> exp.Expression:
 783        """Apply generic preprocessing transformations to a given expression."""
 784        expression = self._move_ctes_to_top_level(expression)
 785
 786        if self.ENSURE_BOOLS:
 787            from sqlglot.transforms import ensure_bools
 788
 789            expression = ensure_bools(expression)
 790
 791        return expression
 792
 793    def _move_ctes_to_top_level(self, expression: E) -> E:
 794        if (
 795            not expression.parent
 796            and type(expression) in self.EXPRESSIONS_WITHOUT_NESTED_CTES
 797            and any(node.parent is not expression for node in expression.find_all(exp.With))
 798        ):
 799            from sqlglot.transforms import move_ctes_to_top_level
 800
 801            expression = move_ctes_to_top_level(expression)
 802        return expression
 803
 804    def unsupported(self, message: str) -> None:
 805        if self.unsupported_level == ErrorLevel.IMMEDIATE:
 806            raise UnsupportedError(message)
 807        self.unsupported_messages.append(message)
 808
 809    def sep(self, sep: str = " ") -> str:
 810        return f"{sep.strip()}\n" if self.pretty else sep
 811
 812    def seg(self, sql: str, sep: str = " ") -> str:
 813        return f"{self.sep(sep)}{sql}"
 814
 815    def sanitize_comment(self, comment: str) -> str:
 816        comment = " " + comment if comment[0].strip() else comment
 817        comment = comment + " " if comment[-1].strip() else comment
 818
 819        if not self.dialect.tokenizer_class.NESTED_COMMENTS:
 820            # Necessary workaround to avoid syntax errors due to nesting: /* ... */ ... */
 821            comment = comment.replace("*/", "* /")
 822
 823        return comment
 824
 825    def maybe_comment(
 826        self,
 827        sql: str,
 828        expression: t.Optional[exp.Expression] = None,
 829        comments: t.Optional[t.List[str]] = None,
 830        separated: bool = False,
 831    ) -> str:
 832        comments = (
 833            ((expression and expression.comments) if comments is None else comments)  # type: ignore
 834            if self.comments
 835            else None
 836        )
 837
 838        if not comments or isinstance(expression, self.EXCLUDE_COMMENTS):
 839            return sql
 840
 841        comments_sql = " ".join(
 842            f"/*{self.sanitize_comment(comment)}*/" for comment in comments if comment
 843        )
 844
 845        if not comments_sql:
 846            return sql
 847
 848        comments_sql = self._replace_line_breaks(comments_sql)
 849
 850        if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS):
 851            return (
 852                f"{self.sep()}{comments_sql}{sql}"
 853                if not sql or sql[0].isspace()
 854                else f"{comments_sql}{self.sep()}{sql}"
 855            )
 856
 857        return f"{sql} {comments_sql}"
 858
 859    def wrap(self, expression: exp.Expression | str) -> str:
 860        this_sql = (
 861            self.sql(expression)
 862            if isinstance(expression, exp.UNWRAPPED_QUERIES)
 863            else self.sql(expression, "this")
 864        )
 865        if not this_sql:
 866            return "()"
 867
 868        this_sql = self.indent(this_sql, level=1, pad=0)
 869        return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"
 870
 871    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
 872        original = self.identify
 873        self.identify = False
 874        result = func(*args, **kwargs)
 875        self.identify = original
 876        return result
 877
 878    def normalize_func(self, name: str) -> str:
 879        if self.normalize_functions == "upper" or self.normalize_functions is True:
 880            return name.upper()
 881        if self.normalize_functions == "lower":
 882            return name.lower()
 883        return name
 884
 885    def indent(
 886        self,
 887        sql: str,
 888        level: int = 0,
 889        pad: t.Optional[int] = None,
 890        skip_first: bool = False,
 891        skip_last: bool = False,
 892    ) -> str:
 893        if not self.pretty or not sql:
 894            return sql
 895
 896        pad = self.pad if pad is None else pad
 897        lines = sql.split("\n")
 898
 899        return "\n".join(
 900            (
 901                line
 902                if (skip_first and i == 0) or (skip_last and i == len(lines) - 1)
 903                else f"{' ' * (level * self._indent + pad)}{line}"
 904            )
 905            for i, line in enumerate(lines)
 906        )
 907
 908    def sql(
 909        self,
 910        expression: t.Optional[str | exp.Expression],
 911        key: t.Optional[str] = None,
 912        comment: bool = True,
 913    ) -> str:
 914        if not expression:
 915            return ""
 916
 917        if isinstance(expression, str):
 918            return expression
 919
 920        if key:
 921            value = expression.args.get(key)
 922            if value:
 923                return self.sql(value)
 924            return ""
 925
 926        transform = self.TRANSFORMS.get(expression.__class__)
 927
 928        if callable(transform):
 929            sql = transform(self, expression)
 930        elif isinstance(expression, exp.Expression):
 931            exp_handler_name = f"{expression.key}_sql"
 932
 933            if hasattr(self, exp_handler_name):
 934                sql = getattr(self, exp_handler_name)(expression)
 935            elif isinstance(expression, exp.Func):
 936                sql = self.function_fallback_sql(expression)
 937            elif isinstance(expression, exp.Property):
 938                sql = self.property_sql(expression)
 939            else:
 940                raise ValueError(f"Unsupported expression type {expression.__class__.__name__}")
 941        else:
 942            raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}")
 943
 944        return self.maybe_comment(sql, expression) if self.comments and comment else sql
 945
 946    def uncache_sql(self, expression: exp.Uncache) -> str:
 947        table = self.sql(expression, "this")
 948        exists_sql = " IF EXISTS" if expression.args.get("exists") else ""
 949        return f"UNCACHE TABLE{exists_sql} {table}"
 950
 951    def cache_sql(self, expression: exp.Cache) -> str:
 952        lazy = " LAZY" if expression.args.get("lazy") else ""
 953        table = self.sql(expression, "this")
 954        options = expression.args.get("options")
 955        options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else ""
 956        sql = self.sql(expression, "expression")
 957        sql = f" AS{self.sep()}{sql}" if sql else ""
 958        sql = f"CACHE{lazy} TABLE {table}{options}{sql}"
 959        return self.prepend_ctes(expression, sql)
 960
 961    def characterset_sql(self, expression: exp.CharacterSet) -> str:
 962        if isinstance(expression.parent, exp.Cast):
 963            return f"CHAR CHARACTER SET {self.sql(expression, 'this')}"
 964        default = "DEFAULT " if expression.args.get("default") else ""
 965        return f"{default}CHARACTER SET={self.sql(expression, 'this')}"
 966
 967    def column_parts(self, expression: exp.Column) -> str:
 968        return ".".join(
 969            self.sql(part)
 970            for part in (
 971                expression.args.get("catalog"),
 972                expression.args.get("db"),
 973                expression.args.get("table"),
 974                expression.args.get("this"),
 975            )
 976            if part
 977        )
 978
 979    def column_sql(self, expression: exp.Column) -> str:
 980        join_mark = " (+)" if expression.args.get("join_mark") else ""
 981
 982        if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS:
 983            join_mark = ""
 984            self.unsupported("Outer join syntax using the (+) operator is not supported.")
 985
 986        return f"{self.column_parts(expression)}{join_mark}"
 987
 988    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
 989        this = self.sql(expression, "this")
 990        this = f" {this}" if this else ""
 991        position = self.sql(expression, "position")
 992        return f"{position}{this}"
 993
 994    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
 995        column = self.sql(expression, "this")
 996        kind = self.sql(expression, "kind")
 997        constraints = self.expressions(expression, key="constraints", sep=" ", flat=True)
 998        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
 999        kind = f"{sep}{kind}" if kind else ""
1000        constraints = f" {constraints}" if constraints else ""
1001        position = self.sql(expression, "position")
1002        position = f" {position}" if position else ""
1003
1004        if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE:
1005            kind = ""
1006
1007        return f"{exists}{column}{kind}{constraints}{position}"
1008
1009    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
1010        this = self.sql(expression, "this")
1011        kind_sql = self.sql(expression, "kind").strip()
1012        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql
1013
1014    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
1015        this = self.sql(expression, "this")
1016        if expression.args.get("not_null"):
1017            persisted = " PERSISTED NOT NULL"
1018        elif expression.args.get("persisted"):
1019            persisted = " PERSISTED"
1020        else:
1021            persisted = ""
1022
1023        return f"AS {this}{persisted}"
1024
1025    def autoincrementcolumnconstraint_sql(self, _) -> str:
1026        return self.token_sql(TokenType.AUTO_INCREMENT)
1027
1028    def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str:
1029        if isinstance(expression.this, list):
1030            this = self.wrap(self.expressions(expression, key="this", flat=True))
1031        else:
1032            this = self.sql(expression, "this")
1033
1034        return f"COMPRESS {this}"
1035
1036    def generatedasidentitycolumnconstraint_sql(
1037        self, expression: exp.GeneratedAsIdentityColumnConstraint
1038    ) -> str:
1039        this = ""
1040        if expression.this is not None:
1041            on_null = " ON NULL" if expression.args.get("on_null") else ""
1042            this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}"
1043
1044        start = expression.args.get("start")
1045        start = f"START WITH {start}" if start else ""
1046        increment = expression.args.get("increment")
1047        increment = f" INCREMENT BY {increment}" if increment else ""
1048        minvalue = expression.args.get("minvalue")
1049        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
1050        maxvalue = expression.args.get("maxvalue")
1051        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
1052        cycle = expression.args.get("cycle")
1053        cycle_sql = ""
1054
1055        if cycle is not None:
1056            cycle_sql = f"{' NO' if not cycle else ''} CYCLE"
1057            cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql
1058
1059        sequence_opts = ""
1060        if start or increment or cycle_sql:
1061            sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}"
1062            sequence_opts = f" ({sequence_opts.strip()})"
1063
1064        expr = self.sql(expression, "expression")
1065        expr = f"({expr})" if expr else "IDENTITY"
1066
1067        return f"GENERATED{this} AS {expr}{sequence_opts}"
1068
1069    def generatedasrowcolumnconstraint_sql(
1070        self, expression: exp.GeneratedAsRowColumnConstraint
1071    ) -> str:
1072        start = "START" if expression.args.get("start") else "END"
1073        hidden = " HIDDEN" if expression.args.get("hidden") else ""
1074        return f"GENERATED ALWAYS AS ROW {start}{hidden}"
1075
1076    def periodforsystemtimeconstraint_sql(
1077        self, expression: exp.PeriodForSystemTimeConstraint
1078    ) -> str:
1079        return f"PERIOD FOR SYSTEM_TIME ({self.sql(expression, 'this')}, {self.sql(expression, 'expression')})"
1080
1081    def notnullcolumnconstraint_sql(self, expression: exp.NotNullColumnConstraint) -> str:
1082        return f"{'' if expression.args.get('allow_null') else 'NOT '}NULL"
1083
1084    def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str:
1085        desc = expression.args.get("desc")
1086        if desc is not None:
1087            return f"PRIMARY KEY{' DESC' if desc else ' ASC'}"
1088        options = self.expressions(expression, key="options", flat=True, sep=" ")
1089        options = f" {options}" if options else ""
1090        return f"PRIMARY KEY{options}"
1091
1092    def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str:
1093        this = self.sql(expression, "this")
1094        this = f" {this}" if this else ""
1095        index_type = expression.args.get("index_type")
1096        index_type = f" USING {index_type}" if index_type else ""
1097        on_conflict = self.sql(expression, "on_conflict")
1098        on_conflict = f" {on_conflict}" if on_conflict else ""
1099        nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else ""
1100        options = self.expressions(expression, key="options", flat=True, sep=" ")
1101        options = f" {options}" if options else ""
1102        return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}{options}"
1103
1104    def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
1105        return self.sql(expression, "this")
1106
1107    def create_sql(self, expression: exp.Create) -> str:
1108        kind = self.sql(expression, "kind")
1109        kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind
1110        properties = expression.args.get("properties")
1111        properties_locs = self.locate_properties(properties) if properties else defaultdict()
1112
1113        this = self.createable_sql(expression, properties_locs)
1114
1115        properties_sql = ""
1116        if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get(
1117            exp.Properties.Location.POST_WITH
1118        ):
1119            properties_sql = self.sql(
1120                exp.Properties(
1121                    expressions=[
1122                        *properties_locs[exp.Properties.Location.POST_SCHEMA],
1123                        *properties_locs[exp.Properties.Location.POST_WITH],
1124                    ]
1125                )
1126            )
1127
1128            if properties_locs.get(exp.Properties.Location.POST_SCHEMA):
1129                properties_sql = self.sep() + properties_sql
1130            elif not self.pretty:
1131                # Standalone POST_WITH properties need a leading whitespace in non-pretty mode
1132                properties_sql = f" {properties_sql}"
1133
1134        begin = " BEGIN" if expression.args.get("begin") else ""
1135        end = " END" if expression.args.get("end") else ""
1136
1137        expression_sql = self.sql(expression, "expression")
1138        if expression_sql:
1139            expression_sql = f"{begin}{self.sep()}{expression_sql}{end}"
1140
1141            if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return):
1142                postalias_props_sql = ""
1143                if properties_locs.get(exp.Properties.Location.POST_ALIAS):
1144                    postalias_props_sql = self.properties(
1145                        exp.Properties(
1146                            expressions=properties_locs[exp.Properties.Location.POST_ALIAS]
1147                        ),
1148                        wrapped=False,
1149                    )
1150                postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else ""
1151                expression_sql = f" AS{postalias_props_sql}{expression_sql}"
1152
1153        postindex_props_sql = ""
1154        if properties_locs.get(exp.Properties.Location.POST_INDEX):
1155            postindex_props_sql = self.properties(
1156                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]),
1157                wrapped=False,
1158                prefix=" ",
1159            )
1160
1161        indexes = self.expressions(expression, key="indexes", indent=False, sep=" ")
1162        indexes = f" {indexes}" if indexes else ""
1163        index_sql = indexes + postindex_props_sql
1164
1165        replace = " OR REPLACE" if expression.args.get("replace") else ""
1166        refresh = " OR REFRESH" if expression.args.get("refresh") else ""
1167        unique = " UNIQUE" if expression.args.get("unique") else ""
1168
1169        clustered = expression.args.get("clustered")
1170        if clustered is None:
1171            clustered_sql = ""
1172        elif clustered:
1173            clustered_sql = " CLUSTERED COLUMNSTORE"
1174        else:
1175            clustered_sql = " NONCLUSTERED COLUMNSTORE"
1176
1177        postcreate_props_sql = ""
1178        if properties_locs.get(exp.Properties.Location.POST_CREATE):
1179            postcreate_props_sql = self.properties(
1180                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]),
1181                sep=" ",
1182                prefix=" ",
1183                wrapped=False,
1184            )
1185
1186        modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql))
1187
1188        postexpression_props_sql = ""
1189        if properties_locs.get(exp.Properties.Location.POST_EXPRESSION):
1190            postexpression_props_sql = self.properties(
1191                exp.Properties(
1192                    expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION]
1193                ),
1194                sep=" ",
1195                prefix=" ",
1196                wrapped=False,
1197            )
1198
1199        concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else ""
1200        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
1201        no_schema_binding = (
1202            " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else ""
1203        )
1204
1205        clone = self.sql(expression, "clone")
1206        clone = f" {clone}" if clone else ""
1207
1208        if kind in self.EXPRESSION_PRECEDES_PROPERTIES_CREATABLES:
1209            properties_expression = f"{expression_sql}{properties_sql}"
1210        else:
1211            properties_expression = f"{properties_sql}{expression_sql}"
1212
1213        expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_expression}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}"
1214        return self.prepend_ctes(expression, expression_sql)
1215
1216    def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str:
1217        start = self.sql(expression, "start")
1218        start = f"START WITH {start}" if start else ""
1219        increment = self.sql(expression, "increment")
1220        increment = f" INCREMENT BY {increment}" if increment else ""
1221        minvalue = self.sql(expression, "minvalue")
1222        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
1223        maxvalue = self.sql(expression, "maxvalue")
1224        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
1225        owned = self.sql(expression, "owned")
1226        owned = f" OWNED BY {owned}" if owned else ""
1227
1228        cache = expression.args.get("cache")
1229        if cache is None:
1230            cache_str = ""
1231        elif cache is True:
1232            cache_str = " CACHE"
1233        else:
1234            cache_str = f" CACHE {cache}"
1235
1236        options = self.expressions(expression, key="options", flat=True, sep=" ")
1237        options = f" {options}" if options else ""
1238
1239        return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip()
1240
1241    def clone_sql(self, expression: exp.Clone) -> str:
1242        this = self.sql(expression, "this")
1243        shallow = "SHALLOW " if expression.args.get("shallow") else ""
1244        keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE"
1245        return f"{shallow}{keyword} {this}"
1246
1247    def describe_sql(self, expression: exp.Describe) -> str:
1248        style = expression.args.get("style")
1249        style = f" {style}" if style else ""
1250        partition = self.sql(expression, "partition")
1251        partition = f" {partition}" if partition else ""
1252        format = self.sql(expression, "format")
1253        format = f" {format}" if format else ""
1254
1255        return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}"
1256
1257    def heredoc_sql(self, expression: exp.Heredoc) -> str:
1258        tag = self.sql(expression, "tag")
1259        return f"${tag}${self.sql(expression, 'this')}${tag}$"
1260
1261    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
1262        with_ = self.sql(expression, "with")
1263        if with_:
1264            sql = f"{with_}{self.sep()}{sql}"
1265        return sql
1266
1267    def with_sql(self, expression: exp.With) -> str:
1268        sql = self.expressions(expression, flat=True)
1269        recursive = (
1270            "RECURSIVE "
1271            if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive")
1272            else ""
1273        )
1274        search = self.sql(expression, "search")
1275        search = f" {search}" if search else ""
1276
1277        return f"WITH {recursive}{sql}{search}"
1278
1279    def cte_sql(self, expression: exp.CTE) -> str:
1280        alias = expression.args.get("alias")
1281        if alias:
1282            alias.add_comments(expression.pop_comments())
1283
1284        alias_sql = self.sql(expression, "alias")
1285
1286        materialized = expression.args.get("materialized")
1287        if materialized is False:
1288            materialized = "NOT MATERIALIZED "
1289        elif materialized:
1290            materialized = "MATERIALIZED "
1291
1292        return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}"
1293
1294    def tablealias_sql(self, expression: exp.TableAlias) -> str:
1295        alias = self.sql(expression, "this")
1296        columns = self.expressions(expression, key="columns", flat=True)
1297        columns = f"({columns})" if columns else ""
1298
1299        if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS:
1300            columns = ""
1301            self.unsupported("Named columns are not supported in table alias.")
1302
1303        if not alias and not self.dialect.UNNEST_COLUMN_ONLY:
1304            alias = self._next_name()
1305
1306        return f"{alias}{columns}"
1307
1308    def bitstring_sql(self, expression: exp.BitString) -> str:
1309        this = self.sql(expression, "this")
1310        if self.dialect.BIT_START:
1311            return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}"
1312        return f"{int(this, 2)}"
1313
1314    def hexstring_sql(
1315        self, expression: exp.HexString, binary_function_repr: t.Optional[str] = None
1316    ) -> str:
1317        this = self.sql(expression, "this")
1318        is_integer_type = expression.args.get("is_integer")
1319
1320        if (is_integer_type and not self.dialect.HEX_STRING_IS_INTEGER_TYPE) or (
1321            not self.dialect.HEX_START and not binary_function_repr
1322        ):
1323            # Integer representation will be returned if:
1324            # - The read dialect treats the hex value as integer literal but not the write
1325            # - The transpilation is not supported (write dialect hasn't set HEX_START or the param flag)
1326            return f"{int(this, 16)}"
1327
1328        if not is_integer_type:
1329            # Read dialect treats the hex value as BINARY/BLOB
1330            if binary_function_repr:
1331                # The write dialect supports the transpilation to its equivalent BINARY/BLOB
1332                return self.func(binary_function_repr, exp.Literal.string(this))
1333            if self.dialect.HEX_STRING_IS_INTEGER_TYPE:
1334                # The write dialect does not support the transpilation, it'll treat the hex value as INTEGER
1335                self.unsupported("Unsupported transpilation from BINARY/BLOB hex string")
1336
1337        return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"
1338
1339    def bytestring_sql(self, expression: exp.ByteString) -> str:
1340        this = self.sql(expression, "this")
1341        if self.dialect.BYTE_START:
1342            return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}"
1343        return this
1344
1345    def unicodestring_sql(self, expression: exp.UnicodeString) -> str:
1346        this = self.sql(expression, "this")
1347        escape = expression.args.get("escape")
1348
1349        if self.dialect.UNICODE_START:
1350            escape_substitute = r"\\\1"
1351            left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END
1352        else:
1353            escape_substitute = r"\\u\1"
1354            left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END
1355
1356        if escape:
1357            escape_pattern = re.compile(rf"{escape.name}(\d+)")
1358            escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else ""
1359        else:
1360            escape_pattern = ESCAPED_UNICODE_RE
1361            escape_sql = ""
1362
1363        if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE):
1364            this = escape_pattern.sub(escape_substitute, this)
1365
1366        return f"{left_quote}{this}{right_quote}{escape_sql}"
1367
1368    def rawstring_sql(self, expression: exp.RawString) -> str:
1369        string = expression.this
1370        if "\\" in self.dialect.tokenizer_class.STRING_ESCAPES:
1371            string = string.replace("\\", "\\\\")
1372
1373        string = self.escape_str(string, escape_backslash=False)
1374        return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}"
1375
1376    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
1377        this = self.sql(expression, "this")
1378        specifier = self.sql(expression, "expression")
1379        specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else ""
1380        return f"{this}{specifier}"
1381
1382    def datatype_sql(self, expression: exp.DataType) -> str:
1383        nested = ""
1384        values = ""
1385        interior = self.expressions(expression, flat=True)
1386
1387        type_value = expression.this
1388        if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"):
1389            type_sql = self.sql(expression, "kind")
1390        else:
1391            type_sql = (
1392                self.TYPE_MAPPING.get(type_value, type_value.value)
1393                if isinstance(type_value, exp.DataType.Type)
1394                else type_value
1395            )
1396
1397        if interior:
1398            if expression.args.get("nested"):
1399                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
1400                if expression.args.get("values") is not None:
1401                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
1402                    values = self.expressions(expression, key="values", flat=True)
1403                    values = f"{delimiters[0]}{values}{delimiters[1]}"
1404            elif type_value == exp.DataType.Type.INTERVAL:
1405                nested = f" {interior}"
1406            else:
1407                nested = f"({interior})"
1408
1409        type_sql = f"{type_sql}{nested}{values}"
1410        if self.TZ_TO_WITH_TIME_ZONE and type_value in (
1411            exp.DataType.Type.TIMETZ,
1412            exp.DataType.Type.TIMESTAMPTZ,
1413        ):
1414            type_sql = f"{type_sql} WITH TIME ZONE"
1415
1416        return type_sql
1417
1418    def directory_sql(self, expression: exp.Directory) -> str:
1419        local = "LOCAL " if expression.args.get("local") else ""
1420        row_format = self.sql(expression, "row_format")
1421        row_format = f" {row_format}" if row_format else ""
1422        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"
1423
1424    def delete_sql(self, expression: exp.Delete) -> str:
1425        this = self.sql(expression, "this")
1426        this = f" FROM {this}" if this else ""
1427        using = self.sql(expression, "using")
1428        using = f" USING {using}" if using else ""
1429        cluster = self.sql(expression, "cluster")
1430        cluster = f" {cluster}" if cluster else ""
1431        where = self.sql(expression, "where")
1432        returning = self.sql(expression, "returning")
1433        limit = self.sql(expression, "limit")
1434        tables = self.expressions(expression, key="tables")
1435        tables = f" {tables}" if tables else ""
1436        if self.RETURNING_END:
1437            expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}"
1438        else:
1439            expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}"
1440        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")
1441
1442    def drop_sql(self, expression: exp.Drop) -> str:
1443        this = self.sql(expression, "this")
1444        expressions = self.expressions(expression, flat=True)
1445        expressions = f" ({expressions})" if expressions else ""
1446        kind = expression.args["kind"]
1447        kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind
1448        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
1449        concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else ""
1450        on_cluster = self.sql(expression, "cluster")
1451        on_cluster = f" {on_cluster}" if on_cluster else ""
1452        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
1453        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
1454        cascade = " CASCADE" if expression.args.get("cascade") else ""
1455        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
1456        purge = " PURGE" if expression.args.get("purge") else ""
1457        return f"DROP{temporary}{materialized} {kind}{concurrently_sql}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}"
1458
1459    def set_operation(self, expression: exp.SetOperation) -> str:
1460        op_type = type(expression)
1461        op_name = op_type.key.upper()
1462
1463        distinct = expression.args.get("distinct")
1464        if (
1465            distinct is False
1466            and op_type in (exp.Except, exp.Intersect)
1467            and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE
1468        ):
1469            self.unsupported(f"{op_name} ALL is not supported")
1470
1471        default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type]
1472
1473        if distinct is None:
1474            distinct = default_distinct
1475            if distinct is None:
1476                self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified")
1477
1478        if distinct is default_distinct:
1479            distinct_or_all = ""
1480        else:
1481            distinct_or_all = " DISTINCT" if distinct else " ALL"
1482
1483        side_kind = " ".join(filter(None, [expression.side, expression.kind]))
1484        side_kind = f"{side_kind} " if side_kind else ""
1485
1486        by_name = " BY NAME" if expression.args.get("by_name") else ""
1487        on = self.expressions(expression, key="on", flat=True)
1488        on = f" ON ({on})" if on else ""
1489
1490        return f"{side_kind}{op_name}{distinct_or_all}{by_name}{on}"
1491
1492    def set_operations(self, expression: exp.SetOperation) -> str:
1493        if not self.SET_OP_MODIFIERS:
1494            limit = expression.args.get("limit")
1495            order = expression.args.get("order")
1496
1497            if limit or order:
1498                select = self._move_ctes_to_top_level(
1499                    exp.subquery(expression, "_l_0", copy=False).select("*", copy=False)
1500                )
1501
1502                if limit:
1503                    select = select.limit(limit.pop(), copy=False)
1504                if order:
1505                    select = select.order_by(order.pop(), copy=False)
1506                return self.sql(select)
1507
1508        sqls: t.List[str] = []
1509        stack: t.List[t.Union[str, exp.Expression]] = [expression]
1510
1511        while stack:
1512            node = stack.pop()
1513
1514            if isinstance(node, exp.SetOperation):
1515                stack.append(node.expression)
1516                stack.append(
1517                    self.maybe_comment(
1518                        self.set_operation(node), comments=node.comments, separated=True
1519                    )
1520                )
1521                stack.append(node.this)
1522            else:
1523                sqls.append(self.sql(node))
1524
1525        this = self.sep().join(sqls)
1526        this = self.query_modifiers(expression, this)
1527        return self.prepend_ctes(expression, this)
1528
1529    def fetch_sql(self, expression: exp.Fetch) -> str:
1530        direction = expression.args.get("direction")
1531        direction = f" {direction}" if direction else ""
1532        count = self.sql(expression, "count")
1533        count = f" {count}" if count else ""
1534        limit_options = self.sql(expression, "limit_options")
1535        limit_options = f"{limit_options}" if limit_options else " ROWS ONLY"
1536        return f"{self.seg('FETCH')}{direction}{count}{limit_options}"
1537
1538    def limitoptions_sql(self, expression: exp.LimitOptions) -> str:
1539        percent = " PERCENT" if expression.args.get("percent") else ""
1540        rows = " ROWS" if expression.args.get("rows") else ""
1541        with_ties = " WITH TIES" if expression.args.get("with_ties") else ""
1542        if not with_ties and rows:
1543            with_ties = " ONLY"
1544        return f"{percent}{rows}{with_ties}"
1545
1546    def filter_sql(self, expression: exp.Filter) -> str:
1547        if self.AGGREGATE_FILTER_SUPPORTED:
1548            this = self.sql(expression, "this")
1549            where = self.sql(expression, "expression").strip()
1550            return f"{this} FILTER({where})"
1551
1552        agg = expression.this
1553        agg_arg = agg.this
1554        cond = expression.expression.this
1555        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
1556        return self.sql(agg)
1557
1558    def hint_sql(self, expression: exp.Hint) -> str:
1559        if not self.QUERY_HINTS:
1560            self.unsupported("Hints are not supported")
1561            return ""
1562
1563        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"
1564
1565    def indexparameters_sql(self, expression: exp.IndexParameters) -> str:
1566        using = self.sql(expression, "using")
1567        using = f" USING {using}" if using else ""
1568        columns = self.expressions(expression, key="columns", flat=True)
1569        columns = f"({columns})" if columns else ""
1570        partition_by = self.expressions(expression, key="partition_by", flat=True)
1571        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
1572        where = self.sql(expression, "where")
1573        include = self.expressions(expression, key="include", flat=True)
1574        if include:
1575            include = f" INCLUDE ({include})"
1576        with_storage = self.expressions(expression, key="with_storage", flat=True)
1577        with_storage = f" WITH ({with_storage})" if with_storage else ""
1578        tablespace = self.sql(expression, "tablespace")
1579        tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else ""
1580        on = self.sql(expression, "on")
1581        on = f" ON {on}" if on else ""
1582
1583        return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"
1584
1585    def index_sql(self, expression: exp.Index) -> str:
1586        unique = "UNIQUE " if expression.args.get("unique") else ""
1587        primary = "PRIMARY " if expression.args.get("primary") else ""
1588        amp = "AMP " if expression.args.get("amp") else ""
1589        name = self.sql(expression, "this")
1590        name = f"{name} " if name else ""
1591        table = self.sql(expression, "table")
1592        table = f"{self.INDEX_ON} {table}" if table else ""
1593
1594        index = "INDEX " if not table else ""
1595
1596        params = self.sql(expression, "params")
1597        return f"{unique}{primary}{amp}{index}{name}{table}{params}"
1598
1599    def identifier_sql(self, expression: exp.Identifier) -> str:
1600        text = expression.name
1601        lower = text.lower()
1602        text = lower if self.normalize and not expression.quoted else text
1603        text = text.replace(self._identifier_end, self._escaped_identifier_end)
1604        if (
1605            expression.quoted
1606            or self.dialect.can_identify(text, self.identify)
1607            or lower in self.RESERVED_KEYWORDS
1608            or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
1609        ):
1610            text = f"{self._identifier_start}{text}{self._identifier_end}"
1611        return text
1612
1613    def hex_sql(self, expression: exp.Hex) -> str:
1614        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
1615        if self.dialect.HEX_LOWERCASE:
1616            text = self.func("LOWER", text)
1617
1618        return text
1619
1620    def lowerhex_sql(self, expression: exp.LowerHex) -> str:
1621        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
1622        if not self.dialect.HEX_LOWERCASE:
1623            text = self.func("LOWER", text)
1624        return text
1625
1626    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
1627        input_format = self.sql(expression, "input_format")
1628        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
1629        output_format = self.sql(expression, "output_format")
1630        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
1631        return self.sep().join((input_format, output_format))
1632
1633    def national_sql(self, expression: exp.National, prefix: str = "N") -> str:
1634        string = self.sql(exp.Literal.string(expression.name))
1635        return f"{prefix}{string}"
1636
1637    def partition_sql(self, expression: exp.Partition) -> str:
1638        partition_keyword = "SUBPARTITION" if expression.args.get("subpartition") else "PARTITION"
1639        return f"{partition_keyword}({self.expressions(expression, flat=True)})"
1640
1641    def properties_sql(self, expression: exp.Properties) -> str:
1642        root_properties = []
1643        with_properties = []
1644
1645        for p in expression.expressions:
1646            p_loc = self.PROPERTIES_LOCATION[p.__class__]
1647            if p_loc == exp.Properties.Location.POST_WITH:
1648                with_properties.append(p)
1649            elif p_loc == exp.Properties.Location.POST_SCHEMA:
1650                root_properties.append(p)
1651
1652        root_props = self.root_properties(exp.Properties(expressions=root_properties))
1653        with_props = self.with_properties(exp.Properties(expressions=with_properties))
1654
1655        if root_props and with_props and not self.pretty:
1656            with_props = " " + with_props
1657
1658        return root_props + with_props
1659
1660    def root_properties(self, properties: exp.Properties) -> str:
1661        if properties.expressions:
1662            return self.expressions(properties, indent=False, sep=" ")
1663        return ""
1664
1665    def properties(
1666        self,
1667        properties: exp.Properties,
1668        prefix: str = "",
1669        sep: str = ", ",
1670        suffix: str = "",
1671        wrapped: bool = True,
1672    ) -> str:
1673        if properties.expressions:
1674            expressions = self.expressions(properties, sep=sep, indent=False)
1675            if expressions:
1676                expressions = self.wrap(expressions) if wrapped else expressions
1677                return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}"
1678        return ""
1679
1680    def with_properties(self, properties: exp.Properties) -> str:
1681        return self.properties(properties, prefix=self.seg(self.WITH_PROPERTIES_PREFIX, sep=""))
1682
1683    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
1684        properties_locs = defaultdict(list)
1685        for p in properties.expressions:
1686            p_loc = self.PROPERTIES_LOCATION[p.__class__]
1687            if p_loc != exp.Properties.Location.UNSUPPORTED:
1688                properties_locs[p_loc].append(p)
1689            else:
1690                self.unsupported(f"Unsupported property {p.key}")
1691
1692        return properties_locs
1693
1694    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
1695        if isinstance(expression.this, exp.Dot):
1696            return self.sql(expression, "this")
1697        return f"'{expression.name}'" if string_key else expression.name
1698
1699    def property_sql(self, expression: exp.Property) -> str:
1700        property_cls = expression.__class__
1701        if property_cls == exp.Property:
1702            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
1703
1704        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
1705        if not property_name:
1706            self.unsupported(f"Unsupported property {expression.key}")
1707
1708        return f"{property_name}={self.sql(expression, 'this')}"
1709
1710    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
1711        if self.SUPPORTS_CREATE_TABLE_LIKE:
1712            options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
1713            options = f" {options}" if options else ""
1714
1715            like = f"LIKE {self.sql(expression, 'this')}{options}"
1716            if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema):
1717                like = f"({like})"
1718
1719            return like
1720
1721        if expression.expressions:
1722            self.unsupported("Transpilation of LIKE property options is unsupported")
1723
1724        select = exp.select("*").from_(expression.this).limit(0)
1725        return f"AS {self.sql(select)}"
1726
1727    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
1728        no = "NO " if expression.args.get("no") else ""
1729        protection = " PROTECTION" if expression.args.get("protection") else ""
1730        return f"{no}FALLBACK{protection}"
1731
1732    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
1733        no = "NO " if expression.args.get("no") else ""
1734        local = expression.args.get("local")
1735        local = f"{local} " if local else ""
1736        dual = "DUAL " if expression.args.get("dual") else ""
1737        before = "BEFORE " if expression.args.get("before") else ""
1738        after = "AFTER " if expression.args.get("after") else ""
1739        return f"{no}{local}{dual}{before}{after}JOURNAL"
1740
1741    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
1742        freespace = self.sql(expression, "this")
1743        percent = " PERCENT" if expression.args.get("percent") else ""
1744        return f"FREESPACE={freespace}{percent}"
1745
1746    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
1747        if expression.args.get("default"):
1748            property = "DEFAULT"
1749        elif expression.args.get("on"):
1750            property = "ON"
1751        else:
1752            property = "OFF"
1753        return f"CHECKSUM={property}"
1754
1755    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
1756        if expression.args.get("no"):
1757            return "NO MERGEBLOCKRATIO"
1758        if expression.args.get("default"):
1759            return "DEFAULT MERGEBLOCKRATIO"
1760
1761        percent = " PERCENT" if expression.args.get("percent") else ""
1762        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"
1763
1764    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
1765        default = expression.args.get("default")
1766        minimum = expression.args.get("minimum")
1767        maximum = expression.args.get("maximum")
1768        if default or minimum or maximum:
1769            if default:
1770                prop = "DEFAULT"
1771            elif minimum:
1772                prop = "MINIMUM"
1773            else:
1774                prop = "MAXIMUM"
1775            return f"{prop} DATABLOCKSIZE"
1776        units = expression.args.get("units")
1777        units = f" {units}" if units else ""
1778        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"
1779
1780    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
1781        autotemp = expression.args.get("autotemp")
1782        always = expression.args.get("always")
1783        default = expression.args.get("default")
1784        manual = expression.args.get("manual")
1785        never = expression.args.get("never")
1786
1787        if autotemp is not None:
1788            prop = f"AUTOTEMP({self.expressions(autotemp)})"
1789        elif always:
1790            prop = "ALWAYS"
1791        elif default:
1792            prop = "DEFAULT"
1793        elif manual:
1794            prop = "MANUAL"
1795        elif never:
1796            prop = "NEVER"
1797        return f"BLOCKCOMPRESSION={prop}"
1798
1799    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
1800        no = expression.args.get("no")
1801        no = " NO" if no else ""
1802        concurrent = expression.args.get("concurrent")
1803        concurrent = " CONCURRENT" if concurrent else ""
1804        target = self.sql(expression, "target")
1805        target = f" {target}" if target else ""
1806        return f"WITH{no}{concurrent} ISOLATED LOADING{target}"
1807
1808    def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str:
1809        if isinstance(expression.this, list):
1810            return f"IN ({self.expressions(expression, key='this', flat=True)})"
1811        if expression.this:
1812            modulus = self.sql(expression, "this")
1813            remainder = self.sql(expression, "expression")
1814            return f"WITH (MODULUS {modulus}, REMAINDER {remainder})"
1815
1816        from_expressions = self.expressions(expression, key="from_expressions", flat=True)
1817        to_expressions = self.expressions(expression, key="to_expressions", flat=True)
1818        return f"FROM ({from_expressions}) TO ({to_expressions})"
1819
1820    def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str:
1821        this = self.sql(expression, "this")
1822
1823        for_values_or_default = expression.expression
1824        if isinstance(for_values_or_default, exp.PartitionBoundSpec):
1825            for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}"
1826        else:
1827            for_values_or_default = " DEFAULT"
1828
1829        return f"PARTITION OF {this}{for_values_or_default}"
1830
1831    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
1832        kind = expression.args.get("kind")
1833        this = f" {self.sql(expression, 'this')}" if expression.this else ""
1834        for_or_in = expression.args.get("for_or_in")
1835        for_or_in = f" {for_or_in}" if for_or_in else ""
1836        lock_type = expression.args.get("lock_type")
1837        override = " OVERRIDE" if expression.args.get("override") else ""
1838        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"
1839
1840    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
1841        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
1842        statistics = expression.args.get("statistics")
1843        statistics_sql = ""
1844        if statistics is not None:
1845            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
1846        return f"{data_sql}{statistics_sql}"
1847
1848    def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str:
1849        this = self.sql(expression, "this")
1850        this = f"HISTORY_TABLE={this}" if this else ""
1851        data_consistency: t.Optional[str] = self.sql(expression, "data_consistency")
1852        data_consistency = (
1853            f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None
1854        )
1855        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
1856        retention_period = (
1857            f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None
1858        )
1859
1860        if this:
1861            on_sql = self.func("ON", this, data_consistency, retention_period)
1862        else:
1863            on_sql = "ON" if expression.args.get("on") else "OFF"
1864
1865        sql = f"SYSTEM_VERSIONING={on_sql}"
1866
1867        return f"WITH({sql})" if expression.args.get("with") else sql
1868
1869    def insert_sql(self, expression: exp.Insert) -> str:
1870        hint = self.sql(expression, "hint")
1871        overwrite = expression.args.get("overwrite")
1872
1873        if isinstance(expression.this, exp.Directory):
1874            this = " OVERWRITE" if overwrite else " INTO"
1875        else:
1876            this = self.INSERT_OVERWRITE if overwrite else " INTO"
1877
1878        stored = self.sql(expression, "stored")
1879        stored = f" {stored}" if stored else ""
1880        alternative = expression.args.get("alternative")
1881        alternative = f" OR {alternative}" if alternative else ""
1882        ignore = " IGNORE" if expression.args.get("ignore") else ""
1883        is_function = expression.args.get("is_function")
1884        if is_function:
1885            this = f"{this} FUNCTION"
1886        this = f"{this} {self.sql(expression, 'this')}"
1887
1888        exists = " IF EXISTS" if expression.args.get("exists") else ""
1889        where = self.sql(expression, "where")
1890        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
1891        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
1892        on_conflict = self.sql(expression, "conflict")
1893        on_conflict = f" {on_conflict}" if on_conflict else ""
1894        by_name = " BY NAME" if expression.args.get("by_name") else ""
1895        returning = self.sql(expression, "returning")
1896
1897        if self.RETURNING_END:
1898            expression_sql = f"{expression_sql}{on_conflict}{returning}"
1899        else:
1900            expression_sql = f"{returning}{expression_sql}{on_conflict}"
1901
1902        partition_by = self.sql(expression, "partition")
1903        partition_by = f" {partition_by}" if partition_by else ""
1904        settings = self.sql(expression, "settings")
1905        settings = f" {settings}" if settings else ""
1906
1907        source = self.sql(expression, "source")
1908        source = f"TABLE {source}" if source else ""
1909
1910        sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}"
1911        return self.prepend_ctes(expression, sql)
1912
1913    def introducer_sql(self, expression: exp.Introducer) -> str:
1914        return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}"
1915
1916    def kill_sql(self, expression: exp.Kill) -> str:
1917        kind = self.sql(expression, "kind")
1918        kind = f" {kind}" if kind else ""
1919        this = self.sql(expression, "this")
1920        this = f" {this}" if this else ""
1921        return f"KILL{kind}{this}"
1922
1923    def pseudotype_sql(self, expression: exp.PseudoType) -> str:
1924        return expression.name
1925
1926    def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str:
1927        return expression.name
1928
1929    def onconflict_sql(self, expression: exp.OnConflict) -> str:
1930        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
1931
1932        constraint = self.sql(expression, "constraint")
1933        constraint = f" ON CONSTRAINT {constraint}" if constraint else ""
1934
1935        conflict_keys = self.expressions(expression, key="conflict_keys", flat=True)
1936        conflict_keys = f"({conflict_keys}) " if conflict_keys else " "
1937        action = self.sql(expression, "action")
1938
1939        expressions = self.expressions(expression, flat=True)
1940        if expressions:
1941            set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
1942            expressions = f" {set_keyword}{expressions}"
1943
1944        where = self.sql(expression, "where")
1945        return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}"
1946
1947    def returning_sql(self, expression: exp.Returning) -> str:
1948        return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}"
1949
1950    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
1951        fields = self.sql(expression, "fields")
1952        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
1953        escaped = self.sql(expression, "escaped")
1954        escaped = f" ESCAPED BY {escaped}" if escaped else ""
1955        items = self.sql(expression, "collection_items")
1956        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
1957        keys = self.sql(expression, "map_keys")
1958        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
1959        lines = self.sql(expression, "lines")
1960        lines = f" LINES TERMINATED BY {lines}" if lines else ""
1961        null = self.sql(expression, "null")
1962        null = f" NULL DEFINED AS {null}" if null else ""
1963        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"
1964
1965    def withtablehint_sql(self, expression: exp.WithTableHint) -> str:
1966        return f"WITH ({self.expressions(expression, flat=True)})"
1967
1968    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
1969        this = f"{self.sql(expression, 'this')} INDEX"
1970        target = self.sql(expression, "target")
1971        target = f" FOR {target}" if target else ""
1972        return f"{this}{target} ({self.expressions(expression, flat=True)})"
1973
1974    def historicaldata_sql(self, expression: exp.HistoricalData) -> str:
1975        this = self.sql(expression, "this")
1976        kind = self.sql(expression, "kind")
1977        expr = self.sql(expression, "expression")
1978        return f"{this} ({kind} => {expr})"
1979
1980    def table_parts(self, expression: exp.Table) -> str:
1981        return ".".join(
1982            self.sql(part)
1983            for part in (
1984                expression.args.get("catalog"),
1985                expression.args.get("db"),
1986                expression.args.get("this"),
1987            )
1988            if part is not None
1989        )
1990
1991    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
1992        table = self.table_parts(expression)
1993        only = "ONLY " if expression.args.get("only") else ""
1994        partition = self.sql(expression, "partition")
1995        partition = f" {partition}" if partition else ""
1996        version = self.sql(expression, "version")
1997        version = f" {version}" if version else ""
1998        alias = self.sql(expression, "alias")
1999        alias = f"{sep}{alias}" if alias else ""
2000
2001        sample = self.sql(expression, "sample")
2002        if self.dialect.ALIAS_POST_TABLESAMPLE:
2003            sample_pre_alias = sample
2004            sample_post_alias = ""
2005        else:
2006            sample_pre_alias = ""
2007            sample_post_alias = sample
2008
2009        hints = self.expressions(expression, key="hints", sep=" ")
2010        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
2011        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
2012        joins = self.indent(
2013            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
2014        )
2015        laterals = self.expressions(expression, key="laterals", sep="")
2016
2017        file_format = self.sql(expression, "format")
2018        if file_format:
2019            pattern = self.sql(expression, "pattern")
2020            pattern = f", PATTERN => {pattern}" if pattern else ""
2021            file_format = f" (FILE_FORMAT => {file_format}{pattern})"
2022
2023        ordinality = expression.args.get("ordinality") or ""
2024        if ordinality:
2025            ordinality = f" WITH ORDINALITY{alias}"
2026            alias = ""
2027
2028        when = self.sql(expression, "when")
2029        if when:
2030            table = f"{table} {when}"
2031
2032        changes = self.sql(expression, "changes")
2033        changes = f" {changes}" if changes else ""
2034
2035        rows_from = self.expressions(expression, key="rows_from")
2036        if rows_from:
2037            table = f"ROWS FROM {self.wrap(rows_from)}"
2038
2039        return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}"
2040
2041    def tablefromrows_sql(self, expression: exp.TableFromRows) -> str:
2042        table = self.func("TABLE", expression.this)
2043        alias = self.sql(expression, "alias")
2044        alias = f" AS {alias}" if alias else ""
2045        sample = self.sql(expression, "sample")
2046        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
2047        joins = self.indent(
2048            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
2049        )
2050        return f"{table}{alias}{pivots}{sample}{joins}"
2051
2052    def tablesample_sql(
2053        self,
2054        expression: exp.TableSample,
2055        tablesample_keyword: t.Optional[str] = None,
2056    ) -> str:
2057        method = self.sql(expression, "method")
2058        method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else ""
2059        numerator = self.sql(expression, "bucket_numerator")
2060        denominator = self.sql(expression, "bucket_denominator")
2061        field = self.sql(expression, "bucket_field")
2062        field = f" ON {field}" if field else ""
2063        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
2064        seed = self.sql(expression, "seed")
2065        seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else ""
2066
2067        size = self.sql(expression, "size")
2068        if size and self.TABLESAMPLE_SIZE_IS_ROWS:
2069            size = f"{size} ROWS"
2070
2071        percent = self.sql(expression, "percent")
2072        if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT:
2073            percent = f"{percent} PERCENT"
2074
2075        expr = f"{bucket}{percent}{size}"
2076        if self.TABLESAMPLE_REQUIRES_PARENS:
2077            expr = f"({expr})"
2078
2079        return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}"
2080
2081    def pivot_sql(self, expression: exp.Pivot) -> str:
2082        expressions = self.expressions(expression, flat=True)
2083        direction = "UNPIVOT" if expression.unpivot else "PIVOT"
2084
2085        group = self.sql(expression, "group")
2086
2087        if expression.this:
2088            this = self.sql(expression, "this")
2089            if not expressions:
2090                return f"UNPIVOT {this}"
2091
2092            on = f"{self.seg('ON')} {expressions}"
2093            into = self.sql(expression, "into")
2094            into = f"{self.seg('INTO')} {into}" if into else ""
2095            using = self.expressions(expression, key="using", flat=True)
2096            using = f"{self.seg('USING')} {using}" if using else ""
2097            return f"{direction} {this}{on}{into}{using}{group}"
2098
2099        alias = self.sql(expression, "alias")
2100        alias = f" AS {alias}" if alias else ""
2101
2102        fields = self.expressions(
2103            expression,
2104            "fields",
2105            sep=" ",
2106            dynamic=True,
2107            new_line=True,
2108            skip_first=True,
2109            skip_last=True,
2110        )
2111
2112        include_nulls = expression.args.get("include_nulls")
2113        if include_nulls is not None:
2114            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
2115        else:
2116            nulls = ""
2117
2118        default_on_null = self.sql(expression, "default_on_null")
2119        default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else ""
2120        return f"{self.seg(direction)}{nulls}({expressions} FOR {fields}{default_on_null}{group}){alias}"
2121
2122    def version_sql(self, expression: exp.Version) -> str:
2123        this = f"FOR {expression.name}"
2124        kind = expression.text("kind")
2125        expr = self.sql(expression, "expression")
2126        return f"{this} {kind} {expr}"
2127
2128    def tuple_sql(self, expression: exp.Tuple) -> str:
2129        return f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})"
2130
2131    def update_sql(self, expression: exp.Update) -> str:
2132        this = self.sql(expression, "this")
2133        set_sql = self.expressions(expression, flat=True)
2134        from_sql = self.sql(expression, "from")
2135        where_sql = self.sql(expression, "where")
2136        returning = self.sql(expression, "returning")
2137        order = self.sql(expression, "order")
2138        limit = self.sql(expression, "limit")
2139        if self.RETURNING_END:
2140            expression_sql = f"{from_sql}{where_sql}{returning}"
2141        else:
2142            expression_sql = f"{returning}{from_sql}{where_sql}"
2143        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
2144        return self.prepend_ctes(expression, sql)
2145
2146    def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str:
2147        values_as_table = values_as_table and self.VALUES_AS_TABLE
2148
2149        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
2150        if values_as_table or not expression.find_ancestor(exp.From, exp.Join):
2151            args = self.expressions(expression)
2152            alias = self.sql(expression, "alias")
2153            values = f"VALUES{self.seg('')}{args}"
2154            values = (
2155                f"({values})"
2156                if self.WRAP_DERIVED_VALUES
2157                and (alias or isinstance(expression.parent, (exp.From, exp.Table)))
2158                else values
2159            )
2160            return f"{values} AS {alias}" if alias else values
2161
2162        # Converts `VALUES...` expression into a series of select unions.
2163        alias_node = expression.args.get("alias")
2164        column_names = alias_node and alias_node.columns
2165
2166        selects: t.List[exp.Query] = []
2167
2168        for i, tup in enumerate(expression.expressions):
2169            row = tup.expressions
2170
2171            if i == 0 and column_names:
2172                row = [
2173                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
2174                ]
2175
2176            selects.append(exp.Select(expressions=row))
2177
2178        if self.pretty:
2179            # This may result in poor performance for large-cardinality `VALUES` tables, due to
2180            # the deep nesting of the resulting exp.Unions. If this is a problem, either increase
2181            # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`.
2182            query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects)
2183            return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False))
2184
2185        alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else ""
2186        unions = " UNION ALL ".join(self.sql(select) for select in selects)
2187        return f"({unions}){alias}"
2188
2189    def var_sql(self, expression: exp.Var) -> str:
2190        return self.sql(expression, "this")
2191
2192    @unsupported_args("expressions")
2193    def into_sql(self, expression: exp.Into) -> str:
2194        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
2195        unlogged = " UNLOGGED" if expression.args.get("unlogged") else ""
2196        return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"
2197
2198    def from_sql(self, expression: exp.From) -> str:
2199        return f"{self.seg('FROM')} {self.sql(expression, 'this')}"
2200
2201    def groupingsets_sql(self, expression: exp.GroupingSets) -> str:
2202        grouping_sets = self.expressions(expression, indent=False)
2203        return f"GROUPING SETS {self.wrap(grouping_sets)}"
2204
2205    def rollup_sql(self, expression: exp.Rollup) -> str:
2206        expressions = self.expressions(expression, indent=False)
2207        return f"ROLLUP {self.wrap(expressions)}" if expressions else "WITH ROLLUP"
2208
2209    def cube_sql(self, expression: exp.Cube) -> str:
2210        expressions = self.expressions(expression, indent=False)
2211        return f"CUBE {self.wrap(expressions)}" if expressions else "WITH CUBE"
2212
2213    def group_sql(self, expression: exp.Group) -> str:
2214        group_by_all = expression.args.get("all")
2215        if group_by_all is True:
2216            modifier = " ALL"
2217        elif group_by_all is False:
2218            modifier = " DISTINCT"
2219        else:
2220            modifier = ""
2221
2222        group_by = self.op_expressions(f"GROUP BY{modifier}", expression)
2223
2224        grouping_sets = self.expressions(expression, key="grouping_sets")
2225        cube = self.expressions(expression, key="cube")
2226        rollup = self.expressions(expression, key="rollup")
2227
2228        groupings = csv(
2229            self.seg(grouping_sets) if grouping_sets else "",
2230            self.seg(cube) if cube else "",
2231            self.seg(rollup) if rollup else "",
2232            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
2233            sep=self.GROUPINGS_SEP,
2234        )
2235
2236        if (
2237            expression.expressions
2238            and groupings
2239            and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP")
2240        ):
2241            group_by = f"{group_by}{self.GROUPINGS_SEP}"
2242
2243        return f"{group_by}{groupings}"
2244
2245    def having_sql(self, expression: exp.Having) -> str:
2246        this = self.indent(self.sql(expression, "this"))
2247        return f"{self.seg('HAVING')}{self.sep()}{this}"
2248
2249    def connect_sql(self, expression: exp.Connect) -> str:
2250        start = self.sql(expression, "start")
2251        start = self.seg(f"START WITH {start}") if start else ""
2252        nocycle = " NOCYCLE" if expression.args.get("nocycle") else ""
2253        connect = self.sql(expression, "connect")
2254        connect = self.seg(f"CONNECT BY{nocycle} {connect}")
2255        return start + connect
2256
2257    def prior_sql(self, expression: exp.Prior) -> str:
2258        return f"PRIOR {self.sql(expression, 'this')}"
2259
2260    def join_sql(self, expression: exp.Join) -> str:
2261        if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"):
2262            side = None
2263        else:
2264            side = expression.side
2265
2266        op_sql = " ".join(
2267            op
2268            for op in (
2269                expression.method,
2270                "GLOBAL" if expression.args.get("global") else None,
2271                side,
2272                expression.kind,
2273                expression.hint if self.JOIN_HINTS else None,
2274            )
2275            if op
2276        )
2277        match_cond = self.sql(expression, "match_condition")
2278        match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else ""
2279        on_sql = self.sql(expression, "on")
2280        using = expression.args.get("using")
2281
2282        if not on_sql and using:
2283            on_sql = csv(*(self.sql(column) for column in using))
2284
2285        this = expression.this
2286        this_sql = self.sql(this)
2287
2288        exprs = self.expressions(expression)
2289        if exprs:
2290            this_sql = f"{this_sql},{self.seg(exprs)}"
2291
2292        if on_sql:
2293            on_sql = self.indent(on_sql, skip_first=True)
2294            space = self.seg(" " * self.pad) if self.pretty else " "
2295            if using:
2296                on_sql = f"{space}USING ({on_sql})"
2297            else:
2298                on_sql = f"{space}ON {on_sql}"
2299        elif not op_sql:
2300            if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None:
2301                return f" {this_sql}"
2302
2303            return f", {this_sql}"
2304
2305        if op_sql != "STRAIGHT_JOIN":
2306            op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
2307
2308        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
2309        return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}{pivots}"
2310
2311    def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->") -> str:
2312        args = self.expressions(expression, flat=True)
2313        args = f"({args})" if len(args.split(",")) > 1 else args
2314        return f"{args} {arrow_sep} {self.sql(expression, 'this')}"
2315
2316    def lateral_op(self, expression: exp.Lateral) -> str:
2317        cross_apply = expression.args.get("cross_apply")
2318
2319        # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/
2320        if cross_apply is True:
2321            op = "INNER JOIN "
2322        elif cross_apply is False:
2323            op = "LEFT JOIN "
2324        else:
2325            op = ""
2326
2327        return f"{op}LATERAL"
2328
2329    def lateral_sql(self, expression: exp.Lateral) -> str:
2330        this = self.sql(expression, "this")
2331
2332        if expression.args.get("view"):
2333            alias = expression.args["alias"]
2334            columns = self.expressions(alias, key="columns", flat=True)
2335            table = f" {alias.name}" if alias.name else ""
2336            columns = f" AS {columns}" if columns else ""
2337            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
2338            return f"{op_sql}{self.sep()}{this}{table}{columns}"
2339
2340        alias = self.sql(expression, "alias")
2341        alias = f" AS {alias}" if alias else ""
2342
2343        ordinality = expression.args.get("ordinality") or ""
2344        if ordinality:
2345            ordinality = f" WITH ORDINALITY{alias}"
2346            alias = ""
2347
2348        return f"{self.lateral_op(expression)} {this}{alias}{ordinality}"
2349
2350    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
2351        this = self.sql(expression, "this")
2352
2353        args = [
2354            self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e
2355            for e in (expression.args.get(k) for k in ("offset", "expression"))
2356            if e
2357        ]
2358
2359        args_sql = ", ".join(self.sql(e) for e in args)
2360        args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql
2361        expressions = self.expressions(expression, flat=True)
2362        limit_options = self.sql(expression, "limit_options")
2363        expressions = f" BY {expressions}" if expressions else ""
2364
2365        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{limit_options}{expressions}"
2366
2367    def offset_sql(self, expression: exp.Offset) -> str:
2368        this = self.sql(expression, "this")
2369        value = expression.expression
2370        value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value
2371        expressions = self.expressions(expression, flat=True)
2372        expressions = f" BY {expressions}" if expressions else ""
2373        return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"
2374
2375    def setitem_sql(self, expression: exp.SetItem) -> str:
2376        kind = self.sql(expression, "kind")
2377        kind = f"{kind} " if kind else ""
2378        this = self.sql(expression, "this")
2379        expressions = self.expressions(expression)
2380        collate = self.sql(expression, "collate")
2381        collate = f" COLLATE {collate}" if collate else ""
2382        global_ = "GLOBAL " if expression.args.get("global") else ""
2383        return f"{global_}{kind}{this}{expressions}{collate}"
2384
2385    def set_sql(self, expression: exp.Set) -> str:
2386        expressions = f" {self.expressions(expression, flat=True)}"
2387        tag = " TAG" if expression.args.get("tag") else ""
2388        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"
2389
2390    def pragma_sql(self, expression: exp.Pragma) -> str:
2391        return f"PRAGMA {self.sql(expression, 'this')}"
2392
2393    def lock_sql(self, expression: exp.Lock) -> str:
2394        if not self.LOCKING_READS_SUPPORTED:
2395            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
2396            return ""
2397
2398        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
2399        expressions = self.expressions(expression, flat=True)
2400        expressions = f" OF {expressions}" if expressions else ""
2401        wait = expression.args.get("wait")
2402
2403        if wait is not None:
2404            if isinstance(wait, exp.Literal):
2405                wait = f" WAIT {self.sql(wait)}"
2406            else:
2407                wait = " NOWAIT" if wait else " SKIP LOCKED"
2408
2409        return f"{lock_type}{expressions}{wait or ''}"
2410
2411    def literal_sql(self, expression: exp.Literal) -> str:
2412        text = expression.this or ""
2413        if expression.is_string:
2414            text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}"
2415        return text
2416
2417    def escape_str(self, text: str, escape_backslash: bool = True) -> str:
2418        if self.dialect.ESCAPED_SEQUENCES:
2419            to_escaped = self.dialect.ESCAPED_SEQUENCES
2420            text = "".join(
2421                to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text
2422            )
2423
2424        return self._replace_line_breaks(text).replace(
2425            self.dialect.QUOTE_END, self._escaped_quote_end
2426        )
2427
2428    def loaddata_sql(self, expression: exp.LoadData) -> str:
2429        local = " LOCAL" if expression.args.get("local") else ""
2430        inpath = f" INPATH {self.sql(expression, 'inpath')}"
2431        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
2432        this = f" INTO TABLE {self.sql(expression, 'this')}"
2433        partition = self.sql(expression, "partition")
2434        partition = f" {partition}" if partition else ""
2435        input_format = self.sql(expression, "input_format")
2436        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
2437        serde = self.sql(expression, "serde")
2438        serde = f" SERDE {serde}" if serde else ""
2439        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"
2440
2441    def null_sql(self, *_) -> str:
2442        return "NULL"
2443
2444    def boolean_sql(self, expression: exp.Boolean) -> str:
2445        return "TRUE" if expression.this else "FALSE"
2446
2447    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
2448        this = self.sql(expression, "this")
2449        this = f"{this} " if this else this
2450        siblings = "SIBLINGS " if expression.args.get("siblings") else ""
2451        return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat)  # type: ignore
2452
2453    def withfill_sql(self, expression: exp.WithFill) -> str:
2454        from_sql = self.sql(expression, "from")
2455        from_sql = f" FROM {from_sql}" if from_sql else ""
2456        to_sql = self.sql(expression, "to")
2457        to_sql = f" TO {to_sql}" if to_sql else ""
2458        step_sql = self.sql(expression, "step")
2459        step_sql = f" STEP {step_sql}" if step_sql else ""
2460        interpolated_values = [
2461            f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}"
2462            if isinstance(e, exp.Alias)
2463            else self.sql(e, "this")
2464            for e in expression.args.get("interpolate") or []
2465        ]
2466        interpolate = (
2467            f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else ""
2468        )
2469        return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}"
2470
2471    def cluster_sql(self, expression: exp.Cluster) -> str:
2472        return self.op_expressions("CLUSTER BY", expression)
2473
2474    def distribute_sql(self, expression: exp.Distribute) -> str:
2475        return self.op_expressions("DISTRIBUTE BY", expression)
2476
2477    def sort_sql(self, expression: exp.Sort) -> str:
2478        return self.op_expressions("SORT BY", expression)
2479
2480    def ordered_sql(self, expression: exp.Ordered) -> str:
2481        desc = expression.args.get("desc")
2482        asc = not desc
2483
2484        nulls_first = expression.args.get("nulls_first")
2485        nulls_last = not nulls_first
2486        nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large"
2487        nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small"
2488        nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last"
2489
2490        this = self.sql(expression, "this")
2491
2492        sort_order = " DESC" if desc else (" ASC" if desc is False else "")
2493        nulls_sort_change = ""
2494        if nulls_first and (
2495            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
2496        ):
2497            nulls_sort_change = " NULLS FIRST"
2498        elif (
2499            nulls_last
2500            and ((asc and nulls_are_small) or (desc and nulls_are_large))
2501            and not nulls_are_last
2502        ):
2503            nulls_sort_change = " NULLS LAST"
2504
2505        # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it
2506        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
2507            window = expression.find_ancestor(exp.Window, exp.Select)
2508            if isinstance(window, exp.Window) and window.args.get("spec"):
2509                self.unsupported(
2510                    f"'{nulls_sort_change.strip()}' translation not supported in window functions"
2511                )
2512                nulls_sort_change = ""
2513            elif self.NULL_ORDERING_SUPPORTED is False and (
2514                (asc and nulls_sort_change == " NULLS LAST")
2515                or (desc and nulls_sort_change == " NULLS FIRST")
2516            ):
2517                # BigQuery does not allow these ordering/nulls combinations when used under
2518                # an aggregation func or under a window containing one
2519                ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select)
2520
2521                if isinstance(ancestor, exp.Window):
2522                    ancestor = ancestor.this
2523                if isinstance(ancestor, exp.AggFunc):
2524                    self.unsupported(
2525                        f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order"
2526                    )
2527                    nulls_sort_change = ""
2528            elif self.NULL_ORDERING_SUPPORTED is None:
2529                if expression.this.is_int:
2530                    self.unsupported(
2531                        f"'{nulls_sort_change.strip()}' translation not supported with positional ordering"
2532                    )
2533                elif not isinstance(expression.this, exp.Rand):
2534                    null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else ""
2535                    this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}"
2536                nulls_sort_change = ""
2537
2538        with_fill = self.sql(expression, "with_fill")
2539        with_fill = f" {with_fill}" if with_fill else ""
2540
2541        return f"{this}{sort_order}{nulls_sort_change}{with_fill}"
2542
2543    def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str:
2544        window_frame = self.sql(expression, "window_frame")
2545        window_frame = f"{window_frame} " if window_frame else ""
2546
2547        this = self.sql(expression, "this")
2548
2549        return f"{window_frame}{this}"
2550
2551    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
2552        partition = self.partition_by_sql(expression)
2553        order = self.sql(expression, "order")
2554        measures = self.expressions(expression, key="measures")
2555        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
2556        rows = self.sql(expression, "rows")
2557        rows = self.seg(rows) if rows else ""
2558        after = self.sql(expression, "after")
2559        after = self.seg(after) if after else ""
2560        pattern = self.sql(expression, "pattern")
2561        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
2562        definition_sqls = [
2563            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
2564            for definition in expression.args.get("define", [])
2565        ]
2566        definitions = self.expressions(sqls=definition_sqls)
2567        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
2568        body = "".join(
2569            (
2570                partition,
2571                order,
2572                measures,
2573                rows,
2574                after,
2575                pattern,
2576                define,
2577            )
2578        )
2579        alias = self.sql(expression, "alias")
2580        alias = f" {alias}" if alias else ""
2581        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"
2582
2583    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
2584        limit = expression.args.get("limit")
2585
2586        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
2587            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
2588        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
2589            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
2590
2591        return csv(
2592            *sqls,
2593            *[self.sql(join) for join in expression.args.get("joins") or []],
2594            self.sql(expression, "match"),
2595            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
2596            self.sql(expression, "prewhere"),
2597            self.sql(expression, "where"),
2598            self.sql(expression, "connect"),
2599            self.sql(expression, "group"),
2600            self.sql(expression, "having"),
2601            *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()],
2602            self.sql(expression, "order"),
2603            *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit),
2604            *self.after_limit_modifiers(expression),
2605            self.options_modifier(expression),
2606            self.for_modifiers(expression),
2607            sep="",
2608        )
2609
2610    def options_modifier(self, expression: exp.Expression) -> str:
2611        options = self.expressions(expression, key="options")
2612        return f" {options}" if options else ""
2613
2614    def for_modifiers(self, expression: exp.Expression) -> str:
2615        for_modifiers = self.expressions(expression, key="for")
2616        return f"{self.sep()}FOR XML{self.seg(for_modifiers)}" if for_modifiers else ""
2617
2618    def queryoption_sql(self, expression: exp.QueryOption) -> str:
2619        self.unsupported("Unsupported query option.")
2620        return ""
2621
2622    def offset_limit_modifiers(
2623        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
2624    ) -> t.List[str]:
2625        return [
2626            self.sql(expression, "offset") if fetch else self.sql(limit),
2627            self.sql(limit) if fetch else self.sql(expression, "offset"),
2628        ]
2629
2630    def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]:
2631        locks = self.expressions(expression, key="locks", sep=" ")
2632        locks = f" {locks}" if locks else ""
2633        return [locks, self.sql(expression, "sample")]
2634
2635    def select_sql(self, expression: exp.Select) -> str:
2636        into = expression.args.get("into")
2637        if not self.SUPPORTS_SELECT_INTO and into:
2638            into.pop()
2639
2640        hint = self.sql(expression, "hint")
2641        distinct = self.sql(expression, "distinct")
2642        distinct = f" {distinct}" if distinct else ""
2643        kind = self.sql(expression, "kind")
2644
2645        limit = expression.args.get("limit")
2646        if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP:
2647            top = self.limit_sql(limit, top=True)
2648            limit.pop()
2649        else:
2650            top = ""
2651
2652        expressions = self.expressions(expression)
2653
2654        if kind:
2655            if kind in self.SELECT_KINDS:
2656                kind = f" AS {kind}"
2657            else:
2658                if kind == "STRUCT":
2659                    expressions = self.expressions(
2660                        sqls=[
2661                            self.sql(
2662                                exp.Struct(
2663                                    expressions=[
2664                                        exp.PropertyEQ(this=e.args.get("alias"), expression=e.this)
2665                                        if isinstance(e, exp.Alias)
2666                                        else e
2667                                        for e in expression.expressions
2668                                    ]
2669                                )
2670                            )
2671                        ]
2672                    )
2673                kind = ""
2674
2675        operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ")
2676        operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else ""
2677
2678        # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata
2679        # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first.
2680        top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}"
2681        expressions = f"{self.sep()}{expressions}" if expressions else expressions
2682        sql = self.query_modifiers(
2683            expression,
2684            f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}",
2685            self.sql(expression, "into", comment=False),
2686            self.sql(expression, "from", comment=False),
2687        )
2688
2689        # If both the CTE and SELECT clauses have comments, generate the latter earlier
2690        if expression.args.get("with"):
2691            sql = self.maybe_comment(sql, expression)
2692            expression.pop_comments()
2693
2694        sql = self.prepend_ctes(expression, sql)
2695
2696        if not self.SUPPORTS_SELECT_INTO and into:
2697            if into.args.get("temporary"):
2698                table_kind = " TEMPORARY"
2699            elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"):
2700                table_kind = " UNLOGGED"
2701            else:
2702                table_kind = ""
2703            sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}"
2704
2705        return sql
2706
2707    def schema_sql(self, expression: exp.Schema) -> str:
2708        this = self.sql(expression, "this")
2709        sql = self.schema_columns_sql(expression)
2710        return f"{this} {sql}" if this and sql else this or sql
2711
2712    def schema_columns_sql(self, expression: exp.Schema) -> str:
2713        if expression.expressions:
2714            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
2715        return ""
2716
2717    def star_sql(self, expression: exp.Star) -> str:
2718        except_ = self.expressions(expression, key="except", flat=True)
2719        except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else ""
2720        replace = self.expressions(expression, key="replace", flat=True)
2721        replace = f"{self.seg('REPLACE')} ({replace})" if replace else ""
2722        rename = self.expressions(expression, key="rename", flat=True)
2723        rename = f"{self.seg('RENAME')} ({rename})" if rename else ""
2724        return f"*{except_}{replace}{rename}"
2725
2726    def parameter_sql(self, expression: exp.Parameter) -> str:
2727        this = self.sql(expression, "this")
2728        return f"{self.PARAMETER_TOKEN}{this}"
2729
2730    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
2731        this = self.sql(expression, "this")
2732        kind = expression.text("kind")
2733        if kind:
2734            kind = f"{kind}."
2735        return f"@@{kind}{this}"
2736
2737    def placeholder_sql(self, expression: exp.Placeholder) -> str:
2738        return f"{self.NAMED_PLACEHOLDER_TOKEN}{expression.name}" if expression.this else "?"
2739
2740    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
2741        alias = self.sql(expression, "alias")
2742        alias = f"{sep}{alias}" if alias else ""
2743        sample = self.sql(expression, "sample")
2744        if self.dialect.ALIAS_POST_TABLESAMPLE and sample:
2745            alias = f"{sample}{alias}"
2746
2747            # Set to None so it's not generated again by self.query_modifiers()
2748            expression.set("sample", None)
2749
2750        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
2751        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
2752        return self.prepend_ctes(expression, sql)
2753
2754    def qualify_sql(self, expression: exp.Qualify) -> str:
2755        this = self.indent(self.sql(expression, "this"))
2756        return f"{self.seg('QUALIFY')}{self.sep()}{this}"
2757
2758    def unnest_sql(self, expression: exp.Unnest) -> str:
2759        args = self.expressions(expression, flat=True)
2760
2761        alias = expression.args.get("alias")
2762        offset = expression.args.get("offset")
2763
2764        if self.UNNEST_WITH_ORDINALITY:
2765            if alias and isinstance(offset, exp.Expression):
2766                alias.append("columns", offset)
2767
2768        if alias and self.dialect.UNNEST_COLUMN_ONLY:
2769            columns = alias.columns
2770            alias = self.sql(columns[0]) if columns else ""
2771        else:
2772            alias = self.sql(alias)
2773
2774        alias = f" AS {alias}" if alias else alias
2775        if self.UNNEST_WITH_ORDINALITY:
2776            suffix = f" WITH ORDINALITY{alias}" if offset else alias
2777        else:
2778            if isinstance(offset, exp.Expression):
2779                suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}"
2780            elif offset:
2781                suffix = f"{alias} WITH OFFSET"
2782            else:
2783                suffix = alias
2784
2785        return f"UNNEST({args}){suffix}"
2786
2787    def prewhere_sql(self, expression: exp.PreWhere) -> str:
2788        return ""
2789
2790    def where_sql(self, expression: exp.Where) -> str:
2791        this = self.indent(self.sql(expression, "this"))
2792        return f"{self.seg('WHERE')}{self.sep()}{this}"
2793
2794    def window_sql(self, expression: exp.Window) -> str:
2795        this = self.sql(expression, "this")
2796        partition = self.partition_by_sql(expression)
2797        order = expression.args.get("order")
2798        order = self.order_sql(order, flat=True) if order else ""
2799        spec = self.sql(expression, "spec")
2800        alias = self.sql(expression, "alias")
2801        over = self.sql(expression, "over") or "OVER"
2802
2803        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
2804
2805        first = expression.args.get("first")
2806        if first is None:
2807            first = ""
2808        else:
2809            first = "FIRST" if first else "LAST"
2810
2811        if not partition and not order and not spec and alias:
2812            return f"{this} {alias}"
2813
2814        args = self.format_args(
2815            *[arg for arg in (alias, first, partition, order, spec) if arg], sep=" "
2816        )
2817        return f"{this} ({args})"
2818
2819    def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str:
2820        partition = self.expressions(expression, key="partition_by", flat=True)
2821        return f"PARTITION BY {partition}" if partition else ""
2822
2823    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
2824        kind = self.sql(expression, "kind")
2825        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
2826        end = (
2827            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
2828            or "CURRENT ROW"
2829        )
2830
2831        window_spec = f"{kind} BETWEEN {start} AND {end}"
2832
2833        exclude = self.sql(expression, "exclude")
2834        if exclude:
2835            if self.SUPPORTS_WINDOW_EXCLUDE:
2836                window_spec += f" EXCLUDE {exclude}"
2837            else:
2838                self.unsupported("EXCLUDE clause is not supported in the WINDOW clause")
2839
2840        return window_spec
2841
2842    def withingroup_sql(self, expression: exp.WithinGroup) -> str:
2843        this = self.sql(expression, "this")
2844        expression_sql = self.sql(expression, "expression")[1:]  # order has a leading space
2845        return f"{this} WITHIN GROUP ({expression_sql})"
2846
2847    def between_sql(self, expression: exp.Between) -> str:
2848        this = self.sql(expression, "this")
2849        low = self.sql(expression, "low")
2850        high = self.sql(expression, "high")
2851        return f"{this} BETWEEN {low} AND {high}"
2852
2853    def bracket_offset_expressions(
2854        self, expression: exp.Bracket, index_offset: t.Optional[int] = None
2855    ) -> t.List[exp.Expression]:
2856        return apply_index_offset(
2857            expression.this,
2858            expression.expressions,
2859            (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0),
2860            dialect=self.dialect,
2861        )
2862
2863    def bracket_sql(self, expression: exp.Bracket) -> str:
2864        expressions = self.bracket_offset_expressions(expression)
2865        expressions_sql = ", ".join(self.sql(e) for e in expressions)
2866        return f"{self.sql(expression, 'this')}[{expressions_sql}]"
2867
2868    def all_sql(self, expression: exp.All) -> str:
2869        return f"ALL {self.wrap(expression)}"
2870
2871    def any_sql(self, expression: exp.Any) -> str:
2872        this = self.sql(expression, "this")
2873        if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)):
2874            if isinstance(expression.this, exp.UNWRAPPED_QUERIES):
2875                this = self.wrap(this)
2876            return f"ANY{this}"
2877        return f"ANY {this}"
2878
2879    def exists_sql(self, expression: exp.Exists) -> str:
2880        return f"EXISTS{self.wrap(expression)}"
2881
2882    def case_sql(self, expression: exp.Case) -> str:
2883        this = self.sql(expression, "this")
2884        statements = [f"CASE {this}" if this else "CASE"]
2885
2886        for e in expression.args["ifs"]:
2887            statements.append(f"WHEN {self.sql(e, 'this')}")
2888            statements.append(f"THEN {self.sql(e, 'true')}")
2889
2890        default = self.sql(expression, "default")
2891
2892        if default:
2893            statements.append(f"ELSE {default}")
2894
2895        statements.append("END")
2896
2897        if self.pretty and self.too_wide(statements):
2898            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
2899
2900        return " ".join(statements)
2901
2902    def constraint_sql(self, expression: exp.Constraint) -> str:
2903        this = self.sql(expression, "this")
2904        expressions = self.expressions(expression, flat=True)
2905        return f"CONSTRAINT {this} {expressions}"
2906
2907    def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str:
2908        order = expression.args.get("order")
2909        order = f" OVER ({self.order_sql(order, flat=True)})" if order else ""
2910        return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}"
2911
2912    def extract_sql(self, expression: exp.Extract) -> str:
2913        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
2914        expression_sql = self.sql(expression, "expression")
2915        return f"EXTRACT({this} FROM {expression_sql})"
2916
2917    def trim_sql(self, expression: exp.Trim) -> str:
2918        trim_type = self.sql(expression, "position")
2919
2920        if trim_type == "LEADING":
2921            func_name = "LTRIM"
2922        elif trim_type == "TRAILING":
2923            func_name = "RTRIM"
2924        else:
2925            func_name = "TRIM"
2926
2927        return self.func(func_name, expression.this, expression.expression)
2928
2929    def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]:
2930        args = expression.expressions
2931        if isinstance(expression, exp.ConcatWs):
2932            args = args[1:]  # Skip the delimiter
2933
2934        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
2935            args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args]
2936
2937        if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"):
2938            args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args]
2939
2940        return args
2941
2942    def concat_sql(self, expression: exp.Concat) -> str:
2943        expressions = self.convert_concat_args(expression)
2944
2945        # Some dialects don't allow a single-argument CONCAT call
2946        if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1:
2947            return self.sql(expressions[0])
2948
2949        return self.func("CONCAT", *expressions)
2950
2951    def concatws_sql(self, expression: exp.ConcatWs) -> str:
2952        return self.func(
2953            "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression)
2954        )
2955
2956    def check_sql(self, expression: exp.Check) -> str:
2957        this = self.sql(expression, key="this")
2958        return f"CHECK ({this})"
2959
2960    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
2961        expressions = self.expressions(expression, flat=True)
2962        expressions = f" ({expressions})" if expressions else ""
2963        reference = self.sql(expression, "reference")
2964        reference = f" {reference}" if reference else ""
2965        delete = self.sql(expression, "delete")
2966        delete = f" ON DELETE {delete}" if delete else ""
2967        update = self.sql(expression, "update")
2968        update = f" ON UPDATE {update}" if update else ""
2969        options = self.expressions(expression, key="options", flat=True, sep=" ")
2970        options = f" {options}" if options else ""
2971        return f"FOREIGN KEY{expressions}{reference}{delete}{update}{options}"
2972
2973    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
2974        expressions = self.expressions(expression, flat=True)
2975        options = self.expressions(expression, key="options", flat=True, sep=" ")
2976        options = f" {options}" if options else ""
2977        return f"PRIMARY KEY ({expressions}){options}"
2978
2979    def if_sql(self, expression: exp.If) -> str:
2980        return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false")))
2981
2982    def matchagainst_sql(self, expression: exp.MatchAgainst) -> str:
2983        modifier = expression.args.get("modifier")
2984        modifier = f" {modifier}" if modifier else ""
2985        return f"{self.func('MATCH', *expression.expressions)} AGAINST({self.sql(expression, 'this')}{modifier})"
2986
2987    def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str:
2988        return f"{self.sql(expression, 'this')}{self.JSON_KEY_VALUE_PAIR_SEP} {self.sql(expression, 'expression')}"
2989
2990    def jsonpath_sql(self, expression: exp.JSONPath) -> str:
2991        path = self.expressions(expression, sep="", flat=True).lstrip(".")
2992
2993        if expression.args.get("escape"):
2994            path = self.escape_str(path)
2995
2996        if self.QUOTE_JSON_PATH:
2997            path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"
2998
2999        return path
3000
3001    def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str:
3002        if isinstance(expression, exp.JSONPathPart):
3003            transform = self.TRANSFORMS.get(expression.__class__)
3004            if not callable(transform):
3005                self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}")
3006                return ""
3007
3008            return transform(self, expression)
3009
3010        if isinstance(expression, int):
3011            return str(expression)
3012
3013        if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE:
3014            escaped = expression.replace("'", "\\'")
3015            escaped = f"\\'{expression}\\'"
3016        else:
3017            escaped = expression.replace('"', '\\"')
3018            escaped = f'"{escaped}"'
3019
3020        return escaped
3021
3022    def formatjson_sql(self, expression: exp.FormatJson) -> str:
3023        return f"{self.sql(expression, 'this')} FORMAT JSON"
3024
3025    def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str:
3026        null_handling = expression.args.get("null_handling")
3027        null_handling = f" {null_handling}" if null_handling else ""
3028
3029        unique_keys = expression.args.get("unique_keys")
3030        if unique_keys is not None:
3031            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
3032        else:
3033            unique_keys = ""
3034
3035        return_type = self.sql(expression, "return_type")
3036        return_type = f" RETURNING {return_type}" if return_type else ""
3037        encoding = self.sql(expression, "encoding")
3038        encoding = f" ENCODING {encoding}" if encoding else ""
3039
3040        return self.func(
3041            "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG",
3042            *expression.expressions,
3043            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
3044        )
3045
3046    def jsonobjectagg_sql(self, expression: exp.JSONObjectAgg) -> str:
3047        return self.jsonobject_sql(expression)
3048
3049    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
3050        null_handling = expression.args.get("null_handling")
3051        null_handling = f" {null_handling}" if null_handling else ""
3052        return_type = self.sql(expression, "return_type")
3053        return_type = f" RETURNING {return_type}" if return_type else ""
3054        strict = " STRICT" if expression.args.get("strict") else ""
3055        return self.func(
3056            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
3057        )
3058
3059    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
3060        this = self.sql(expression, "this")
3061        order = self.sql(expression, "order")
3062        null_handling = expression.args.get("null_handling")
3063        null_handling = f" {null_handling}" if null_handling else ""
3064        return_type = self.sql(expression, "return_type")
3065        return_type = f" RETURNING {return_type}" if return_type else ""
3066        strict = " STRICT" if expression.args.get("strict") else ""
3067        return self.func(
3068            "JSON_ARRAYAGG",
3069            this,
3070            suffix=f"{order}{null_handling}{return_type}{strict})",
3071        )
3072
3073    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
3074        path = self.sql(expression, "path")
3075        path = f" PATH {path}" if path else ""
3076        nested_schema = self.sql(expression, "nested_schema")
3077
3078        if nested_schema:
3079            return f"NESTED{path} {nested_schema}"
3080
3081        this = self.sql(expression, "this")
3082        kind = self.sql(expression, "kind")
3083        kind = f" {kind}" if kind else ""
3084        return f"{this}{kind}{path}"
3085
3086    def jsonschema_sql(self, expression: exp.JSONSchema) -> str:
3087        return self.func("COLUMNS", *expression.expressions)
3088
3089    def jsontable_sql(self, expression: exp.JSONTable) -> str:
3090        this = self.sql(expression, "this")
3091        path = self.sql(expression, "path")
3092        path = f", {path}" if path else ""
3093        error_handling = expression.args.get("error_handling")
3094        error_handling = f" {error_handling}" if error_handling else ""
3095        empty_handling = expression.args.get("empty_handling")
3096        empty_handling = f" {empty_handling}" if empty_handling else ""
3097        schema = self.sql(expression, "schema")
3098        return self.func(
3099            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
3100        )
3101
3102    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
3103        this = self.sql(expression, "this")
3104        kind = self.sql(expression, "kind")
3105        path = self.sql(expression, "path")
3106        path = f" {path}" if path else ""
3107        as_json = " AS JSON" if expression.args.get("as_json") else ""
3108        return f"{this} {kind}{path}{as_json}"
3109
3110    def openjson_sql(self, expression: exp.OpenJSON) -> str:
3111        this = self.sql(expression, "this")
3112        path = self.sql(expression, "path")
3113        path = f", {path}" if path else ""
3114        expressions = self.expressions(expression)
3115        with_ = (
3116            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
3117            if expressions
3118            else ""
3119        )
3120        return f"OPENJSON({this}{path}){with_}"
3121
3122    def in_sql(self, expression: exp.In) -> str:
3123        query = expression.args.get("query")
3124        unnest = expression.args.get("unnest")
3125        field = expression.args.get("field")
3126        is_global = " GLOBAL" if expression.args.get("is_global") else ""
3127
3128        if query:
3129            in_sql = self.sql(query)
3130        elif unnest:
3131            in_sql = self.in_unnest_op(unnest)
3132        elif field:
3133            in_sql = self.sql(field)
3134        else:
3135            in_sql = f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})"
3136
3137        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"
3138
3139    def in_unnest_op(self, unnest: exp.Unnest) -> str:
3140        return f"(SELECT {self.sql(unnest)})"
3141
3142    def interval_sql(self, expression: exp.Interval) -> str:
3143        unit = self.sql(expression, "unit")
3144        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
3145            unit = self.TIME_PART_SINGULARS.get(unit, unit)
3146        unit = f" {unit}" if unit else ""
3147
3148        if self.SINGLE_STRING_INTERVAL:
3149            this = expression.this.name if expression.this else ""
3150            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
3151
3152        this = self.sql(expression, "this")
3153        if this:
3154            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
3155            this = f" {this}" if unwrapped else f" ({this})"
3156
3157        return f"INTERVAL{this}{unit}"
3158
3159    def return_sql(self, expression: exp.Return) -> str:
3160        return f"RETURN {self.sql(expression, 'this')}"
3161
3162    def reference_sql(self, expression: exp.Reference) -> str:
3163        this = self.sql(expression, "this")
3164        expressions = self.expressions(expression, flat=True)
3165        expressions = f"({expressions})" if expressions else ""
3166        options = self.expressions(expression, key="options", flat=True, sep=" ")
3167        options = f" {options}" if options else ""
3168        return f"REFERENCES {this}{expressions}{options}"
3169
3170    def anonymous_sql(self, expression: exp.Anonymous) -> str:
3171        # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive
3172        parent = expression.parent
3173        is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression
3174        return self.func(
3175            self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified
3176        )
3177
3178    def paren_sql(self, expression: exp.Paren) -> str:
3179        sql = self.seg(self.indent(self.sql(expression, "this")), sep="")
3180        return f"({sql}{self.seg(')', sep='')}"
3181
3182    def neg_sql(self, expression: exp.Neg) -> str:
3183        # This makes sure we don't convert "- - 5" to "--5", which is a comment
3184        this_sql = self.sql(expression, "this")
3185        sep = " " if this_sql[0] == "-" else ""
3186        return f"-{sep}{this_sql}"
3187
3188    def not_sql(self, expression: exp.Not) -> str:
3189        return f"NOT {self.sql(expression, 'this')}"
3190
3191    def alias_sql(self, expression: exp.Alias) -> str:
3192        alias = self.sql(expression, "alias")
3193        alias = f" AS {alias}" if alias else ""
3194        return f"{self.sql(expression, 'this')}{alias}"
3195
3196    def pivotalias_sql(self, expression: exp.PivotAlias) -> str:
3197        alias = expression.args["alias"]
3198
3199        parent = expression.parent
3200        pivot = parent and parent.parent
3201
3202        if isinstance(pivot, exp.Pivot) and pivot.unpivot:
3203            identifier_alias = isinstance(alias, exp.Identifier)
3204            literal_alias = isinstance(alias, exp.Literal)
3205
3206            if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
3207                alias.replace(exp.Literal.string(alias.output_name))
3208            elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
3209                alias.replace(exp.to_identifier(alias.output_name))
3210
3211        return self.alias_sql(expression)
3212
3213    def aliases_sql(self, expression: exp.Aliases) -> str:
3214        return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})"
3215
3216    def atindex_sql(self, expression: exp.AtTimeZone) -> str:
3217        this = self.sql(expression, "this")
3218        index = self.sql(expression, "expression")
3219        return f"{this} AT {index}"
3220
3221    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
3222        this = self.sql(expression, "this")
3223        zone = self.sql(expression, "zone")
3224        return f"{this} AT TIME ZONE {zone}"
3225
3226    def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str:
3227        this = self.sql(expression, "this")
3228        zone = self.sql(expression, "zone")
3229        return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'"
3230
3231    def add_sql(self, expression: exp.Add) -> str:
3232        return self.binary(expression, "+")
3233
3234    def and_sql(
3235        self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None
3236    ) -> str:
3237        return self.connector_sql(expression, "AND", stack)
3238
3239    def or_sql(
3240        self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None
3241    ) -> str:
3242        return self.connector_sql(expression, "OR", stack)
3243
3244    def xor_sql(
3245        self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None
3246    ) -> str:
3247        return self.connector_sql(expression, "XOR", stack)
3248
3249    def connector_sql(
3250        self,
3251        expression: exp.Connector,
3252        op: str,
3253        stack: t.Optional[t.List[str | exp.Expression]] = None,
3254    ) -> str:
3255        if stack is not None:
3256            if expression.expressions:
3257                stack.append(self.expressions(expression, sep=f" {op} "))
3258            else:
3259                stack.append(expression.right)
3260                if expression.comments and self.comments:
3261                    for comment in expression.comments:
3262                        if comment:
3263                            op += f" /*{self.sanitize_comment(comment)}*/"
3264                stack.extend((op, expression.left))
3265            return op
3266
3267        stack = [expression]
3268        sqls: t.List[str] = []
3269        ops = set()
3270
3271        while stack:
3272            node = stack.pop()
3273            if isinstance(node, exp.Connector):
3274                ops.add(getattr(self, f"{node.key}_sql")(node, stack))
3275            else:
3276                sql = self.sql(node)
3277                if sqls and sqls[-1] in ops:
3278                    sqls[-1] += f" {sql}"
3279                else:
3280                    sqls.append(sql)
3281
3282        sep = "\n" if self.pretty and self.too_wide(sqls) else " "
3283        return sep.join(sqls)
3284
3285    def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str:
3286        return self.binary(expression, "&")
3287
3288    def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str:
3289        return self.binary(expression, "<<")
3290
3291    def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str:
3292        return f"~{self.sql(expression, 'this')}"
3293
3294    def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str:
3295        return self.binary(expression, "|")
3296
3297    def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str:
3298        return self.binary(expression, ">>")
3299
3300    def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str:
3301        return self.binary(expression, "^")
3302
3303    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
3304        format_sql = self.sql(expression, "format")
3305        format_sql = f" FORMAT {format_sql}" if format_sql else ""
3306        to_sql = self.sql(expression, "to")
3307        to_sql = f" {to_sql}" if to_sql else ""
3308        action = self.sql(expression, "action")
3309        action = f" {action}" if action else ""
3310        default = self.sql(expression, "default")
3311        default = f" DEFAULT {default} ON CONVERSION ERROR" if default else ""
3312        return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{default}{format_sql}{action})"
3313
3314    def currentdate_sql(self, expression: exp.CurrentDate) -> str:
3315        zone = self.sql(expression, "this")
3316        return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE"
3317
3318    def collate_sql(self, expression: exp.Collate) -> str:
3319        if self.COLLATE_IS_FUNC:
3320            return self.function_fallback_sql(expression)
3321        return self.binary(expression, "COLLATE")
3322
3323    def command_sql(self, expression: exp.Command) -> str:
3324        return f"{self.sql(expression, 'this')} {expression.text('expression').strip()}"
3325
3326    def comment_sql(self, expression: exp.Comment) -> str:
3327        this = self.sql(expression, "this")
3328        kind = expression.args["kind"]
3329        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
3330        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
3331        expression_sql = self.sql(expression, "expression")
3332        return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"
3333
3334    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
3335        this = self.sql(expression, "this")
3336        delete = " DELETE" if expression.args.get("delete") else ""
3337        recompress = self.sql(expression, "recompress")
3338        recompress = f" RECOMPRESS {recompress}" if recompress else ""
3339        to_disk = self.sql(expression, "to_disk")
3340        to_disk = f" TO DISK {to_disk}" if to_disk else ""
3341        to_volume = self.sql(expression, "to_volume")
3342        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
3343        return f"{this}{delete}{recompress}{to_disk}{to_volume}"
3344
3345    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
3346        where = self.sql(expression, "where")
3347        group = self.sql(expression, "group")
3348        aggregates = self.expressions(expression, key="aggregates")
3349        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
3350
3351        if not (where or group or aggregates) and len(expression.expressions) == 1:
3352            return f"TTL {self.expressions(expression, flat=True)}"
3353
3354        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"
3355
3356    def transaction_sql(self, expression: exp.Transaction) -> str:
3357        return "BEGIN"
3358
3359    def commit_sql(self, expression: exp.Commit) -> str:
3360        chain = expression.args.get("chain")
3361        if chain is not None:
3362            chain = " AND CHAIN" if chain else " AND NO CHAIN"
3363
3364        return f"COMMIT{chain or ''}"
3365
3366    def rollback_sql(self, expression: exp.Rollback) -> str:
3367        savepoint = expression.args.get("savepoint")
3368        savepoint = f" TO {savepoint}" if savepoint else ""
3369        return f"ROLLBACK{savepoint}"
3370
3371    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
3372        this = self.sql(expression, "this")
3373
3374        dtype = self.sql(expression, "dtype")
3375        if dtype:
3376            collate = self.sql(expression, "collate")
3377            collate = f" COLLATE {collate}" if collate else ""
3378            using = self.sql(expression, "using")
3379            using = f" USING {using}" if using else ""
3380            alter_set_type = self.ALTER_SET_TYPE + " " if self.ALTER_SET_TYPE else ""
3381            return f"ALTER COLUMN {this} {alter_set_type}{dtype}{collate}{using}"
3382
3383        default = self.sql(expression, "default")
3384        if default:
3385            return f"ALTER COLUMN {this} SET DEFAULT {default}"
3386
3387        comment = self.sql(expression, "comment")
3388        if comment:
3389            return f"ALTER COLUMN {this} COMMENT {comment}"
3390
3391        visible = expression.args.get("visible")
3392        if visible:
3393            return f"ALTER COLUMN {this} SET {visible}"
3394
3395        allow_null = expression.args.get("allow_null")
3396        drop = expression.args.get("drop")
3397
3398        if not drop and not allow_null:
3399            self.unsupported("Unsupported ALTER COLUMN syntax")
3400
3401        if allow_null is not None:
3402            keyword = "DROP" if drop else "SET"
3403            return f"ALTER COLUMN {this} {keyword} NOT NULL"
3404
3405        return f"ALTER COLUMN {this} DROP DEFAULT"
3406
3407    def alterindex_sql(self, expression: exp.AlterIndex) -> str:
3408        this = self.sql(expression, "this")
3409
3410        visible = expression.args.get("visible")
3411        visible_sql = "VISIBLE" if visible else "INVISIBLE"
3412
3413        return f"ALTER INDEX {this} {visible_sql}"
3414
3415    def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str:
3416        this = self.sql(expression, "this")
3417        if not isinstance(expression.this, exp.Var):
3418            this = f"KEY DISTKEY {this}"
3419        return f"ALTER DISTSTYLE {this}"
3420
3421    def altersortkey_sql(self, expression: exp.AlterSortKey) -> str:
3422        compound = " COMPOUND" if expression.args.get("compound") else ""
3423        this = self.sql(expression, "this")
3424        expressions = self.expressions(expression, flat=True)
3425        expressions = f"({expressions})" if expressions else ""
3426        return f"ALTER{compound} SORTKEY {this or expressions}"
3427
3428    def alterrename_sql(self, expression: exp.AlterRename) -> str:
3429        if not self.RENAME_TABLE_WITH_DB:
3430            # Remove db from tables
3431            expression = expression.transform(
3432                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
3433            ).assert_is(exp.AlterRename)
3434        this = self.sql(expression, "this")
3435        return f"RENAME TO {this}"
3436
3437    def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
3438        exists = " IF EXISTS" if expression.args.get("exists") else ""
3439        old_column = self.sql(expression, "this")
3440        new_column = self.sql(expression, "to")
3441        return f"RENAME COLUMN{exists} {old_column} TO {new_column}"
3442
3443    def alterset_sql(self, expression: exp.AlterSet) -> str:
3444        exprs = self.expressions(expression, flat=True)
3445        if self.ALTER_SET_WRAPPED:
3446            exprs = f"({exprs})"
3447
3448        return f"SET {exprs}"
3449
3450    def alter_sql(self, expression: exp.Alter) -> str:
3451        actions = expression.args["actions"]
3452
3453        if not self.dialect.ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN and isinstance(
3454            actions[0], exp.ColumnDef
3455        ):
3456            actions_sql = self.expressions(expression, key="actions", flat=True)
3457            actions_sql = f"ADD {actions_sql}"
3458        else:
3459            actions_list = []
3460            for action in actions:
3461                if isinstance(action, (exp.ColumnDef, exp.Schema)):
3462                    action_sql = self.add_column_sql(action)
3463                else:
3464                    action_sql = self.sql(action)
3465                    if isinstance(action, exp.Query):
3466                        action_sql = f"AS {action_sql}"
3467
3468                actions_list.append(action_sql)
3469
3470            actions_sql = self.format_args(*actions_list)
3471
3472        exists = " IF EXISTS" if expression.args.get("exists") else ""
3473        on_cluster = self.sql(expression, "cluster")
3474        on_cluster = f" {on_cluster}" if on_cluster else ""
3475        only = " ONLY" if expression.args.get("only") else ""
3476        options = self.expressions(expression, key="options")
3477        options = f", {options}" if options else ""
3478        kind = self.sql(expression, "kind")
3479        not_valid = " NOT VALID" if expression.args.get("not_valid") else ""
3480
3481        return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions_sql}{not_valid}{options}"
3482
3483    def add_column_sql(self, expression: exp.Expression) -> str:
3484        sql = self.sql(expression)
3485        if isinstance(expression, exp.Schema):
3486            column_text = " COLUMNS"
3487        elif isinstance(expression, exp.ColumnDef) and self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD:
3488            column_text = " COLUMN"
3489        else:
3490            column_text = ""
3491
3492        return f"ADD{column_text} {sql}"
3493
3494    def droppartition_sql(self, expression: exp.DropPartition) -> str:
3495        expressions = self.expressions(expression)
3496        exists = " IF EXISTS " if expression.args.get("exists") else " "
3497        return f"DROP{exists}{expressions}"
3498
3499    def addconstraint_sql(self, expression: exp.AddConstraint) -> str:
3500        return f"ADD {self.expressions(expression)}"
3501
3502    def addpartition_sql(self, expression: exp.AddPartition) -> str:
3503        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
3504        return f"ADD {exists}{self.sql(expression.this)}"
3505
3506    def distinct_sql(self, expression: exp.Distinct) -> str:
3507        this = self.expressions(expression, flat=True)
3508
3509        if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1:
3510            case = exp.case()
3511            for arg in expression.expressions:
3512                case = case.when(arg.is_(exp.null()), exp.null())
3513            this = self.sql(case.else_(f"({this})"))
3514
3515        this = f" {this}" if this else ""
3516
3517        on = self.sql(expression, "on")
3518        on = f" ON {on}" if on else ""
3519        return f"DISTINCT{this}{on}"
3520
3521    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
3522        return self._embed_ignore_nulls(expression, "IGNORE NULLS")
3523
3524    def respectnulls_sql(self, expression: exp.RespectNulls) -> str:
3525        return self._embed_ignore_nulls(expression, "RESPECT NULLS")
3526
3527    def havingmax_sql(self, expression: exp.HavingMax) -> str:
3528        this_sql = self.sql(expression, "this")
3529        expression_sql = self.sql(expression, "expression")
3530        kind = "MAX" if expression.args.get("max") else "MIN"
3531        return f"{this_sql} HAVING {kind} {expression_sql}"
3532
3533    def intdiv_sql(self, expression: exp.IntDiv) -> str:
3534        return self.sql(
3535            exp.Cast(
3536                this=exp.Div(this=expression.this, expression=expression.expression),
3537                to=exp.DataType(this=exp.DataType.Type.INT),
3538            )
3539        )
3540
3541    def dpipe_sql(self, expression: exp.DPipe) -> str:
3542        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
3543            return self.func(
3544                "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten())
3545            )
3546        return self.binary(expression, "||")
3547
3548    def div_sql(self, expression: exp.Div) -> str:
3549        l, r = expression.left, expression.right
3550
3551        if not self.dialect.SAFE_DIVISION and expression.args.get("safe"):
3552            r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0)))
3553
3554        if self.dialect.TYPED_DIVISION and not expression.args.get("typed"):
3555            if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES):
3556                l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE))
3557
3558        elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"):
3559            if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES):
3560                return self.sql(
3561                    exp.cast(
3562                        l / r,
3563                        to=exp.DataType.Type.BIGINT,
3564                    )
3565                )
3566
3567        return self.binary(expression, "/")
3568
3569    def safedivide_sql(self, expression: exp.SafeDivide) -> str:
3570        n = exp._wrap(expression.this, exp.Binary)
3571        d = exp._wrap(expression.expression, exp.Binary)
3572        return self.sql(exp.If(this=d.neq(0), true=n / d, false=exp.Null()))
3573
3574    def overlaps_sql(self, expression: exp.Overlaps) -> str:
3575        return self.binary(expression, "OVERLAPS")
3576
3577    def distance_sql(self, expression: exp.Distance) -> str:
3578        return self.binary(expression, "<->")
3579
3580    def dot_sql(self, expression: exp.Dot) -> str:
3581        return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}"
3582
3583    def eq_sql(self, expression: exp.EQ) -> str:
3584        return self.binary(expression, "=")
3585
3586    def propertyeq_sql(self, expression: exp.PropertyEQ) -> str:
3587        return self.binary(expression, ":=")
3588
3589    def escape_sql(self, expression: exp.Escape) -> str:
3590        return self.binary(expression, "ESCAPE")
3591
3592    def glob_sql(self, expression: exp.Glob) -> str:
3593        return self.binary(expression, "GLOB")
3594
3595    def gt_sql(self, expression: exp.GT) -> str:
3596        return self.binary(expression, ">")
3597
3598    def gte_sql(self, expression: exp.GTE) -> str:
3599        return self.binary(expression, ">=")
3600
3601    def ilike_sql(self, expression: exp.ILike) -> str:
3602        return self.binary(expression, "ILIKE")
3603
3604    def ilikeany_sql(self, expression: exp.ILikeAny) -> str:
3605        return self.binary(expression, "ILIKE ANY")
3606
3607    def is_sql(self, expression: exp.Is) -> str:
3608        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
3609            return self.sql(
3610                expression.this if expression.expression.this else exp.not_(expression.this)
3611            )
3612        return self.binary(expression, "IS")
3613
3614    def like_sql(self, expression: exp.Like) -> str:
3615        return self.binary(expression, "LIKE")
3616
3617    def likeany_sql(self, expression: exp.LikeAny) -> str:
3618        return self.binary(expression, "LIKE ANY")
3619
3620    def similarto_sql(self, expression: exp.SimilarTo) -> str:
3621        return self.binary(expression, "SIMILAR TO")
3622
3623    def lt_sql(self, expression: exp.LT) -> str:
3624        return self.binary(expression, "<")
3625
3626    def lte_sql(self, expression: exp.LTE) -> str:
3627        return self.binary(expression, "<=")
3628
3629    def mod_sql(self, expression: exp.Mod) -> str:
3630        return self.binary(expression, "%")
3631
3632    def mul_sql(self, expression: exp.Mul) -> str:
3633        return self.binary(expression, "*")
3634
3635    def neq_sql(self, expression: exp.NEQ) -> str:
3636        return self.binary(expression, "<>")
3637
3638    def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str:
3639        return self.binary(expression, "IS NOT DISTINCT FROM")
3640
3641    def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str:
3642        return self.binary(expression, "IS DISTINCT FROM")
3643
3644    def slice_sql(self, expression: exp.Slice) -> str:
3645        return self.binary(expression, ":")
3646
3647    def sub_sql(self, expression: exp.Sub) -> str:
3648        return self.binary(expression, "-")
3649
3650    def trycast_sql(self, expression: exp.TryCast) -> str:
3651        return self.cast_sql(expression, safe_prefix="TRY_")
3652
3653    def jsoncast_sql(self, expression: exp.JSONCast) -> str:
3654        return self.cast_sql(expression)
3655
3656    def try_sql(self, expression: exp.Try) -> str:
3657        if not self.TRY_SUPPORTED:
3658            self.unsupported("Unsupported TRY function")
3659            return self.sql(expression, "this")
3660
3661        return self.func("TRY", expression.this)
3662
3663    def log_sql(self, expression: exp.Log) -> str:
3664        this = expression.this
3665        expr = expression.expression
3666
3667        if self.dialect.LOG_BASE_FIRST is False:
3668            this, expr = expr, this
3669        elif self.dialect.LOG_BASE_FIRST is None and expr:
3670            if this.name in ("2", "10"):
3671                return self.func(f"LOG{this.name}", expr)
3672
3673            self.unsupported(f"Unsupported logarithm with base {self.sql(this)}")
3674
3675        return self.func("LOG", this, expr)
3676
3677    def use_sql(self, expression: exp.Use) -> str:
3678        kind = self.sql(expression, "kind")
3679        kind = f" {kind}" if kind else ""
3680        this = self.sql(expression, "this") or self.expressions(expression, flat=True)
3681        this = f" {this}" if this else ""
3682        return f"USE{kind}{this}"
3683
3684    def binary(self, expression: exp.Binary, op: str) -> str:
3685        sqls: t.List[str] = []
3686        stack: t.List[t.Union[str, exp.Expression]] = [expression]
3687        binary_type = type(expression)
3688
3689        while stack:
3690            node = stack.pop()
3691
3692            if type(node) is binary_type:
3693                op_func = node.args.get("operator")
3694                if op_func:
3695                    op = f"OPERATOR({self.sql(op_func)})"
3696
3697                stack.append(node.right)
3698                stack.append(f" {self.maybe_comment(op, comments=node.comments)} ")
3699                stack.append(node.left)
3700            else:
3701                sqls.append(self.sql(node))
3702
3703        return "".join(sqls)
3704
3705    def ceil_floor(self, expression: exp.Ceil | exp.Floor) -> str:
3706        to_clause = self.sql(expression, "to")
3707        if to_clause:
3708            return f"{expression.sql_name()}({self.sql(expression, 'this')} TO {to_clause})"
3709
3710        return self.function_fallback_sql(expression)
3711
3712    def function_fallback_sql(self, expression: exp.Func) -> str:
3713        args = []
3714
3715        for key in expression.arg_types:
3716            arg_value = expression.args.get(key)
3717
3718            if isinstance(arg_value, list):
3719                for value in arg_value:
3720                    args.append(value)
3721            elif arg_value is not None:
3722                args.append(arg_value)
3723
3724        if self.dialect.PRESERVE_ORIGINAL_NAMES:
3725            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
3726        else:
3727            name = expression.sql_name()
3728
3729        return self.func(name, *args)
3730
3731    def func(
3732        self,
3733        name: str,
3734        *args: t.Optional[exp.Expression | str],
3735        prefix: str = "(",
3736        suffix: str = ")",
3737        normalize: bool = True,
3738    ) -> str:
3739        name = self.normalize_func(name) if normalize else name
3740        return f"{name}{prefix}{self.format_args(*args)}{suffix}"
3741
3742    def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str:
3743        arg_sqls = tuple(
3744            self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool)
3745        )
3746        if self.pretty and self.too_wide(arg_sqls):
3747            return self.indent(
3748                "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True
3749            )
3750        return sep.join(arg_sqls)
3751
3752    def too_wide(self, args: t.Iterable) -> bool:
3753        return sum(len(arg) for arg in args) > self.max_text_width
3754
3755    def format_time(
3756        self,
3757        expression: exp.Expression,
3758        inverse_time_mapping: t.Optional[t.Dict[str, str]] = None,
3759        inverse_time_trie: t.Optional[t.Dict] = None,
3760    ) -> t.Optional[str]:
3761        return format_time(
3762            self.sql(expression, "format"),
3763            inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING,
3764            inverse_time_trie or self.dialect.INVERSE_TIME_TRIE,
3765        )
3766
3767    def expressions(
3768        self,
3769        expression: t.Optional[exp.Expression] = None,
3770        key: t.Optional[str] = None,
3771        sqls: t.Optional[t.Collection[str | exp.Expression]] = None,
3772        flat: bool = False,
3773        indent: bool = True,
3774        skip_first: bool = False,
3775        skip_last: bool = False,
3776        sep: str = ", ",
3777        prefix: str = "",
3778        dynamic: bool = False,
3779        new_line: bool = False,
3780    ) -> str:
3781        expressions = expression.args.get(key or "expressions") if expression else sqls
3782
3783        if not expressions:
3784            return ""
3785
3786        if flat:
3787            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
3788
3789        num_sqls = len(expressions)
3790        result_sqls = []
3791
3792        for i, e in enumerate(expressions):
3793            sql = self.sql(e, comment=False)
3794            if not sql:
3795                continue
3796
3797            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
3798
3799            if self.pretty:
3800                if self.leading_comma:
3801                    result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}")
3802                else:
3803                    result_sqls.append(
3804                        f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}"
3805                    )
3806            else:
3807                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
3808
3809        if self.pretty and (not dynamic or self.too_wide(result_sqls)):
3810            if new_line:
3811                result_sqls.insert(0, "")
3812                result_sqls.append("")
3813            result_sql = "\n".join(s.rstrip() for s in result_sqls)
3814        else:
3815            result_sql = "".join(result_sqls)
3816
3817        return (
3818            self.indent(result_sql, skip_first=skip_first, skip_last=skip_last)
3819            if indent
3820            else result_sql
3821        )
3822
3823    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
3824        flat = flat or isinstance(expression.parent, exp.Properties)
3825        expressions_sql = self.expressions(expression, flat=flat)
3826        if flat:
3827            return f"{op} {expressions_sql}"
3828        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"
3829
3830    def naked_property(self, expression: exp.Property) -> str:
3831        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
3832        if not property_name:
3833            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
3834        return f"{property_name} {self.sql(expression, 'this')}"
3835
3836    def tag_sql(self, expression: exp.Tag) -> str:
3837        return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}"
3838
3839    def token_sql(self, token_type: TokenType) -> str:
3840        return self.TOKEN_MAPPING.get(token_type, token_type.name)
3841
3842    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
3843        this = self.sql(expression, "this")
3844        expressions = self.no_identify(self.expressions, expression)
3845        expressions = (
3846            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
3847        )
3848        return f"{this}{expressions}" if expressions.strip() != "" else this
3849
3850    def joinhint_sql(self, expression: exp.JoinHint) -> str:
3851        this = self.sql(expression, "this")
3852        expressions = self.expressions(expression, flat=True)
3853        return f"{this}({expressions})"
3854
3855    def kwarg_sql(self, expression: exp.Kwarg) -> str:
3856        return self.binary(expression, "=>")
3857
3858    def when_sql(self, expression: exp.When) -> str:
3859        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
3860        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
3861        condition = self.sql(expression, "condition")
3862        condition = f" AND {condition}" if condition else ""
3863
3864        then_expression = expression.args.get("then")
3865        if isinstance(then_expression, exp.Insert):
3866            this = self.sql(then_expression, "this")
3867            this = f"INSERT {this}" if this else "INSERT"
3868            then = self.sql(then_expression, "expression")
3869            then = f"{this} VALUES {then}" if then else this
3870        elif isinstance(then_expression, exp.Update):
3871            if isinstance(then_expression.args.get("expressions"), exp.Star):
3872                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
3873            else:
3874                then = f"UPDATE SET{self.sep()}{self.expressions(then_expression)}"
3875        else:
3876            then = self.sql(then_expression)
3877        return f"WHEN {matched}{source}{condition} THEN {then}"
3878
3879    def whens_sql(self, expression: exp.Whens) -> str:
3880        return self.expressions(expression, sep=" ", indent=False)
3881
3882    def merge_sql(self, expression: exp.Merge) -> str:
3883        table = expression.this
3884        table_alias = ""
3885
3886        hints = table.args.get("hints")
3887        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
3888            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
3889            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
3890
3891        this = self.sql(table)
3892        using = f"USING {self.sql(expression, 'using')}"
3893        on = f"ON {self.sql(expression, 'on')}"
3894        whens = self.sql(expression, "whens")
3895
3896        returning = self.sql(expression, "returning")
3897        if returning:
3898            whens = f"{whens}{returning}"
3899
3900        sep = self.sep()
3901
3902        return self.prepend_ctes(
3903            expression,
3904            f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}",
3905        )
3906
3907    @unsupported_args("format")
3908    def tochar_sql(self, expression: exp.ToChar) -> str:
3909        return self.sql(exp.cast(expression.this, exp.DataType.Type.TEXT))
3910
3911    def tonumber_sql(self, expression: exp.ToNumber) -> str:
3912        if not self.SUPPORTS_TO_NUMBER:
3913            self.unsupported("Unsupported TO_NUMBER function")
3914            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
3915
3916        fmt = expression.args.get("format")
3917        if not fmt:
3918            self.unsupported("Conversion format is required for TO_NUMBER")
3919            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
3920
3921        return self.func("TO_NUMBER", expression.this, fmt)
3922
3923    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
3924        this = self.sql(expression, "this")
3925        kind = self.sql(expression, "kind")
3926        settings_sql = self.expressions(expression, key="settings", sep=" ")
3927        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
3928        return f"{this}({kind}{args})"
3929
3930    def dictrange_sql(self, expression: exp.DictRange) -> str:
3931        this = self.sql(expression, "this")
3932        max = self.sql(expression, "max")
3933        min = self.sql(expression, "min")
3934        return f"{this}(MIN {min} MAX {max})"
3935
3936    def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str:
3937        return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}"
3938
3939    def duplicatekeyproperty_sql(self, expression: exp.DuplicateKeyProperty) -> str:
3940        return f"DUPLICATE KEY ({self.expressions(expression, flat=True)})"
3941
3942    # https://docs.starrocks.io/docs/sql-reference/sql-statements/table_bucket_part_index/CREATE_TABLE/
3943    def uniquekeyproperty_sql(self, expression: exp.UniqueKeyProperty) -> str:
3944        return f"UNIQUE KEY ({self.expressions(expression, flat=True)})"
3945
3946    # https://docs.starrocks.io/docs/sql-reference/sql-statements/data-definition/CREATE_TABLE/#distribution_desc
3947    def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str:
3948        expressions = self.expressions(expression, flat=True)
3949        expressions = f" {self.wrap(expressions)}" if expressions else ""
3950        buckets = self.sql(expression, "buckets")
3951        kind = self.sql(expression, "kind")
3952        buckets = f" BUCKETS {buckets}" if buckets else ""
3953        order = self.sql(expression, "order")
3954        return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}"
3955
3956    def oncluster_sql(self, expression: exp.OnCluster) -> str:
3957        return ""
3958
3959    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
3960        expressions = self.expressions(expression, key="expressions", flat=True)
3961        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
3962        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
3963        buckets = self.sql(expression, "buckets")
3964        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"
3965
3966    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
3967        this = self.sql(expression, "this")
3968        having = self.sql(expression, "having")
3969
3970        if having:
3971            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
3972
3973        return self.func("ANY_VALUE", this)
3974
3975    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
3976        transform = self.func("TRANSFORM", *expression.expressions)
3977        row_format_before = self.sql(expression, "row_format_before")
3978        row_format_before = f" {row_format_before}" if row_format_before else ""
3979        record_writer = self.sql(expression, "record_writer")
3980        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
3981        using = f" USING {self.sql(expression, 'command_script')}"
3982        schema = self.sql(expression, "schema")
3983        schema = f" AS {schema}" if schema else ""
3984        row_format_after = self.sql(expression, "row_format_after")
3985        row_format_after = f" {row_format_after}" if row_format_after else ""
3986        record_reader = self.sql(expression, "record_reader")
3987        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
3988        return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}"
3989
3990    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
3991        key_block_size = self.sql(expression, "key_block_size")
3992        if key_block_size:
3993            return f"KEY_BLOCK_SIZE = {key_block_size}"
3994
3995        using = self.sql(expression, "using")
3996        if using:
3997            return f"USING {using}"
3998
3999        parser = self.sql(expression, "parser")
4000        if parser:
4001            return f"WITH PARSER {parser}"
4002
4003        comment = self.sql(expression, "comment")
4004        if comment:
4005            return f"COMMENT {comment}"
4006
4007        visible = expression.args.get("visible")
4008        if visible is not None:
4009            return "VISIBLE" if visible else "INVISIBLE"
4010
4011        engine_attr = self.sql(expression, "engine_attr")
4012        if engine_attr:
4013            return f"ENGINE_ATTRIBUTE = {engine_attr}"
4014
4015        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
4016        if secondary_engine_attr:
4017            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
4018
4019        self.unsupported("Unsupported index constraint option.")
4020        return ""
4021
4022    def checkcolumnconstraint_sql(self, expression: exp.CheckColumnConstraint) -> str:
4023        enforced = " ENFORCED" if expression.args.get("enforced") else ""
4024        return f"CHECK ({self.sql(expression, 'this')}){enforced}"
4025
4026    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
4027        kind = self.sql(expression, "kind")
4028        kind = f"{kind} INDEX" if kind else "INDEX"
4029        this = self.sql(expression, "this")
4030        this = f" {this}" if this else ""
4031        index_type = self.sql(expression, "index_type")
4032        index_type = f" USING {index_type}" if index_type else ""
4033        expressions = self.expressions(expression, flat=True)
4034        expressions = f" ({expressions})" if expressions else ""
4035        options = self.expressions(expression, key="options", sep=" ")
4036        options = f" {options}" if options else ""
4037        return f"{kind}{this}{index_type}{expressions}{options}"
4038
4039    def nvl2_sql(self, expression: exp.Nvl2) -> str:
4040        if self.NVL2_SUPPORTED:
4041            return self.function_fallback_sql(expression)
4042
4043        case = exp.Case().when(
4044            expression.this.is_(exp.null()).not_(copy=False),
4045            expression.args["true"],
4046            copy=False,
4047        )
4048        else_cond = expression.args.get("false")
4049        if else_cond:
4050            case.else_(else_cond, copy=False)
4051
4052        return self.sql(case)
4053
4054    def comprehension_sql(self, expression: exp.Comprehension) -> str:
4055        this = self.sql(expression, "this")
4056        expr = self.sql(expression, "expression")
4057        iterator = self.sql(expression, "iterator")
4058        condition = self.sql(expression, "condition")
4059        condition = f" IF {condition}" if condition else ""
4060        return f"{this} FOR {expr} IN {iterator}{condition}"
4061
4062    def columnprefix_sql(self, expression: exp.ColumnPrefix) -> str:
4063        return f"{self.sql(expression, 'this')}({self.sql(expression, 'expression')})"
4064
4065    def opclass_sql(self, expression: exp.Opclass) -> str:
4066        return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}"
4067
4068    def predict_sql(self, expression: exp.Predict) -> str:
4069        model = self.sql(expression, "this")
4070        model = f"MODEL {model}"
4071        table = self.sql(expression, "expression")
4072        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
4073        parameters = self.sql(expression, "params_struct")
4074        return self.func("PREDICT", model, table, parameters or None)
4075
4076    def forin_sql(self, expression: exp.ForIn) -> str:
4077        this = self.sql(expression, "this")
4078        expression_sql = self.sql(expression, "expression")
4079        return f"FOR {this} DO {expression_sql}"
4080
4081    def refresh_sql(self, expression: exp.Refresh) -> str:
4082        this = self.sql(expression, "this")
4083        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
4084        return f"REFRESH {table}{this}"
4085
4086    def toarray_sql(self, expression: exp.ToArray) -> str:
4087        arg = expression.this
4088        if not arg.type:
4089            from sqlglot.optimizer.annotate_types import annotate_types
4090
4091            arg = annotate_types(arg, dialect=self.dialect)
4092
4093        if arg.is_type(exp.DataType.Type.ARRAY):
4094            return self.sql(arg)
4095
4096        cond_for_null = arg.is_(exp.null())
4097        return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False)))
4098
4099    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
4100        this = expression.this
4101        time_format = self.format_time(expression)
4102
4103        if time_format:
4104            return self.sql(
4105                exp.cast(
4106                    exp.StrToTime(this=this, format=expression.args["format"]),
4107                    exp.DataType.Type.TIME,
4108                )
4109            )
4110
4111        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
4112            return self.sql(this)
4113
4114        return self.sql(exp.cast(this, exp.DataType.Type.TIME))
4115
4116    def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str:
4117        this = expression.this
4118        if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP):
4119            return self.sql(this)
4120
4121        return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect))
4122
4123    def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str:
4124        this = expression.this
4125        if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME):
4126            return self.sql(this)
4127
4128        return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect))
4129
4130    def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:
4131        this = expression.this
4132        time_format = self.format_time(expression)
4133
4134        if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT):
4135            return self.sql(
4136                exp.cast(
4137                    exp.StrToTime(this=this, format=expression.args["format"]),
4138                    exp.DataType.Type.DATE,
4139                )
4140            )
4141
4142        if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE):
4143            return self.sql(this)
4144
4145        return self.sql(exp.cast(this, exp.DataType.Type.DATE))
4146
4147    def unixdate_sql(self, expression: exp.UnixDate) -> str:
4148        return self.sql(
4149            exp.func(
4150                "DATEDIFF",
4151                expression.this,
4152                exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE),
4153                "day",
4154            )
4155        )
4156
4157    def lastday_sql(self, expression: exp.LastDay) -> str:
4158        if self.LAST_DAY_SUPPORTS_DATE_PART:
4159            return self.function_fallback_sql(expression)
4160
4161        unit = expression.text("unit")
4162        if unit and unit != "MONTH":
4163            self.unsupported("Date parts are not supported in LAST_DAY.")
4164
4165        return self.func("LAST_DAY", expression.this)
4166
4167    def dateadd_sql(self, expression: exp.DateAdd) -> str:
4168        from sqlglot.dialects.dialect import unit_to_str
4169
4170        return self.func(
4171            "DATE_ADD", expression.this, expression.expression, unit_to_str(expression)
4172        )
4173
4174    def arrayany_sql(self, expression: exp.ArrayAny) -> str:
4175        if self.CAN_IMPLEMENT_ARRAY_ANY:
4176            filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression)
4177            filtered_not_empty = exp.ArraySize(this=filtered).neq(0)
4178            original_is_empty = exp.ArraySize(this=expression.this).eq(0)
4179            return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty)))
4180
4181        from sqlglot.dialects import Dialect
4182
4183        # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect
4184        if self.dialect.__class__ != Dialect:
4185            self.unsupported("ARRAY_ANY is unsupported")
4186
4187        return self.function_fallback_sql(expression)
4188
4189    def struct_sql(self, expression: exp.Struct) -> str:
4190        expression.set(
4191            "expressions",
4192            [
4193                exp.alias_(e.expression, e.name if e.this.is_string else e.this)
4194                if isinstance(e, exp.PropertyEQ)
4195                else e
4196                for e in expression.expressions
4197            ],
4198        )
4199
4200        return self.function_fallback_sql(expression)
4201
4202    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
4203        low = self.sql(expression, "this")
4204        high = self.sql(expression, "expression")
4205
4206        return f"{low} TO {high}"
4207
4208    def truncatetable_sql(self, expression: exp.TruncateTable) -> str:
4209        target = "DATABASE" if expression.args.get("is_database") else "TABLE"
4210        tables = f" {self.expressions(expression)}"
4211
4212        exists = " IF EXISTS" if expression.args.get("exists") else ""
4213
4214        on_cluster = self.sql(expression, "cluster")
4215        on_cluster = f" {on_cluster}" if on_cluster else ""
4216
4217        identity = self.sql(expression, "identity")
4218        identity = f" {identity} IDENTITY" if identity else ""
4219
4220        option = self.sql(expression, "option")
4221        option = f" {option}" if option else ""
4222
4223        partition = self.sql(expression, "partition")
4224        partition = f" {partition}" if partition else ""
4225
4226        return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"
4227
4228    # This transpiles T-SQL's CONVERT function
4229    # https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16
4230    def convert_sql(self, expression: exp.Convert) -> str:
4231        to = expression.this
4232        value = expression.expression
4233        style = expression.args.get("style")
4234        safe = expression.args.get("safe")
4235        strict = expression.args.get("strict")
4236
4237        if not to or not value:
4238            return ""
4239
4240        # Retrieve length of datatype and override to default if not specified
4241        if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES:
4242            to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
4243
4244        transformed: t.Optional[exp.Expression] = None
4245        cast = exp.Cast if strict else exp.TryCast
4246
4247        # Check whether a conversion with format (T-SQL calls this 'style') is applicable
4248        if isinstance(style, exp.Literal) and style.is_int:
4249            from sqlglot.dialects.tsql import TSQL
4250
4251            style_value = style.name
4252            converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value)
4253            if not converted_style:
4254                self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}")
4255
4256            fmt = exp.Literal.string(converted_style)
4257
4258            if to.this == exp.DataType.Type.DATE:
4259                transformed = exp.StrToDate(this=value, format=fmt)
4260            elif to.this in (exp.DataType.Type.DATETIME, exp.DataType.Type.DATETIME2):
4261                transformed = exp.StrToTime(this=value, format=fmt)
4262            elif to.this in self.PARAMETERIZABLE_TEXT_TYPES:
4263                transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe)
4264            elif to.this == exp.DataType.Type.TEXT:
4265                transformed = exp.TimeToStr(this=value, format=fmt)
4266
4267        if not transformed:
4268            transformed = cast(this=value, to=to, safe=safe)
4269
4270        return self.sql(transformed)
4271
4272    def _jsonpathkey_sql(self, expression: exp.JSONPathKey) -> str:
4273        this = expression.this
4274        if isinstance(this, exp.JSONPathWildcard):
4275            this = self.json_path_part(this)
4276            return f".{this}" if this else ""
4277
4278        if exp.SAFE_IDENTIFIER_RE.match(this):
4279            return f".{this}"
4280
4281        this = self.json_path_part(this)
4282        return (
4283            f"[{this}]"
4284            if self._quote_json_path_key_using_brackets and self.JSON_PATH_BRACKETED_KEY_SUPPORTED
4285            else f".{this}"
4286        )
4287
4288    def _jsonpathsubscript_sql(self, expression: exp.JSONPathSubscript) -> str:
4289        this = self.json_path_part(expression.this)
4290        return f"[{this}]" if this else ""
4291
4292    def _simplify_unless_literal(self, expression: E) -> E:
4293        if not isinstance(expression, exp.Literal):
4294            from sqlglot.optimizer.simplify import simplify
4295
4296            expression = simplify(expression, dialect=self.dialect)
4297
4298        return expression
4299
4300    def _embed_ignore_nulls(self, expression: exp.IgnoreNulls | exp.RespectNulls, text: str) -> str:
4301        this = expression.this
4302        if isinstance(this, self.RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS):
4303            self.unsupported(
4304                f"RESPECT/IGNORE NULLS is not supported for {type(this).key} in {self.dialect.__class__.__name__}"
4305            )
4306            return self.sql(this)
4307
4308        if self.IGNORE_NULLS_IN_FUNC and not expression.meta.get("inline"):
4309            # The first modifier here will be the one closest to the AggFunc's arg
4310            mods = sorted(
4311                expression.find_all(exp.HavingMax, exp.Order, exp.Limit),
4312                key=lambda x: 0
4313                if isinstance(x, exp.HavingMax)
4314                else (1 if isinstance(x, exp.Order) else 2),
4315            )
4316
4317            if mods:
4318                mod = mods[0]
4319                this = expression.__class__(this=mod.this.copy())
4320                this.meta["inline"] = True
4321                mod.this.replace(this)
4322                return self.sql(expression.this)
4323
4324            agg_func = expression.find(exp.AggFunc)
4325
4326            if agg_func:
4327                agg_func_sql = self.sql(agg_func, comment=False)[:-1] + f" {text})"
4328                return self.maybe_comment(agg_func_sql, comments=agg_func.comments)
4329
4330        return f"{self.sql(expression, 'this')} {text}"
4331
4332    def _replace_line_breaks(self, string: str) -> str:
4333        """We don't want to extra indent line breaks so we temporarily replace them with sentinels."""
4334        if self.pretty:
4335            return string.replace("\n", self.SENTINEL_LINE_BREAK)
4336        return string
4337
4338    def copyparameter_sql(self, expression: exp.CopyParameter) -> str:
4339        option = self.sql(expression, "this")
4340
4341        if expression.expressions:
4342            upper = option.upper()
4343
4344            # Snowflake FILE_FORMAT options are separated by whitespace
4345            sep = " " if upper == "FILE_FORMAT" else ", "
4346
4347            # Databricks copy/format options do not set their list of values with EQ
4348            op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = "
4349            values = self.expressions(expression, flat=True, sep=sep)
4350            return f"{option}{op}({values})"
4351
4352        value = self.sql(expression, "expression")
4353
4354        if not value:
4355            return option
4356
4357        op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " "
4358
4359        return f"{option}{op}{value}"
4360
4361    def credentials_sql(self, expression: exp.Credentials) -> str:
4362        cred_expr = expression.args.get("credentials")
4363        if isinstance(cred_expr, exp.Literal):
4364            # Redshift case: CREDENTIALS <string>
4365            credentials = self.sql(expression, "credentials")
4366            credentials = f"CREDENTIALS {credentials}" if credentials else ""
4367        else:
4368            # Snowflake case: CREDENTIALS = (...)
4369            credentials = self.expressions(expression, key="credentials", flat=True, sep=" ")
4370            credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else ""
4371
4372        storage = self.sql(expression, "storage")
4373        storage = f"STORAGE_INTEGRATION = {storage}" if storage else ""
4374
4375        encryption = self.expressions(expression, key="encryption", flat=True, sep=" ")
4376        encryption = f" ENCRYPTION = ({encryption})" if encryption else ""
4377
4378        iam_role = self.sql(expression, "iam_role")
4379        iam_role = f"IAM_ROLE {iam_role}" if iam_role else ""
4380
4381        region = self.sql(expression, "region")
4382        region = f" REGION {region}" if region else ""
4383
4384        return f"{credentials}{storage}{encryption}{iam_role}{region}"
4385
4386    def copy_sql(self, expression: exp.Copy) -> str:
4387        this = self.sql(expression, "this")
4388        this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}"
4389
4390        credentials = self.sql(expression, "credentials")
4391        credentials = self.seg(credentials) if credentials else ""
4392        kind = self.seg("FROM" if expression.args.get("kind") else "TO")
4393        files = self.expressions(expression, key="files", flat=True)
4394
4395        sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " "
4396        params = self.expressions(
4397            expression,
4398            key="params",
4399            sep=sep,
4400            new_line=True,
4401            skip_last=True,
4402            skip_first=True,
4403            indent=self.COPY_PARAMS_ARE_WRAPPED,
4404        )
4405
4406        if params:
4407            if self.COPY_PARAMS_ARE_WRAPPED:
4408                params = f" WITH ({params})"
4409            elif not self.pretty:
4410                params = f" {params}"
4411
4412        return f"COPY{this}{kind} {files}{credentials}{params}"
4413
4414    def semicolon_sql(self, expression: exp.Semicolon) -> str:
4415        return ""
4416
4417    def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str:
4418        on_sql = "ON" if expression.args.get("on") else "OFF"
4419        filter_col: t.Optional[str] = self.sql(expression, "filter_column")
4420        filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None
4421        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
4422        retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None
4423
4424        if filter_col or retention_period:
4425            on_sql = self.func("ON", filter_col, retention_period)
4426
4427        return f"DATA_DELETION={on_sql}"
4428
4429    def maskingpolicycolumnconstraint_sql(
4430        self, expression: exp.MaskingPolicyColumnConstraint
4431    ) -> str:
4432        this = self.sql(expression, "this")
4433        expressions = self.expressions(expression, flat=True)
4434        expressions = f" USING ({expressions})" if expressions else ""
4435        return f"MASKING POLICY {this}{expressions}"
4436
4437    def gapfill_sql(self, expression: exp.GapFill) -> str:
4438        this = self.sql(expression, "this")
4439        this = f"TABLE {this}"
4440        return self.func("GAP_FILL", this, *[v for k, v in expression.args.items() if k != "this"])
4441
4442    def scope_resolution(self, rhs: str, scope_name: str) -> str:
4443        return self.func("SCOPE_RESOLUTION", scope_name or None, rhs)
4444
4445    def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str:
4446        this = self.sql(expression, "this")
4447        expr = expression.expression
4448
4449        if isinstance(expr, exp.Func):
4450            # T-SQL's CLR functions are case sensitive
4451            expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})"
4452        else:
4453            expr = self.sql(expression, "expression")
4454
4455        return self.scope_resolution(expr, this)
4456
4457    def parsejson_sql(self, expression: exp.ParseJSON) -> str:
4458        if self.PARSE_JSON_NAME is None:
4459            return self.sql(expression.this)
4460
4461        return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression)
4462
4463    def rand_sql(self, expression: exp.Rand) -> str:
4464        lower = self.sql(expression, "lower")
4465        upper = self.sql(expression, "upper")
4466
4467        if lower and upper:
4468            return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}"
4469        return self.func("RAND", expression.this)
4470
4471    def changes_sql(self, expression: exp.Changes) -> str:
4472        information = self.sql(expression, "information")
4473        information = f"INFORMATION => {information}"
4474        at_before = self.sql(expression, "at_before")
4475        at_before = f"{self.seg('')}{at_before}" if at_before else ""
4476        end = self.sql(expression, "end")
4477        end = f"{self.seg('')}{end}" if end else ""
4478
4479        return f"CHANGES ({information}){at_before}{end}"
4480
4481    def pad_sql(self, expression: exp.Pad) -> str:
4482        prefix = "L" if expression.args.get("is_left") else "R"
4483
4484        fill_pattern = self.sql(expression, "fill_pattern") or None
4485        if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED:
4486            fill_pattern = "' '"
4487
4488        return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)
4489
4490    def summarize_sql(self, expression: exp.Summarize) -> str:
4491        table = " TABLE" if expression.args.get("table") else ""
4492        return f"SUMMARIZE{table} {self.sql(expression.this)}"
4493
4494    def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str:
4495        generate_series = exp.GenerateSeries(**expression.args)
4496
4497        parent = expression.parent
4498        if isinstance(parent, (exp.Alias, exp.TableAlias)):
4499            parent = parent.parent
4500
4501        if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)):
4502            return self.sql(exp.Unnest(expressions=[generate_series]))
4503
4504        if isinstance(parent, exp.Select):
4505            self.unsupported("GenerateSeries projection unnesting is not supported.")
4506
4507        return self.sql(generate_series)
4508
4509    def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str:
4510        exprs = expression.expressions
4511        if not self.ARRAY_CONCAT_IS_VAR_LEN:
4512            rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs)
4513        else:
4514            rhs = self.expressions(expression)
4515
4516        return self.func(name, expression.this, rhs or None)
4517
4518    def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str:
4519        if self.SUPPORTS_CONVERT_TIMEZONE:
4520            return self.function_fallback_sql(expression)
4521
4522        source_tz = expression.args.get("source_tz")
4523        target_tz = expression.args.get("target_tz")
4524        timestamp = expression.args.get("timestamp")
4525
4526        if source_tz and timestamp:
4527            timestamp = exp.AtTimeZone(
4528                this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz
4529            )
4530
4531        expr = exp.AtTimeZone(this=timestamp, zone=target_tz)
4532
4533        return self.sql(expr)
4534
4535    def json_sql(self, expression: exp.JSON) -> str:
4536        this = self.sql(expression, "this")
4537        this = f" {this}" if this else ""
4538
4539        _with = expression.args.get("with")
4540
4541        if _with is None:
4542            with_sql = ""
4543        elif not _with:
4544            with_sql = " WITHOUT"
4545        else:
4546            with_sql = " WITH"
4547
4548        unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else ""
4549
4550        return f"JSON{this}{with_sql}{unique_sql}"
4551
4552    def jsonvalue_sql(self, expression: exp.JSONValue) -> str:
4553        def _generate_on_options(arg: t.Any) -> str:
4554            return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}"
4555
4556        path = self.sql(expression, "path")
4557        returning = self.sql(expression, "returning")
4558        returning = f" RETURNING {returning}" if returning else ""
4559
4560        on_condition = self.sql(expression, "on_condition")
4561        on_condition = f" {on_condition}" if on_condition else ""
4562
4563        return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}")
4564
4565    def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str:
4566        else_ = "ELSE " if expression.args.get("else_") else ""
4567        condition = self.sql(expression, "expression")
4568        condition = f"WHEN {condition} THEN " if condition else else_
4569        insert = self.sql(expression, "this")[len("INSERT") :].strip()
4570        return f"{condition}{insert}"
4571
4572    def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str:
4573        kind = self.sql(expression, "kind")
4574        expressions = self.seg(self.expressions(expression, sep=" "))
4575        res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}"
4576        return res
4577
4578    def oncondition_sql(self, expression: exp.OnCondition) -> str:
4579        # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR"
4580        empty = expression.args.get("empty")
4581        empty = (
4582            f"DEFAULT {empty} ON EMPTY"
4583            if isinstance(empty, exp.Expression)
4584            else self.sql(expression, "empty")
4585        )
4586
4587        error = expression.args.get("error")
4588        error = (
4589            f"DEFAULT {error} ON ERROR"
4590            if isinstance(error, exp.Expression)
4591            else self.sql(expression, "error")
4592        )
4593
4594        if error and empty:
4595            error = (
4596                f"{empty} {error}"
4597                if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR
4598                else f"{error} {empty}"
4599            )
4600            empty = ""
4601
4602        null = self.sql(expression, "null")
4603
4604        return f"{empty}{error}{null}"
4605
4606    def jsonextractquote_sql(self, expression: exp.JSONExtractQuote) -> str:
4607        scalar = " ON SCALAR STRING" if expression.args.get("scalar") else ""
4608        return f"{self.sql(expression, 'option')} QUOTES{scalar}"
4609
4610    def jsonexists_sql(self, expression: exp.JSONExists) -> str:
4611        this = self.sql(expression, "this")
4612        path = self.sql(expression, "path")
4613
4614        passing = self.expressions(expression, "passing")
4615        passing = f" PASSING {passing}" if passing else ""
4616
4617        on_condition = self.sql(expression, "on_condition")
4618        on_condition = f" {on_condition}" if on_condition else ""
4619
4620        path = f"{path}{passing}{on_condition}"
4621
4622        return self.func("JSON_EXISTS", this, path)
4623
4624    def arrayagg_sql(self, expression: exp.ArrayAgg) -> str:
4625        array_agg = self.function_fallback_sql(expression)
4626
4627        # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls
4628        # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB)
4629        if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"):
4630            parent = expression.parent
4631            if isinstance(parent, exp.Filter):
4632                parent_cond = parent.expression.this
4633                parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_()))
4634            else:
4635                this = expression.this
4636                # Do not add the filter if the input is not a column (e.g. literal, struct etc)
4637                if this.find(exp.Column):
4638                    # DISTINCT is already present in the agg function, do not propagate it to FILTER as well
4639                    this_sql = (
4640                        self.expressions(this)
4641                        if isinstance(this, exp.Distinct)
4642                        else self.sql(expression, "this")
4643                    )
4644
4645                    array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)"
4646
4647        return array_agg
4648
4649    def apply_sql(self, expression: exp.Apply) -> str:
4650        this = self.sql(expression, "this")
4651        expr = self.sql(expression, "expression")
4652
4653        return f"{this} APPLY({expr})"
4654
4655    def grant_sql(self, expression: exp.Grant) -> str:
4656        privileges_sql = self.expressions(expression, key="privileges", flat=True)
4657
4658        kind = self.sql(expression, "kind")
4659        kind = f" {kind}" if kind else ""
4660
4661        securable = self.sql(expression, "securable")
4662        securable = f" {securable}" if securable else ""
4663
4664        principals = self.expressions(expression, key="principals", flat=True)
4665
4666        grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else ""
4667
4668        return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}"
4669
4670    def grantprivilege_sql(self, expression: exp.GrantPrivilege):
4671        this = self.sql(expression, "this")
4672        columns = self.expressions(expression, flat=True)
4673        columns = f"({columns})" if columns else ""
4674
4675        return f"{this}{columns}"
4676
4677    def grantprincipal_sql(self, expression: exp.GrantPrincipal):
4678        this = self.sql(expression, "this")
4679
4680        kind = self.sql(expression, "kind")
4681        kind = f"{kind} " if kind else ""
4682
4683        return f"{kind}{this}"
4684
4685    def columns_sql(self, expression: exp.Columns):
4686        func = self.function_fallback_sql(expression)
4687        if expression.args.get("unpack"):
4688            func = f"*{func}"
4689
4690        return func
4691
4692    def overlay_sql(self, expression: exp.Overlay):
4693        this = self.sql(expression, "this")
4694        expr = self.sql(expression, "expression")
4695        from_sql = self.sql(expression, "from")
4696        for_sql = self.sql(expression, "for")
4697        for_sql = f" FOR {for_sql}" if for_sql else ""
4698
4699        return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})"
4700
4701    @unsupported_args("format")
4702    def todouble_sql(self, expression: exp.ToDouble) -> str:
4703        return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
4704
4705    def string_sql(self, expression: exp.String) -> str:
4706        this = expression.this
4707        zone = expression.args.get("zone")
4708
4709        if zone:
4710            # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>)
4711            # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC
4712            # set for source_tz to transpile the time conversion before the STRING cast
4713            this = exp.ConvertTimezone(
4714                source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this
4715            )
4716
4717        return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR))
4718
4719    def median_sql(self, expression: exp.Median):
4720        if not self.SUPPORTS_MEDIAN:
4721            return self.sql(
4722                exp.PercentileCont(this=expression.this, expression=exp.Literal.number(0.5))
4723            )
4724
4725        return self.function_fallback_sql(expression)
4726
4727    def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str:
4728        filler = self.sql(expression, "this")
4729        filler = f" {filler}" if filler else ""
4730        with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT"
4731        return f"TRUNCATE{filler} {with_count}"
4732
4733    def unixseconds_sql(self, expression: exp.UnixSeconds) -> str:
4734        if self.SUPPORTS_UNIX_SECONDS:
4735            return self.function_fallback_sql(expression)
4736
4737        start_ts = exp.cast(
4738            exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ
4739        )
4740
4741        return self.sql(
4742            exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS"))
4743        )
4744
4745    def arraysize_sql(self, expression: exp.ArraySize) -> str:
4746        dim = expression.expression
4747
4748        # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension)
4749        if dim and self.ARRAY_SIZE_DIM_REQUIRED is None:
4750            if not (dim.is_int and dim.name == "1"):
4751                self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH")
4752            dim = None
4753
4754        # If dimension is required but not specified, default initialize it
4755        if self.ARRAY_SIZE_DIM_REQUIRED and not dim:
4756            dim = exp.Literal.number(1)
4757
4758        return self.func(self.ARRAY_SIZE_NAME, expression.this, dim)
4759
4760    def attach_sql(self, expression: exp.Attach) -> str:
4761        this = self.sql(expression, "this")
4762        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
4763        expressions = self.expressions(expression)
4764        expressions = f" ({expressions})" if expressions else ""
4765
4766        return f"ATTACH{exists_sql} {this}{expressions}"
4767
4768    def detach_sql(self, expression: exp.Detach) -> str:
4769        this = self.sql(expression, "this")
4770        exists_sql = " IF EXISTS" if expression.args.get("exists") else ""
4771
4772        return f"DETACH{exists_sql} {this}"
4773
4774    def attachoption_sql(self, expression: exp.AttachOption) -> str:
4775        this = self.sql(expression, "this")
4776        value = self.sql(expression, "expression")
4777        value = f" {value}" if value else ""
4778        return f"{this}{value}"
4779
4780    def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str:
4781        this_sql = self.sql(expression, "this")
4782        if isinstance(expression.this, exp.Table):
4783            this_sql = f"TABLE {this_sql}"
4784
4785        return self.func(
4786            "FEATURES_AT_TIME",
4787            this_sql,
4788            expression.args.get("time"),
4789            expression.args.get("num_rows"),
4790            expression.args.get("ignore_feature_nulls"),
4791        )
4792
4793    def watermarkcolumnconstraint_sql(self, expression: exp.WatermarkColumnConstraint) -> str:
4794        return (
4795            f"WATERMARK FOR {self.sql(expression, 'this')} AS {self.sql(expression, 'expression')}"
4796        )
4797
4798    def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str:
4799        encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE"
4800        encode = f"{encode} {self.sql(expression, 'this')}"
4801
4802        properties = expression.args.get("properties")
4803        if properties:
4804            encode = f"{encode} {self.properties(properties)}"
4805
4806        return encode
4807
4808    def includeproperty_sql(self, expression: exp.IncludeProperty) -> str:
4809        this = self.sql(expression, "this")
4810        include = f"INCLUDE {this}"
4811
4812        column_def = self.sql(expression, "column_def")
4813        if column_def:
4814            include = f"{include} {column_def}"
4815
4816        alias = self.sql(expression, "alias")
4817        if alias:
4818            include = f"{include} AS {alias}"
4819
4820        return include
4821
4822    def xmlelement_sql(self, expression: exp.XMLElement) -> str:
4823        name = f"NAME {self.sql(expression, 'this')}"
4824        return self.func("XMLELEMENT", name, *expression.expressions)
4825
4826    def xmlkeyvalueoption_sql(self, expression: exp.XMLKeyValueOption) -> str:
4827        this = self.sql(expression, "this")
4828        expr = self.sql(expression, "expression")
4829        expr = f"({expr})" if expr else ""
4830        return f"{this}{expr}"
4831
4832    def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str:
4833        partitions = self.expressions(expression, "partition_expressions")
4834        create = self.expressions(expression, "create_expressions")
4835        return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}"
4836
4837    def partitionbyrangepropertydynamic_sql(
4838        self, expression: exp.PartitionByRangePropertyDynamic
4839    ) -> str:
4840        start = self.sql(expression, "start")
4841        end = self.sql(expression, "end")
4842
4843        every = expression.args["every"]
4844        if isinstance(every, exp.Interval) and every.this.is_string:
4845            every.this.replace(exp.Literal.number(every.name))
4846
4847        return f"START {self.wrap(start)} END {self.wrap(end)} EVERY {self.wrap(self.sql(every))}"
4848
4849    def unpivotcolumns_sql(self, expression: exp.UnpivotColumns) -> str:
4850        name = self.sql(expression, "this")
4851        values = self.expressions(expression, flat=True)
4852
4853        return f"NAME {name} VALUE {values}"
4854
4855    def analyzesample_sql(self, expression: exp.AnalyzeSample) -> str:
4856        kind = self.sql(expression, "kind")
4857        sample = self.sql(expression, "sample")
4858        return f"SAMPLE {sample} {kind}"
4859
4860    def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str:
4861        kind = self.sql(expression, "kind")
4862        option = self.sql(expression, "option")
4863        option = f" {option}" if option else ""
4864        this = self.sql(expression, "this")
4865        this = f" {this}" if this else ""
4866        columns = self.expressions(expression)
4867        columns = f" {columns}" if columns else ""
4868        return f"{kind}{option} STATISTICS{this}{columns}"
4869
4870    def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str:
4871        this = self.sql(expression, "this")
4872        columns = self.expressions(expression)
4873        inner_expression = self.sql(expression, "expression")
4874        inner_expression = f" {inner_expression}" if inner_expression else ""
4875        update_options = self.sql(expression, "update_options")
4876        update_options = f" {update_options} UPDATE" if update_options else ""
4877        return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}"
4878
4879    def analyzedelete_sql(self, expression: exp.AnalyzeDelete) -> str:
4880        kind = self.sql(expression, "kind")
4881        kind = f" {kind}" if kind else ""
4882        return f"DELETE{kind} STATISTICS"
4883
4884    def analyzelistchainedrows_sql(self, expression: exp.AnalyzeListChainedRows) -> str:
4885        inner_expression = self.sql(expression, "expression")
4886        return f"LIST CHAINED ROWS{inner_expression}"
4887
4888    def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str:
4889        kind = self.sql(expression, "kind")
4890        this = self.sql(expression, "this")
4891        this = f" {this}" if this else ""
4892        inner_expression = self.sql(expression, "expression")
4893        return f"VALIDATE {kind}{this}{inner_expression}"
4894
4895    def analyze_sql(self, expression: exp.Analyze) -> str:
4896        options = self.expressions(expression, key="options", sep=" ")
4897        options = f" {options}" if options else ""
4898        kind = self.sql(expression, "kind")
4899        kind = f" {kind}" if kind else ""
4900        this = self.sql(expression, "this")
4901        this = f" {this}" if this else ""
4902        mode = self.sql(expression, "mode")
4903        mode = f" {mode}" if mode else ""
4904        properties = self.sql(expression, "properties")
4905        properties = f" {properties}" if properties else ""
4906        partition = self.sql(expression, "partition")
4907        partition = f" {partition}" if partition else ""
4908        inner_expression = self.sql(expression, "expression")
4909        inner_expression = f" {inner_expression}" if inner_expression else ""
4910        return f"ANALYZE{options}{kind}{this}{partition}{mode}{inner_expression}{properties}"
4911
4912    def xmltable_sql(self, expression: exp.XMLTable) -> str:
4913        this = self.sql(expression, "this")
4914        namespaces = self.expressions(expression, key="namespaces")
4915        namespaces = f"XMLNAMESPACES({namespaces}), " if namespaces else ""
4916        passing = self.expressions(expression, key="passing")
4917        passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else ""
4918        columns = self.expressions(expression, key="columns")
4919        columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else ""
4920        by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else ""
4921        return f"XMLTABLE({self.sep('')}{self.indent(namespaces + this + passing + by_ref + columns)}{self.seg(')', sep='')}"
4922
4923    def xmlnamespace_sql(self, expression: exp.XMLNamespace) -> str:
4924        this = self.sql(expression, "this")
4925        return this if isinstance(expression.this, exp.Alias) else f"DEFAULT {this}"
4926
4927    def export_sql(self, expression: exp.Export) -> str:
4928        this = self.sql(expression, "this")
4929        connection = self.sql(expression, "connection")
4930        connection = f"WITH CONNECTION {connection} " if connection else ""
4931        options = self.sql(expression, "options")
4932        return f"EXPORT DATA {connection}{options} AS {this}"
4933
4934    def declare_sql(self, expression: exp.Declare) -> str:
4935        return f"DECLARE {self.expressions(expression, flat=True)}"
4936
4937    def declareitem_sql(self, expression: exp.DeclareItem) -> str:
4938        variable = self.sql(expression, "this")
4939        default = self.sql(expression, "default")
4940        default = f" = {default}" if default else ""
4941
4942        kind = self.sql(expression, "kind")
4943        if isinstance(expression.args.get("kind"), exp.Schema):
4944            kind = f"TABLE {kind}"
4945
4946        return f"{variable} AS {kind}{default}"
4947
4948    def recursivewithsearch_sql(self, expression: exp.RecursiveWithSearch) -> str:
4949        kind = self.sql(expression, "kind")
4950        this = self.sql(expression, "this")
4951        set = self.sql(expression, "expression")
4952        using = self.sql(expression, "using")
4953        using = f" USING {using}" if using else ""
4954
4955        kind_sql = kind if kind == "CYCLE" else f"SEARCH {kind} FIRST BY"
4956
4957        return f"{kind_sql} {this} SET {set}{using}"
4958
4959    def parameterizedagg_sql(self, expression: exp.ParameterizedAgg) -> str:
4960        params = self.expressions(expression, key="params", flat=True)
4961        return self.func(expression.name, *expression.expressions) + f"({params})"
4962
4963    def anonymousaggfunc_sql(self, expression: exp.AnonymousAggFunc) -> str:
4964        return self.func(expression.name, *expression.expressions)
4965
4966    def combinedaggfunc_sql(self, expression: exp.CombinedAggFunc) -> str:
4967        return self.anonymousaggfunc_sql(expression)
4968
4969    def combinedparameterizedagg_sql(self, expression: exp.CombinedParameterizedAgg) -> str:
4970        return self.parameterizedagg_sql(expression)
4971
4972    def show_sql(self, expression: exp.Show) -> str:
4973        self.unsupported("Unsupported SHOW statement")
4974        return ""
4975
4976    def get_put_sql(self, expression: exp.Put | exp.Get) -> str:
4977        # Snowflake GET/PUT statements:
4978        #   PUT <file> <internalStage> <properties>
4979        #   GET <internalStage> <file> <properties>
4980        props = expression.args.get("properties")
4981        props_sql = self.properties(props, prefix=" ", sep=" ", wrapped=False) if props else ""
4982        this = self.sql(expression, "this")
4983        target = self.sql(expression, "target")
4984
4985        if isinstance(expression, exp.Put):
4986            return f"PUT {this} {target}{props_sql}"
4987        else:
4988            return f"GET {target} {this}{props_sql}"
4989
4990    def translatecharacters_sql(self, expression: exp.TranslateCharacters):
4991        this = self.sql(expression, "this")
4992        expr = self.sql(expression, "expression")
4993        with_error = " WITH ERROR" if expression.args.get("with_error") else ""
4994        return f"TRANSLATE({this} USING {expr}{with_error})"

Generator converts a given syntax tree to the corresponding SQL string.

Arguments:
  • pretty: Whether 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 to normalize identifiers to lowercase. Default: False.
  • pad: The pad size in a formatted string. For example, this affects the indentation of a projection in a query, relative to its nesting level. Default: 2.
  • indent: The indentation size in a formatted string. For example, this affects the indentation of subqueries and filters under a WHERE clause. Default: 2.
  • normalize_functions: How to normalize 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: Whether 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 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, Type[sqlglot.dialects.Dialect], NoneType] = None)
700    def __init__(
701        self,
702        pretty: t.Optional[bool] = None,
703        identify: str | bool = False,
704        normalize: bool = False,
705        pad: int = 2,
706        indent: int = 2,
707        normalize_functions: t.Optional[str | bool] = None,
708        unsupported_level: ErrorLevel = ErrorLevel.WARN,
709        max_unsupported: int = 3,
710        leading_comma: bool = False,
711        max_text_width: int = 80,
712        comments: bool = True,
713        dialect: DialectType = None,
714    ):
715        import sqlglot
716        from sqlglot.dialects import Dialect
717
718        self.pretty = pretty if pretty is not None else sqlglot.pretty
719        self.identify = identify
720        self.normalize = normalize
721        self.pad = pad
722        self._indent = indent
723        self.unsupported_level = unsupported_level
724        self.max_unsupported = max_unsupported
725        self.leading_comma = leading_comma
726        self.max_text_width = max_text_width
727        self.comments = comments
728        self.dialect = Dialect.get_or_raise(dialect)
729
730        # This is both a Dialect property and a Generator argument, so we prioritize the latter
731        self.normalize_functions = (
732            self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions
733        )
734
735        self.unsupported_messages: t.List[str] = []
736        self._escaped_quote_end: str = (
737            self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END
738        )
739        self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2
740
741        self._next_name = name_sequence("_t")
742
743        self._identifier_start = self.dialect.IDENTIFIER_START
744        self._identifier_end = self.dialect.IDENTIFIER_END
745
746        self._quote_json_path_key_using_brackets = True
TRANSFORMS: Dict[Type[sqlglot.expressions.Expression], Callable[..., str]] = {<class 'sqlglot.expressions.JSONPathFilter'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathKey'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathRecursive'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathRoot'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathScript'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSelector'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSlice'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSubscript'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathUnion'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathWildcard'>: <function <lambda>>, <class 'sqlglot.expressions.AllowedValuesProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AnalyzeColumns'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AnalyzeWith'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ArrayContainsAll'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ArrayOverlaps'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AutoRefreshProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.BackupProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CaseSpecificColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Ceil'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CommentColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ConnectByRoot'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ConvertToCharset'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CredentialsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DateFormatColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DefaultColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DynamicProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EmptyProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EncodeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EnviromentProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EphemeralColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExcludeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Except'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExternalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Floor'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Get'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.GlobalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.HeapProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.IcebergProperty'>: <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.Intersect'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.IntervalSpan'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Int64'>: <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.NonClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <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.Operator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OutputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PartitionedByBucket'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PartitionByTruncate'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PivotAny'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ProjectionPolicyColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Put'>: <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.SecureProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetConfigProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SharingProperty'>: <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.Stream'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StreamingTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StrictProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SwapTable'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Tags'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TemporaryProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Union'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UnloggedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UsingTemplateProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UsingData'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Uuid'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VarMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ViewAttributeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithProcedureOptions'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithSchemaBindingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithOperator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ForceProperty'>: <function Generator.<lambda>>}
NULL_ORDERING_SUPPORTED: Optional[bool] = True
IGNORE_NULLS_IN_FUNC = False
LOCKING_READS_SUPPORTED = False
EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = True
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
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
SUPPORTS_CREATE_TABLE_LIKE = True
LIKE_PROPERTY_INSIDE_SCHEMA = False
MULTI_ARG_DISTINCT = True
JSON_TYPE_REQUIRED_FOR_EXTRACTION = False
JSON_PATH_BRACKETED_KEY_SUPPORTED = True
JSON_PATH_SINGLE_QUOTE_ESCAPE = False
CAN_IMPLEMENT_ARRAY_ANY = False
SUPPORTS_TO_NUMBER = True
SUPPORTS_WINDOW_EXCLUDE = False
SET_OP_MODIFIERS = True
COPY_PARAMS_ARE_WRAPPED = True
COPY_PARAMS_EQ_REQUIRED = False
COPY_HAS_INTO_KEYWORD = True
TRY_SUPPORTED = True
SUPPORTS_UESCAPE = True
STAR_EXCEPT = 'EXCEPT'
HEX_FUNC = 'HEX'
WITH_PROPERTIES_PREFIX = 'WITH'
QUOTE_JSON_PATH = True
PAD_FILL_PATTERN_IS_REQUIRED = False
SUPPORTS_EXPLODING_PROJECTIONS = True
ARRAY_CONCAT_IS_VAR_LEN = True
SUPPORTS_CONVERT_TIMEZONE = False
SUPPORTS_MEDIAN = True
SUPPORTS_UNIX_SECONDS = False
ALTER_SET_WRAPPED = False
PARSE_JSON_NAME: Optional[str] = 'PARSE_JSON'
ARRAY_SIZE_NAME: str = 'ARRAY_LENGTH'
ALTER_SET_TYPE = 'SET DATA TYPE'
ARRAY_SIZE_DIM_REQUIRED: Optional[bool] = None
TYPE_MAPPING = {<Type.DATETIME2: 'DATETIME2'>: 'TIMESTAMP', <Type.NCHAR: 'NCHAR'>: 'CHAR', <Type.NVARCHAR: 'NVARCHAR'>: 'VARCHAR', <Type.MEDIUMTEXT: 'MEDIUMTEXT'>: 'TEXT', <Type.LONGTEXT: 'LONGTEXT'>: 'TEXT', <Type.TINYTEXT: 'TINYTEXT'>: 'TEXT', <Type.BLOB: 'BLOB'>: 'VARBINARY', <Type.MEDIUMBLOB: 'MEDIUMBLOB'>: 'BLOB', <Type.LONGBLOB: 'LONGBLOB'>: 'BLOB', <Type.TINYBLOB: 'TINYBLOB'>: 'BLOB', <Type.INET: 'INET'>: 'INET', <Type.ROWVERSION: 'ROWVERSION'>: 'VARBINARY', <Type.SMALLDATETIME: 'SMALLDATETIME'>: 'TIMESTAMP'}
TIME_PART_SINGULARS = {'MICROSECONDS': 'MICROSECOND', 'SECONDS': 'SECOND', 'MINUTES': 'MINUTE', 'HOURS': 'HOUR', 'DAYS': 'DAY', 'WEEKS': 'WEEK', 'MONTHS': 'MONTH', 'QUARTERS': 'QUARTER', 'YEARS': 'YEAR'}
AFTER_HAVING_MODIFIER_TRANSFORMS = {'cluster': <function Generator.<lambda>>, 'distribute': <function Generator.<lambda>>, 'sort': <function Generator.<lambda>>, 'windows': <function Generator.<lambda>>, 'qualify': <function Generator.<lambda>>}
TOKEN_MAPPING: Dict[sqlglot.tokens.TokenType, str] = {}
STRUCT_DELIMITER = ('<', '>')
PARAMETER_TOKEN = '@'
NAMED_PLACEHOLDER_TOKEN = ':'
EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: Set[str] = set()
PROPERTIES_LOCATION = {<class 'sqlglot.expressions.AllowedValuesProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <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.BackupProperty'>: <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.DistributedByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DuplicateKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DataBlocksizeProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.DataDeletionProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <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.DynamicProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.DistKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistStyleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EmptyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EncodeProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.EngineProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EnviromentProperty'>: <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.GlobalProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.HeapProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.InheritsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.IcebergProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.IncludeProperty'>: <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.LockProperty'>: <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.SecureProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.SecurityProperty'>: <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.SharingProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.SequenceProperties'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <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.StorageHandlerProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.StreamingTableProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StrictProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Tags'>: <Location.POST_WITH: 'POST_WITH'>, <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.UnloggedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.UsingTemplateProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ViewAttributeProperty'>: <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.WithProcedureOptions'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.WithSchemaBindingProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.WithSystemVersioningProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ForceProperty'>: <Location.POST_CREATE: 'POST_CREATE'>}
RESERVED_KEYWORDS: Set[str] = set()
EXCLUDE_COMMENTS: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Binary'>, <class 'sqlglot.expressions.SetOperation'>)
UNWRAPPED_INTERVAL_VALUES: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Column'>, <class 'sqlglot.expressions.Literal'>, <class 'sqlglot.expressions.Neg'>, <class 'sqlglot.expressions.Paren'>)
PARAMETERIZABLE_TEXT_TYPES = {<Type.NCHAR: 'NCHAR'>, <Type.NVARCHAR: 'NVARCHAR'>, <Type.VARCHAR: 'VARCHAR'>, <Type.CHAR: 'CHAR'>}
EXPRESSIONS_WITHOUT_NESTED_CTES: Set[Type[sqlglot.expressions.Expression]] = set()
RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS: Tuple[Type[sqlglot.expressions.Expression], ...] = ()
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:
748    def generate(self, expression: exp.Expression, copy: bool = True) -> str:
749        """
750        Generates the SQL string corresponding to the given syntax tree.
751
752        Args:
753            expression: The syntax tree.
754            copy: Whether to copy the expression. The generator performs mutations so
755                it is safer to copy.
756
757        Returns:
758            The SQL string corresponding to `expression`.
759        """
760        if copy:
761            expression = expression.copy()
762
763        expression = self.preprocess(expression)
764
765        self.unsupported_messages = []
766        sql = self.sql(expression).strip()
767
768        if self.pretty:
769            sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n")
770
771        if self.unsupported_level == ErrorLevel.IGNORE:
772            return sql
773
774        if self.unsupported_level == ErrorLevel.WARN:
775            for msg in self.unsupported_messages:
776                logger.warning(msg)
777        elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages:
778            raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported))
779
780        return sql

Generates the SQL string corresponding to the given syntax tree.

Arguments:
  • expression: The syntax tree.
  • copy: Whether 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:
782    def preprocess(self, expression: exp.Expression) -> exp.Expression:
783        """Apply generic preprocessing transformations to a given expression."""
784        expression = self._move_ctes_to_top_level(expression)
785
786        if self.ENSURE_BOOLS:
787            from sqlglot.transforms import ensure_bools
788
789            expression = ensure_bools(expression)
790
791        return expression

Apply generic preprocessing transformations to a given expression.

def unsupported(self, message: str) -> None:
804    def unsupported(self, message: str) -> None:
805        if self.unsupported_level == ErrorLevel.IMMEDIATE:
806            raise UnsupportedError(message)
807        self.unsupported_messages.append(message)
def sep(self, sep: str = ' ') -> str:
809    def sep(self, sep: str = " ") -> str:
810        return f"{sep.strip()}\n" if self.pretty else sep
def seg(self, sql: str, sep: str = ' ') -> str:
812    def seg(self, sql: str, sep: str = " ") -> str:
813        return f"{self.sep(sep)}{sql}"
def sanitize_comment(self, comment: str) -> str:
815    def sanitize_comment(self, comment: str) -> str:
816        comment = " " + comment if comment[0].strip() else comment
817        comment = comment + " " if comment[-1].strip() else comment
818
819        if not self.dialect.tokenizer_class.NESTED_COMMENTS:
820            # Necessary workaround to avoid syntax errors due to nesting: /* ... */ ... */
821            comment = comment.replace("*/", "* /")
822
823        return comment
def maybe_comment( self, sql: str, expression: Optional[sqlglot.expressions.Expression] = None, comments: Optional[List[str]] = None, separated: bool = False) -> str:
825    def maybe_comment(
826        self,
827        sql: str,
828        expression: t.Optional[exp.Expression] = None,
829        comments: t.Optional[t.List[str]] = None,
830        separated: bool = False,
831    ) -> str:
832        comments = (
833            ((expression and expression.comments) if comments is None else comments)  # type: ignore
834            if self.comments
835            else None
836        )
837
838        if not comments or isinstance(expression, self.EXCLUDE_COMMENTS):
839            return sql
840
841        comments_sql = " ".join(
842            f"/*{self.sanitize_comment(comment)}*/" for comment in comments if comment
843        )
844
845        if not comments_sql:
846            return sql
847
848        comments_sql = self._replace_line_breaks(comments_sql)
849
850        if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS):
851            return (
852                f"{self.sep()}{comments_sql}{sql}"
853                if not sql or sql[0].isspace()
854                else f"{comments_sql}{self.sep()}{sql}"
855            )
856
857        return f"{sql} {comments_sql}"
def wrap(self, expression: sqlglot.expressions.Expression | str) -> str:
859    def wrap(self, expression: exp.Expression | str) -> str:
860        this_sql = (
861            self.sql(expression)
862            if isinstance(expression, exp.UNWRAPPED_QUERIES)
863            else self.sql(expression, "this")
864        )
865        if not this_sql:
866            return "()"
867
868        this_sql = self.indent(this_sql, level=1, pad=0)
869        return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"
def no_identify(self, func: Callable[..., str], *args, **kwargs) -> str:
871    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
872        original = self.identify
873        self.identify = False
874        result = func(*args, **kwargs)
875        self.identify = original
876        return result
def normalize_func(self, name: str) -> str:
878    def normalize_func(self, name: str) -> str:
879        if self.normalize_functions == "upper" or self.normalize_functions is True:
880            return name.upper()
881        if self.normalize_functions == "lower":
882            return name.lower()
883        return name
def indent( self, sql: str, level: int = 0, pad: Optional[int] = None, skip_first: bool = False, skip_last: bool = False) -> str:
885    def indent(
886        self,
887        sql: str,
888        level: int = 0,
889        pad: t.Optional[int] = None,
890        skip_first: bool = False,
891        skip_last: bool = False,
892    ) -> str:
893        if not self.pretty or not sql:
894            return sql
895
896        pad = self.pad if pad is None else pad
897        lines = sql.split("\n")
898
899        return "\n".join(
900            (
901                line
902                if (skip_first and i == 0) or (skip_last and i == len(lines) - 1)
903                else f"{' ' * (level * self._indent + pad)}{line}"
904            )
905            for i, line in enumerate(lines)
906        )
def sql( self, expression: Union[str, sqlglot.expressions.Expression, NoneType], key: Optional[str] = None, comment: bool = True) -> str:
908    def sql(
909        self,
910        expression: t.Optional[str | exp.Expression],
911        key: t.Optional[str] = None,
912        comment: bool = True,
913    ) -> str:
914        if not expression:
915            return ""
916
917        if isinstance(expression, str):
918            return expression
919
920        if key:
921            value = expression.args.get(key)
922            if value:
923                return self.sql(value)
924            return ""
925
926        transform = self.TRANSFORMS.get(expression.__class__)
927
928        if callable(transform):
929            sql = transform(self, expression)
930        elif isinstance(expression, exp.Expression):
931            exp_handler_name = f"{expression.key}_sql"
932
933            if hasattr(self, exp_handler_name):
934                sql = getattr(self, exp_handler_name)(expression)
935            elif isinstance(expression, exp.Func):
936                sql = self.function_fallback_sql(expression)
937            elif isinstance(expression, exp.Property):
938                sql = self.property_sql(expression)
939            else:
940                raise ValueError(f"Unsupported expression type {expression.__class__.__name__}")
941        else:
942            raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}")
943
944        return self.maybe_comment(sql, expression) if self.comments and comment else sql
def uncache_sql(self, expression: sqlglot.expressions.Uncache) -> str:
946    def uncache_sql(self, expression: exp.Uncache) -> str:
947        table = self.sql(expression, "this")
948        exists_sql = " IF EXISTS" if expression.args.get("exists") else ""
949        return f"UNCACHE TABLE{exists_sql} {table}"
def cache_sql(self, expression: sqlglot.expressions.Cache) -> str:
951    def cache_sql(self, expression: exp.Cache) -> str:
952        lazy = " LAZY" if expression.args.get("lazy") else ""
953        table = self.sql(expression, "this")
954        options = expression.args.get("options")
955        options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else ""
956        sql = self.sql(expression, "expression")
957        sql = f" AS{self.sep()}{sql}" if sql else ""
958        sql = f"CACHE{lazy} TABLE {table}{options}{sql}"
959        return self.prepend_ctes(expression, sql)
def characterset_sql(self, expression: sqlglot.expressions.CharacterSet) -> str:
961    def characterset_sql(self, expression: exp.CharacterSet) -> str:
962        if isinstance(expression.parent, exp.Cast):
963            return f"CHAR CHARACTER SET {self.sql(expression, 'this')}"
964        default = "DEFAULT " if expression.args.get("default") else ""
965        return f"{default}CHARACTER SET={self.sql(expression, 'this')}"
def column_parts(self, expression: sqlglot.expressions.Column) -> str:
967    def column_parts(self, expression: exp.Column) -> str:
968        return ".".join(
969            self.sql(part)
970            for part in (
971                expression.args.get("catalog"),
972                expression.args.get("db"),
973                expression.args.get("table"),
974                expression.args.get("this"),
975            )
976            if part
977        )
def column_sql(self, expression: sqlglot.expressions.Column) -> str:
979    def column_sql(self, expression: exp.Column) -> str:
980        join_mark = " (+)" if expression.args.get("join_mark") else ""
981
982        if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS:
983            join_mark = ""
984            self.unsupported("Outer join syntax using the (+) operator is not supported.")
985
986        return f"{self.column_parts(expression)}{join_mark}"
def columnposition_sql(self, expression: sqlglot.expressions.ColumnPosition) -> str:
988    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
989        this = self.sql(expression, "this")
990        this = f" {this}" if this else ""
991        position = self.sql(expression, "position")
992        return f"{position}{this}"
def columndef_sql(self, expression: sqlglot.expressions.ColumnDef, sep: str = ' ') -> str:
 994    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
 995        column = self.sql(expression, "this")
 996        kind = self.sql(expression, "kind")
 997        constraints = self.expressions(expression, key="constraints", sep=" ", flat=True)
 998        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
 999        kind = f"{sep}{kind}" if kind else ""
1000        constraints = f" {constraints}" if constraints else ""
1001        position = self.sql(expression, "position")
1002        position = f" {position}" if position else ""
1003
1004        if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE:
1005            kind = ""
1006
1007        return f"{exists}{column}{kind}{constraints}{position}"
def columnconstraint_sql(self, expression: sqlglot.expressions.ColumnConstraint) -> str:
1009    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
1010        this = self.sql(expression, "this")
1011        kind_sql = self.sql(expression, "kind").strip()
1012        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql
def computedcolumnconstraint_sql(self, expression: sqlglot.expressions.ComputedColumnConstraint) -> str:
1014    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
1015        this = self.sql(expression, "this")
1016        if expression.args.get("not_null"):
1017            persisted = " PERSISTED NOT NULL"
1018        elif expression.args.get("persisted"):
1019            persisted = " PERSISTED"
1020        else:
1021            persisted = ""
1022
1023        return f"AS {this}{persisted}"
def autoincrementcolumnconstraint_sql(self, _) -> str:
1025    def autoincrementcolumnconstraint_sql(self, _) -> str:
1026        return self.token_sql(TokenType.AUTO_INCREMENT)
def compresscolumnconstraint_sql(self, expression: sqlglot.expressions.CompressColumnConstraint) -> str:
1028    def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str:
1029        if isinstance(expression.this, list):
1030            this = self.wrap(self.expressions(expression, key="this", flat=True))
1031        else:
1032            this = self.sql(expression, "this")
1033
1034        return f"COMPRESS {this}"
def generatedasidentitycolumnconstraint_sql( self, expression: sqlglot.expressions.GeneratedAsIdentityColumnConstraint) -> str:
1036    def generatedasidentitycolumnconstraint_sql(
1037        self, expression: exp.GeneratedAsIdentityColumnConstraint
1038    ) -> str:
1039        this = ""
1040        if expression.this is not None:
1041            on_null = " ON NULL" if expression.args.get("on_null") else ""
1042            this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}"
1043
1044        start = expression.args.get("start")
1045        start = f"START WITH {start}" if start else ""
1046        increment = expression.args.get("increment")
1047        increment = f" INCREMENT BY {increment}" if increment else ""
1048        minvalue = expression.args.get("minvalue")
1049        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
1050        maxvalue = expression.args.get("maxvalue")
1051        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
1052        cycle = expression.args.get("cycle")
1053        cycle_sql = ""
1054
1055        if cycle is not None:
1056            cycle_sql = f"{' NO' if not cycle else ''} CYCLE"
1057            cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql
1058
1059        sequence_opts = ""
1060        if start or increment or cycle_sql:
1061            sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}"
1062            sequence_opts = f" ({sequence_opts.strip()})"
1063
1064        expr = self.sql(expression, "expression")
1065        expr = f"({expr})" if expr else "IDENTITY"
1066
1067        return f"GENERATED{this} AS {expr}{sequence_opts}"
def generatedasrowcolumnconstraint_sql( self, expression: sqlglot.expressions.GeneratedAsRowColumnConstraint) -> str:
1069    def generatedasrowcolumnconstraint_sql(
1070        self, expression: exp.GeneratedAsRowColumnConstraint
1071    ) -> str:
1072        start = "START" if expression.args.get("start") else "END"
1073        hidden = " HIDDEN" if expression.args.get("hidden") else ""
1074        return f"GENERATED ALWAYS AS ROW {start}{hidden}"
def periodforsystemtimeconstraint_sql( self, expression: sqlglot.expressions.PeriodForSystemTimeConstraint) -> str:
1076    def periodforsystemtimeconstraint_sql(
1077        self, expression: exp.PeriodForSystemTimeConstraint
1078    ) -> str:
1079        return f"PERIOD FOR SYSTEM_TIME ({self.sql(expression, 'this')}, {self.sql(expression, 'expression')})"
def notnullcolumnconstraint_sql(self, expression: sqlglot.expressions.NotNullColumnConstraint) -> str:
1081    def notnullcolumnconstraint_sql(self, expression: exp.NotNullColumnConstraint) -> str:
1082        return f"{'' if expression.args.get('allow_null') else 'NOT '}NULL"
def primarykeycolumnconstraint_sql(self, expression: sqlglot.expressions.PrimaryKeyColumnConstraint) -> str:
1084    def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str:
1085        desc = expression.args.get("desc")
1086        if desc is not None:
1087            return f"PRIMARY KEY{' DESC' if desc else ' ASC'}"
1088        options = self.expressions(expression, key="options", flat=True, sep=" ")
1089        options = f" {options}" if options else ""
1090        return f"PRIMARY KEY{options}"
def uniquecolumnconstraint_sql(self, expression: sqlglot.expressions.UniqueColumnConstraint) -> str:
1092    def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str:
1093        this = self.sql(expression, "this")
1094        this = f" {this}" if this else ""
1095        index_type = expression.args.get("index_type")
1096        index_type = f" USING {index_type}" if index_type else ""
1097        on_conflict = self.sql(expression, "on_conflict")
1098        on_conflict = f" {on_conflict}" if on_conflict else ""
1099        nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else ""
1100        options = self.expressions(expression, key="options", flat=True, sep=" ")
1101        options = f" {options}" if options else ""
1102        return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}{options}"
def createable_sql( self, expression: sqlglot.expressions.Create, locations: DefaultDict) -> str:
1104    def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
1105        return self.sql(expression, "this")
def create_sql(self, expression: sqlglot.expressions.Create) -> str:
1107    def create_sql(self, expression: exp.Create) -> str:
1108        kind = self.sql(expression, "kind")
1109        kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind
1110        properties = expression.args.get("properties")
1111        properties_locs = self.locate_properties(properties) if properties else defaultdict()
1112
1113        this = self.createable_sql(expression, properties_locs)
1114
1115        properties_sql = ""
1116        if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get(
1117            exp.Properties.Location.POST_WITH
1118        ):
1119            properties_sql = self.sql(
1120                exp.Properties(
1121                    expressions=[
1122                        *properties_locs[exp.Properties.Location.POST_SCHEMA],
1123                        *properties_locs[exp.Properties.Location.POST_WITH],
1124                    ]
1125                )
1126            )
1127
1128            if properties_locs.get(exp.Properties.Location.POST_SCHEMA):
1129                properties_sql = self.sep() + properties_sql
1130            elif not self.pretty:
1131                # Standalone POST_WITH properties need a leading whitespace in non-pretty mode
1132                properties_sql = f" {properties_sql}"
1133
1134        begin = " BEGIN" if expression.args.get("begin") else ""
1135        end = " END" if expression.args.get("end") else ""
1136
1137        expression_sql = self.sql(expression, "expression")
1138        if expression_sql:
1139            expression_sql = f"{begin}{self.sep()}{expression_sql}{end}"
1140
1141            if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return):
1142                postalias_props_sql = ""
1143                if properties_locs.get(exp.Properties.Location.POST_ALIAS):
1144                    postalias_props_sql = self.properties(
1145                        exp.Properties(
1146                            expressions=properties_locs[exp.Properties.Location.POST_ALIAS]
1147                        ),
1148                        wrapped=False,
1149                    )
1150                postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else ""
1151                expression_sql = f" AS{postalias_props_sql}{expression_sql}"
1152
1153        postindex_props_sql = ""
1154        if properties_locs.get(exp.Properties.Location.POST_INDEX):
1155            postindex_props_sql = self.properties(
1156                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]),
1157                wrapped=False,
1158                prefix=" ",
1159            )
1160
1161        indexes = self.expressions(expression, key="indexes", indent=False, sep=" ")
1162        indexes = f" {indexes}" if indexes else ""
1163        index_sql = indexes + postindex_props_sql
1164
1165        replace = " OR REPLACE" if expression.args.get("replace") else ""
1166        refresh = " OR REFRESH" if expression.args.get("refresh") else ""
1167        unique = " UNIQUE" if expression.args.get("unique") else ""
1168
1169        clustered = expression.args.get("clustered")
1170        if clustered is None:
1171            clustered_sql = ""
1172        elif clustered:
1173            clustered_sql = " CLUSTERED COLUMNSTORE"
1174        else:
1175            clustered_sql = " NONCLUSTERED COLUMNSTORE"
1176
1177        postcreate_props_sql = ""
1178        if properties_locs.get(exp.Properties.Location.POST_CREATE):
1179            postcreate_props_sql = self.properties(
1180                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]),
1181                sep=" ",
1182                prefix=" ",
1183                wrapped=False,
1184            )
1185
1186        modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql))
1187
1188        postexpression_props_sql = ""
1189        if properties_locs.get(exp.Properties.Location.POST_EXPRESSION):
1190            postexpression_props_sql = self.properties(
1191                exp.Properties(
1192                    expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION]
1193                ),
1194                sep=" ",
1195                prefix=" ",
1196                wrapped=False,
1197            )
1198
1199        concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else ""
1200        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
1201        no_schema_binding = (
1202            " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else ""
1203        )
1204
1205        clone = self.sql(expression, "clone")
1206        clone = f" {clone}" if clone else ""
1207
1208        if kind in self.EXPRESSION_PRECEDES_PROPERTIES_CREATABLES:
1209            properties_expression = f"{expression_sql}{properties_sql}"
1210        else:
1211            properties_expression = f"{properties_sql}{expression_sql}"
1212
1213        expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_expression}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}"
1214        return self.prepend_ctes(expression, expression_sql)
def sequenceproperties_sql(self, expression: sqlglot.expressions.SequenceProperties) -> str:
1216    def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str:
1217        start = self.sql(expression, "start")
1218        start = f"START WITH {start}" if start else ""
1219        increment = self.sql(expression, "increment")
1220        increment = f" INCREMENT BY {increment}" if increment else ""
1221        minvalue = self.sql(expression, "minvalue")
1222        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
1223        maxvalue = self.sql(expression, "maxvalue")
1224        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
1225        owned = self.sql(expression, "owned")
1226        owned = f" OWNED BY {owned}" if owned else ""
1227
1228        cache = expression.args.get("cache")
1229        if cache is None:
1230            cache_str = ""
1231        elif cache is True:
1232            cache_str = " CACHE"
1233        else:
1234            cache_str = f" CACHE {cache}"
1235
1236        options = self.expressions(expression, key="options", flat=True, sep=" ")
1237        options = f" {options}" if options else ""
1238
1239        return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip()
def clone_sql(self, expression: sqlglot.expressions.Clone) -> str:
1241    def clone_sql(self, expression: exp.Clone) -> str:
1242        this = self.sql(expression, "this")
1243        shallow = "SHALLOW " if expression.args.get("shallow") else ""
1244        keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE"
1245        return f"{shallow}{keyword} {this}"
def describe_sql(self, expression: sqlglot.expressions.Describe) -> str:
1247    def describe_sql(self, expression: exp.Describe) -> str:
1248        style = expression.args.get("style")
1249        style = f" {style}" if style else ""
1250        partition = self.sql(expression, "partition")
1251        partition = f" {partition}" if partition else ""
1252        format = self.sql(expression, "format")
1253        format = f" {format}" if format else ""
1254
1255        return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}"
def heredoc_sql(self, expression: sqlglot.expressions.Heredoc) -> str:
1257    def heredoc_sql(self, expression: exp.Heredoc) -> str:
1258        tag = self.sql(expression, "tag")
1259        return f"${tag}${self.sql(expression, 'this')}${tag}$"
def prepend_ctes(self, expression: sqlglot.expressions.Expression, sql: str) -> str:
1261    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
1262        with_ = self.sql(expression, "with")
1263        if with_:
1264            sql = f"{with_}{self.sep()}{sql}"
1265        return sql
def with_sql(self, expression: sqlglot.expressions.With) -> str:
1267    def with_sql(self, expression: exp.With) -> str:
1268        sql = self.expressions(expression, flat=True)
1269        recursive = (
1270            "RECURSIVE "
1271            if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive")
1272            else ""
1273        )
1274        search = self.sql(expression, "search")
1275        search = f" {search}" if search else ""
1276
1277        return f"WITH {recursive}{sql}{search}"
def cte_sql(self, expression: sqlglot.expressions.CTE) -> str:
1279    def cte_sql(self, expression: exp.CTE) -> str:
1280        alias = expression.args.get("alias")
1281        if alias:
1282            alias.add_comments(expression.pop_comments())
1283
1284        alias_sql = self.sql(expression, "alias")
1285
1286        materialized = expression.args.get("materialized")
1287        if materialized is False:
1288            materialized = "NOT MATERIALIZED "
1289        elif materialized:
1290            materialized = "MATERIALIZED "
1291
1292        return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}"
def tablealias_sql(self, expression: sqlglot.expressions.TableAlias) -> str:
1294    def tablealias_sql(self, expression: exp.TableAlias) -> str:
1295        alias = self.sql(expression, "this")
1296        columns = self.expressions(expression, key="columns", flat=True)
1297        columns = f"({columns})" if columns else ""
1298
1299        if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS:
1300            columns = ""
1301            self.unsupported("Named columns are not supported in table alias.")
1302
1303        if not alias and not self.dialect.UNNEST_COLUMN_ONLY:
1304            alias = self._next_name()
1305
1306        return f"{alias}{columns}"
def bitstring_sql(self, expression: sqlglot.expressions.BitString) -> str:
1308    def bitstring_sql(self, expression: exp.BitString) -> str:
1309        this = self.sql(expression, "this")
1310        if self.dialect.BIT_START:
1311            return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}"
1312        return f"{int(this, 2)}"
def hexstring_sql( self, expression: sqlglot.expressions.HexString, binary_function_repr: Optional[str] = None) -> str:
1314    def hexstring_sql(
1315        self, expression: exp.HexString, binary_function_repr: t.Optional[str] = None
1316    ) -> str:
1317        this = self.sql(expression, "this")
1318        is_integer_type = expression.args.get("is_integer")
1319
1320        if (is_integer_type and not self.dialect.HEX_STRING_IS_INTEGER_TYPE) or (
1321            not self.dialect.HEX_START and not binary_function_repr
1322        ):
1323            # Integer representation will be returned if:
1324            # - The read dialect treats the hex value as integer literal but not the write
1325            # - The transpilation is not supported (write dialect hasn't set HEX_START or the param flag)
1326            return f"{int(this, 16)}"
1327
1328        if not is_integer_type:
1329            # Read dialect treats the hex value as BINARY/BLOB
1330            if binary_function_repr:
1331                # The write dialect supports the transpilation to its equivalent BINARY/BLOB
1332                return self.func(binary_function_repr, exp.Literal.string(this))
1333            if self.dialect.HEX_STRING_IS_INTEGER_TYPE:
1334                # The write dialect does not support the transpilation, it'll treat the hex value as INTEGER
1335                self.unsupported("Unsupported transpilation from BINARY/BLOB hex string")
1336
1337        return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"
def bytestring_sql(self, expression: sqlglot.expressions.ByteString) -> str:
1339    def bytestring_sql(self, expression: exp.ByteString) -> str:
1340        this = self.sql(expression, "this")
1341        if self.dialect.BYTE_START:
1342            return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}"
1343        return this
def unicodestring_sql(self, expression: sqlglot.expressions.UnicodeString) -> str:
1345    def unicodestring_sql(self, expression: exp.UnicodeString) -> str:
1346        this = self.sql(expression, "this")
1347        escape = expression.args.get("escape")
1348
1349        if self.dialect.UNICODE_START:
1350            escape_substitute = r"\\\1"
1351            left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END
1352        else:
1353            escape_substitute = r"\\u\1"
1354            left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END
1355
1356        if escape:
1357            escape_pattern = re.compile(rf"{escape.name}(\d+)")
1358            escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else ""
1359        else:
1360            escape_pattern = ESCAPED_UNICODE_RE
1361            escape_sql = ""
1362
1363        if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE):
1364            this = escape_pattern.sub(escape_substitute, this)
1365
1366        return f"{left_quote}{this}{right_quote}{escape_sql}"
def rawstring_sql(self, expression: sqlglot.expressions.RawString) -> str:
1368    def rawstring_sql(self, expression: exp.RawString) -> str:
1369        string = expression.this
1370        if "\\" in self.dialect.tokenizer_class.STRING_ESCAPES:
1371            string = string.replace("\\", "\\\\")
1372
1373        string = self.escape_str(string, escape_backslash=False)
1374        return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}"
def datatypeparam_sql(self, expression: sqlglot.expressions.DataTypeParam) -> str:
1376    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
1377        this = self.sql(expression, "this")
1378        specifier = self.sql(expression, "expression")
1379        specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else ""
1380        return f"{this}{specifier}"
def datatype_sql(self, expression: sqlglot.expressions.DataType) -> str:
1382    def datatype_sql(self, expression: exp.DataType) -> str:
1383        nested = ""
1384        values = ""
1385        interior = self.expressions(expression, flat=True)
1386
1387        type_value = expression.this
1388        if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"):
1389            type_sql = self.sql(expression, "kind")
1390        else:
1391            type_sql = (
1392                self.TYPE_MAPPING.get(type_value, type_value.value)
1393                if isinstance(type_value, exp.DataType.Type)
1394                else type_value
1395            )
1396
1397        if interior:
1398            if expression.args.get("nested"):
1399                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
1400                if expression.args.get("values") is not None:
1401                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
1402                    values = self.expressions(expression, key="values", flat=True)
1403                    values = f"{delimiters[0]}{values}{delimiters[1]}"
1404            elif type_value == exp.DataType.Type.INTERVAL:
1405                nested = f" {interior}"
1406            else:
1407                nested = f"({interior})"
1408
1409        type_sql = f"{type_sql}{nested}{values}"
1410        if self.TZ_TO_WITH_TIME_ZONE and type_value in (
1411            exp.DataType.Type.TIMETZ,
1412            exp.DataType.Type.TIMESTAMPTZ,
1413        ):
1414            type_sql = f"{type_sql} WITH TIME ZONE"
1415
1416        return type_sql
def directory_sql(self, expression: sqlglot.expressions.Directory) -> str:
1418    def directory_sql(self, expression: exp.Directory) -> str:
1419        local = "LOCAL " if expression.args.get("local") else ""
1420        row_format = self.sql(expression, "row_format")
1421        row_format = f" {row_format}" if row_format else ""
1422        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"
def delete_sql(self, expression: sqlglot.expressions.Delete) -> str:
1424    def delete_sql(self, expression: exp.Delete) -> str:
1425        this = self.sql(expression, "this")
1426        this = f" FROM {this}" if this else ""
1427        using = self.sql(expression, "using")
1428        using = f" USING {using}" if using else ""
1429        cluster = self.sql(expression, "cluster")
1430        cluster = f" {cluster}" if cluster else ""
1431        where = self.sql(expression, "where")
1432        returning = self.sql(expression, "returning")
1433        limit = self.sql(expression, "limit")
1434        tables = self.expressions(expression, key="tables")
1435        tables = f" {tables}" if tables else ""
1436        if self.RETURNING_END:
1437            expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}"
1438        else:
1439            expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}"
1440        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")
def drop_sql(self, expression: sqlglot.expressions.Drop) -> str:
1442    def drop_sql(self, expression: exp.Drop) -> str:
1443        this = self.sql(expression, "this")
1444        expressions = self.expressions(expression, flat=True)
1445        expressions = f" ({expressions})" if expressions else ""
1446        kind = expression.args["kind"]
1447        kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind
1448        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
1449        concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else ""
1450        on_cluster = self.sql(expression, "cluster")
1451        on_cluster = f" {on_cluster}" if on_cluster else ""
1452        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
1453        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
1454        cascade = " CASCADE" if expression.args.get("cascade") else ""
1455        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
1456        purge = " PURGE" if expression.args.get("purge") else ""
1457        return f"DROP{temporary}{materialized} {kind}{concurrently_sql}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}"
def set_operation(self, expression: sqlglot.expressions.SetOperation) -> str:
1459    def set_operation(self, expression: exp.SetOperation) -> str:
1460        op_type = type(expression)
1461        op_name = op_type.key.upper()
1462
1463        distinct = expression.args.get("distinct")
1464        if (
1465            distinct is False
1466            and op_type in (exp.Except, exp.Intersect)
1467            and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE
1468        ):
1469            self.unsupported(f"{op_name} ALL is not supported")
1470
1471        default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type]
1472
1473        if distinct is None:
1474            distinct = default_distinct
1475            if distinct is None:
1476                self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified")
1477
1478        if distinct is default_distinct:
1479            distinct_or_all = ""
1480        else:
1481            distinct_or_all = " DISTINCT" if distinct else " ALL"
1482
1483        side_kind = " ".join(filter(None, [expression.side, expression.kind]))
1484        side_kind = f"{side_kind} " if side_kind else ""
1485
1486        by_name = " BY NAME" if expression.args.get("by_name") else ""
1487        on = self.expressions(expression, key="on", flat=True)
1488        on = f" ON ({on})" if on else ""
1489
1490        return f"{side_kind}{op_name}{distinct_or_all}{by_name}{on}"
def set_operations(self, expression: sqlglot.expressions.SetOperation) -> str:
1492    def set_operations(self, expression: exp.SetOperation) -> str:
1493        if not self.SET_OP_MODIFIERS:
1494            limit = expression.args.get("limit")
1495            order = expression.args.get("order")
1496
1497            if limit or order:
1498                select = self._move_ctes_to_top_level(
1499                    exp.subquery(expression, "_l_0", copy=False).select("*", copy=False)
1500                )
1501
1502                if limit:
1503                    select = select.limit(limit.pop(), copy=False)
1504                if order:
1505                    select = select.order_by(order.pop(), copy=False)
1506                return self.sql(select)
1507
1508        sqls: t.List[str] = []
1509        stack: t.List[t.Union[str, exp.Expression]] = [expression]
1510
1511        while stack:
1512            node = stack.pop()
1513
1514            if isinstance(node, exp.SetOperation):
1515                stack.append(node.expression)
1516                stack.append(
1517                    self.maybe_comment(
1518                        self.set_operation(node), comments=node.comments, separated=True
1519                    )
1520                )
1521                stack.append(node.this)
1522            else:
1523                sqls.append(self.sql(node))
1524
1525        this = self.sep().join(sqls)
1526        this = self.query_modifiers(expression, this)
1527        return self.prepend_ctes(expression, this)
def fetch_sql(self, expression: sqlglot.expressions.Fetch) -> str:
1529    def fetch_sql(self, expression: exp.Fetch) -> str:
1530        direction = expression.args.get("direction")
1531        direction = f" {direction}" if direction else ""
1532        count = self.sql(expression, "count")
1533        count = f" {count}" if count else ""
1534        limit_options = self.sql(expression, "limit_options")
1535        limit_options = f"{limit_options}" if limit_options else " ROWS ONLY"
1536        return f"{self.seg('FETCH')}{direction}{count}{limit_options}"
def limitoptions_sql(self, expression: sqlglot.expressions.LimitOptions) -> str:
1538    def limitoptions_sql(self, expression: exp.LimitOptions) -> str:
1539        percent = " PERCENT" if expression.args.get("percent") else ""
1540        rows = " ROWS" if expression.args.get("rows") else ""
1541        with_ties = " WITH TIES" if expression.args.get("with_ties") else ""
1542        if not with_ties and rows:
1543            with_ties = " ONLY"
1544        return f"{percent}{rows}{with_ties}"
def filter_sql(self, expression: sqlglot.expressions.Filter) -> str:
1546    def filter_sql(self, expression: exp.Filter) -> str:
1547        if self.AGGREGATE_FILTER_SUPPORTED:
1548            this = self.sql(expression, "this")
1549            where = self.sql(expression, "expression").strip()
1550            return f"{this} FILTER({where})"
1551
1552        agg = expression.this
1553        agg_arg = agg.this
1554        cond = expression.expression.this
1555        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
1556        return self.sql(agg)
def hint_sql(self, expression: sqlglot.expressions.Hint) -> str:
1558    def hint_sql(self, expression: exp.Hint) -> str:
1559        if not self.QUERY_HINTS:
1560            self.unsupported("Hints are not supported")
1561            return ""
1562
1563        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"
def indexparameters_sql(self, expression: sqlglot.expressions.IndexParameters) -> str:
1565    def indexparameters_sql(self, expression: exp.IndexParameters) -> str:
1566        using = self.sql(expression, "using")
1567        using = f" USING {using}" if using else ""
1568        columns = self.expressions(expression, key="columns", flat=True)
1569        columns = f"({columns})" if columns else ""
1570        partition_by = self.expressions(expression, key="partition_by", flat=True)
1571        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
1572        where = self.sql(expression, "where")
1573        include = self.expressions(expression, key="include", flat=True)
1574        if include:
1575            include = f" INCLUDE ({include})"
1576        with_storage = self.expressions(expression, key="with_storage", flat=True)
1577        with_storage = f" WITH ({with_storage})" if with_storage else ""
1578        tablespace = self.sql(expression, "tablespace")
1579        tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else ""
1580        on = self.sql(expression, "on")
1581        on = f" ON {on}" if on else ""
1582
1583        return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"
def index_sql(self, expression: sqlglot.expressions.Index) -> str:
1585    def index_sql(self, expression: exp.Index) -> str:
1586        unique = "UNIQUE " if expression.args.get("unique") else ""
1587        primary = "PRIMARY " if expression.args.get("primary") else ""
1588        amp = "AMP " if expression.args.get("amp") else ""
1589        name = self.sql(expression, "this")
1590        name = f"{name} " if name else ""
1591        table = self.sql(expression, "table")
1592        table = f"{self.INDEX_ON} {table}" if table else ""
1593
1594        index = "INDEX " if not table else ""
1595
1596        params = self.sql(expression, "params")
1597        return f"{unique}{primary}{amp}{index}{name}{table}{params}"
def identifier_sql(self, expression: sqlglot.expressions.Identifier) -> str:
1599    def identifier_sql(self, expression: exp.Identifier) -> str:
1600        text = expression.name
1601        lower = text.lower()
1602        text = lower if self.normalize and not expression.quoted else text
1603        text = text.replace(self._identifier_end, self._escaped_identifier_end)
1604        if (
1605            expression.quoted
1606            or self.dialect.can_identify(text, self.identify)
1607            or lower in self.RESERVED_KEYWORDS
1608            or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
1609        ):
1610            text = f"{self._identifier_start}{text}{self._identifier_end}"
1611        return text
def hex_sql(self, expression: sqlglot.expressions.Hex) -> str:
1613    def hex_sql(self, expression: exp.Hex) -> str:
1614        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
1615        if self.dialect.HEX_LOWERCASE:
1616            text = self.func("LOWER", text)
1617
1618        return text
def lowerhex_sql(self, expression: sqlglot.expressions.LowerHex) -> str:
1620    def lowerhex_sql(self, expression: exp.LowerHex) -> str:
1621        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
1622        if not self.dialect.HEX_LOWERCASE:
1623            text = self.func("LOWER", text)
1624        return text
def inputoutputformat_sql(self, expression: sqlglot.expressions.InputOutputFormat) -> str:
1626    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
1627        input_format = self.sql(expression, "input_format")
1628        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
1629        output_format = self.sql(expression, "output_format")
1630        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
1631        return self.sep().join((input_format, output_format))
def national_sql(self, expression: sqlglot.expressions.National, prefix: str = 'N') -> str:
1633    def national_sql(self, expression: exp.National, prefix: str = "N") -> str:
1634        string = self.sql(exp.Literal.string(expression.name))
1635        return f"{prefix}{string}"
def partition_sql(self, expression: sqlglot.expressions.Partition) -> str:
1637    def partition_sql(self, expression: exp.Partition) -> str:
1638        partition_keyword = "SUBPARTITION" if expression.args.get("subpartition") else "PARTITION"
1639        return f"{partition_keyword}({self.expressions(expression, flat=True)})"
def properties_sql(self, expression: sqlglot.expressions.Properties) -> str:
1641    def properties_sql(self, expression: exp.Properties) -> str:
1642        root_properties = []
1643        with_properties = []
1644
1645        for p in expression.expressions:
1646            p_loc = self.PROPERTIES_LOCATION[p.__class__]
1647            if p_loc == exp.Properties.Location.POST_WITH:
1648                with_properties.append(p)
1649            elif p_loc == exp.Properties.Location.POST_SCHEMA:
1650                root_properties.append(p)
1651
1652        root_props = self.root_properties(exp.Properties(expressions=root_properties))
1653        with_props = self.with_properties(exp.Properties(expressions=with_properties))
1654
1655        if root_props and with_props and not self.pretty:
1656            with_props = " " + with_props
1657
1658        return root_props + with_props
def root_properties(self, properties: sqlglot.expressions.Properties) -> str:
1660    def root_properties(self, properties: exp.Properties) -> str:
1661        if properties.expressions:
1662            return self.expressions(properties, indent=False, sep=" ")
1663        return ""
def properties( self, properties: sqlglot.expressions.Properties, prefix: str = '', sep: str = ', ', suffix: str = '', wrapped: bool = True) -> str:
1665    def properties(
1666        self,
1667        properties: exp.Properties,
1668        prefix: str = "",
1669        sep: str = ", ",
1670        suffix: str = "",
1671        wrapped: bool = True,
1672    ) -> str:
1673        if properties.expressions:
1674            expressions = self.expressions(properties, sep=sep, indent=False)
1675            if expressions:
1676                expressions = self.wrap(expressions) if wrapped else expressions
1677                return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}"
1678        return ""
def with_properties(self, properties: sqlglot.expressions.Properties) -> str:
1680    def with_properties(self, properties: exp.Properties) -> str:
1681        return self.properties(properties, prefix=self.seg(self.WITH_PROPERTIES_PREFIX, sep=""))
def locate_properties(self, properties: sqlglot.expressions.Properties) -> DefaultDict:
1683    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
1684        properties_locs = defaultdict(list)
1685        for p in properties.expressions:
1686            p_loc = self.PROPERTIES_LOCATION[p.__class__]
1687            if p_loc != exp.Properties.Location.UNSUPPORTED:
1688                properties_locs[p_loc].append(p)
1689            else:
1690                self.unsupported(f"Unsupported property {p.key}")
1691
1692        return properties_locs
def property_name( self, expression: sqlglot.expressions.Property, string_key: bool = False) -> str:
1694    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
1695        if isinstance(expression.this, exp.Dot):
1696            return self.sql(expression, "this")
1697        return f"'{expression.name}'" if string_key else expression.name
def property_sql(self, expression: sqlglot.expressions.Property) -> str:
1699    def property_sql(self, expression: exp.Property) -> str:
1700        property_cls = expression.__class__
1701        if property_cls == exp.Property:
1702            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
1703
1704        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
1705        if not property_name:
1706            self.unsupported(f"Unsupported property {expression.key}")
1707
1708        return f"{property_name}={self.sql(expression, 'this')}"
def likeproperty_sql(self, expression: sqlglot.expressions.LikeProperty) -> str:
1710    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
1711        if self.SUPPORTS_CREATE_TABLE_LIKE:
1712            options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
1713            options = f" {options}" if options else ""
1714
1715            like = f"LIKE {self.sql(expression, 'this')}{options}"
1716            if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema):
1717                like = f"({like})"
1718
1719            return like
1720
1721        if expression.expressions:
1722            self.unsupported("Transpilation of LIKE property options is unsupported")
1723
1724        select = exp.select("*").from_(expression.this).limit(0)
1725        return f"AS {self.sql(select)}"
def fallbackproperty_sql(self, expression: sqlglot.expressions.FallbackProperty) -> str:
1727    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
1728        no = "NO " if expression.args.get("no") else ""
1729        protection = " PROTECTION" if expression.args.get("protection") else ""
1730        return f"{no}FALLBACK{protection}"
def journalproperty_sql(self, expression: sqlglot.expressions.JournalProperty) -> str:
1732    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
1733        no = "NO " if expression.args.get("no") else ""
1734        local = expression.args.get("local")
1735        local = f"{local} " if local else ""
1736        dual = "DUAL " if expression.args.get("dual") else ""
1737        before = "BEFORE " if expression.args.get("before") else ""
1738        after = "AFTER " if expression.args.get("after") else ""
1739        return f"{no}{local}{dual}{before}{after}JOURNAL"
def freespaceproperty_sql(self, expression: sqlglot.expressions.FreespaceProperty) -> str:
1741    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
1742        freespace = self.sql(expression, "this")
1743        percent = " PERCENT" if expression.args.get("percent") else ""
1744        return f"FREESPACE={freespace}{percent}"
def checksumproperty_sql(self, expression: sqlglot.expressions.ChecksumProperty) -> str:
1746    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
1747        if expression.args.get("default"):
1748            property = "DEFAULT"
1749        elif expression.args.get("on"):
1750            property = "ON"
1751        else:
1752            property = "OFF"
1753        return f"CHECKSUM={property}"
def mergeblockratioproperty_sql(self, expression: sqlglot.expressions.MergeBlockRatioProperty) -> str:
1755    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
1756        if expression.args.get("no"):
1757            return "NO MERGEBLOCKRATIO"
1758        if expression.args.get("default"):
1759            return "DEFAULT MERGEBLOCKRATIO"
1760
1761        percent = " PERCENT" if expression.args.get("percent") else ""
1762        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"
def datablocksizeproperty_sql(self, expression: sqlglot.expressions.DataBlocksizeProperty) -> str:
1764    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
1765        default = expression.args.get("default")
1766        minimum = expression.args.get("minimum")
1767        maximum = expression.args.get("maximum")
1768        if default or minimum or maximum:
1769            if default:
1770                prop = "DEFAULT"
1771            elif minimum:
1772                prop = "MINIMUM"
1773            else:
1774                prop = "MAXIMUM"
1775            return f"{prop} DATABLOCKSIZE"
1776        units = expression.args.get("units")
1777        units = f" {units}" if units else ""
1778        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"
def blockcompressionproperty_sql(self, expression: sqlglot.expressions.BlockCompressionProperty) -> str:
1780    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
1781        autotemp = expression.args.get("autotemp")
1782        always = expression.args.get("always")
1783        default = expression.args.get("default")
1784        manual = expression.args.get("manual")
1785        never = expression.args.get("never")
1786
1787        if autotemp is not None:
1788            prop = f"AUTOTEMP({self.expressions(autotemp)})"
1789        elif always:
1790            prop = "ALWAYS"
1791        elif default:
1792            prop = "DEFAULT"
1793        elif manual:
1794            prop = "MANUAL"
1795        elif never:
1796            prop = "NEVER"
1797        return f"BLOCKCOMPRESSION={prop}"
def isolatedloadingproperty_sql(self, expression: sqlglot.expressions.IsolatedLoadingProperty) -> str:
1799    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
1800        no = expression.args.get("no")
1801        no = " NO" if no else ""
1802        concurrent = expression.args.get("concurrent")
1803        concurrent = " CONCURRENT" if concurrent else ""
1804        target = self.sql(expression, "target")
1805        target = f" {target}" if target else ""
1806        return f"WITH{no}{concurrent} ISOLATED LOADING{target}"
def partitionboundspec_sql(self, expression: sqlglot.expressions.PartitionBoundSpec) -> str:
1808    def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str:
1809        if isinstance(expression.this, list):
1810            return f"IN ({self.expressions(expression, key='this', flat=True)})"
1811        if expression.this:
1812            modulus = self.sql(expression, "this")
1813            remainder = self.sql(expression, "expression")
1814            return f"WITH (MODULUS {modulus}, REMAINDER {remainder})"
1815
1816        from_expressions = self.expressions(expression, key="from_expressions", flat=True)
1817        to_expressions = self.expressions(expression, key="to_expressions", flat=True)
1818        return f"FROM ({from_expressions}) TO ({to_expressions})"
def partitionedofproperty_sql(self, expression: sqlglot.expressions.PartitionedOfProperty) -> str:
1820    def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str:
1821        this = self.sql(expression, "this")
1822
1823        for_values_or_default = expression.expression
1824        if isinstance(for_values_or_default, exp.PartitionBoundSpec):
1825            for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}"
1826        else:
1827            for_values_or_default = " DEFAULT"
1828
1829        return f"PARTITION OF {this}{for_values_or_default}"
def lockingproperty_sql(self, expression: sqlglot.expressions.LockingProperty) -> str:
1831    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
1832        kind = expression.args.get("kind")
1833        this = f" {self.sql(expression, 'this')}" if expression.this else ""
1834        for_or_in = expression.args.get("for_or_in")
1835        for_or_in = f" {for_or_in}" if for_or_in else ""
1836        lock_type = expression.args.get("lock_type")
1837        override = " OVERRIDE" if expression.args.get("override") else ""
1838        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"
def withdataproperty_sql(self, expression: sqlglot.expressions.WithDataProperty) -> str:
1840    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
1841        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
1842        statistics = expression.args.get("statistics")
1843        statistics_sql = ""
1844        if statistics is not None:
1845            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
1846        return f"{data_sql}{statistics_sql}"
def withsystemversioningproperty_sql( self, expression: sqlglot.expressions.WithSystemVersioningProperty) -> str:
1848    def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str:
1849        this = self.sql(expression, "this")
1850        this = f"HISTORY_TABLE={this}" if this else ""
1851        data_consistency: t.Optional[str] = self.sql(expression, "data_consistency")
1852        data_consistency = (
1853            f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None
1854        )
1855        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
1856        retention_period = (
1857            f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None
1858        )
1859
1860        if this:
1861            on_sql = self.func("ON", this, data_consistency, retention_period)
1862        else:
1863            on_sql = "ON" if expression.args.get("on") else "OFF"
1864
1865        sql = f"SYSTEM_VERSIONING={on_sql}"
1866
1867        return f"WITH({sql})" if expression.args.get("with") else sql
def insert_sql(self, expression: sqlglot.expressions.Insert) -> str:
1869    def insert_sql(self, expression: exp.Insert) -> str:
1870        hint = self.sql(expression, "hint")
1871        overwrite = expression.args.get("overwrite")
1872
1873        if isinstance(expression.this, exp.Directory):
1874            this = " OVERWRITE" if overwrite else " INTO"
1875        else:
1876            this = self.INSERT_OVERWRITE if overwrite else " INTO"
1877
1878        stored = self.sql(expression, "stored")
1879        stored = f" {stored}" if stored else ""
1880        alternative = expression.args.get("alternative")
1881        alternative = f" OR {alternative}" if alternative else ""
1882        ignore = " IGNORE" if expression.args.get("ignore") else ""
1883        is_function = expression.args.get("is_function")
1884        if is_function:
1885            this = f"{this} FUNCTION"
1886        this = f"{this} {self.sql(expression, 'this')}"
1887
1888        exists = " IF EXISTS" if expression.args.get("exists") else ""
1889        where = self.sql(expression, "where")
1890        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
1891        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
1892        on_conflict = self.sql(expression, "conflict")
1893        on_conflict = f" {on_conflict}" if on_conflict else ""
1894        by_name = " BY NAME" if expression.args.get("by_name") else ""
1895        returning = self.sql(expression, "returning")
1896
1897        if self.RETURNING_END:
1898            expression_sql = f"{expression_sql}{on_conflict}{returning}"
1899        else:
1900            expression_sql = f"{returning}{expression_sql}{on_conflict}"
1901
1902        partition_by = self.sql(expression, "partition")
1903        partition_by = f" {partition_by}" if partition_by else ""
1904        settings = self.sql(expression, "settings")
1905        settings = f" {settings}" if settings else ""
1906
1907        source = self.sql(expression, "source")
1908        source = f"TABLE {source}" if source else ""
1909
1910        sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}"
1911        return self.prepend_ctes(expression, sql)
def introducer_sql(self, expression: sqlglot.expressions.Introducer) -> str:
1913    def introducer_sql(self, expression: exp.Introducer) -> str:
1914        return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}"
def kill_sql(self, expression: sqlglot.expressions.Kill) -> str:
1916    def kill_sql(self, expression: exp.Kill) -> str:
1917        kind = self.sql(expression, "kind")
1918        kind = f" {kind}" if kind else ""
1919        this = self.sql(expression, "this")
1920        this = f" {this}" if this else ""
1921        return f"KILL{kind}{this}"
def pseudotype_sql(self, expression: sqlglot.expressions.PseudoType) -> str:
1923    def pseudotype_sql(self, expression: exp.PseudoType) -> str:
1924        return expression.name
def objectidentifier_sql(self, expression: sqlglot.expressions.ObjectIdentifier) -> str:
1926    def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str:
1927        return expression.name
def onconflict_sql(self, expression: sqlglot.expressions.OnConflict) -> str:
1929    def onconflict_sql(self, expression: exp.OnConflict) -> str:
1930        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
1931
1932        constraint = self.sql(expression, "constraint")
1933        constraint = f" ON CONSTRAINT {constraint}" if constraint else ""
1934
1935        conflict_keys = self.expressions(expression, key="conflict_keys", flat=True)
1936        conflict_keys = f"({conflict_keys}) " if conflict_keys else " "
1937        action = self.sql(expression, "action")
1938
1939        expressions = self.expressions(expression, flat=True)
1940        if expressions:
1941            set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
1942            expressions = f" {set_keyword}{expressions}"
1943
1944        where = self.sql(expression, "where")
1945        return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}"
def returning_sql(self, expression: sqlglot.expressions.Returning) -> str:
1947    def returning_sql(self, expression: exp.Returning) -> str:
1948        return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}"
def rowformatdelimitedproperty_sql(self, expression: sqlglot.expressions.RowFormatDelimitedProperty) -> str:
1950    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
1951        fields = self.sql(expression, "fields")
1952        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
1953        escaped = self.sql(expression, "escaped")
1954        escaped = f" ESCAPED BY {escaped}" if escaped else ""
1955        items = self.sql(expression, "collection_items")
1956        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
1957        keys = self.sql(expression, "map_keys")
1958        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
1959        lines = self.sql(expression, "lines")
1960        lines = f" LINES TERMINATED BY {lines}" if lines else ""
1961        null = self.sql(expression, "null")
1962        null = f" NULL DEFINED AS {null}" if null else ""
1963        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"
def withtablehint_sql(self, expression: sqlglot.expressions.WithTableHint) -> str:
1965    def withtablehint_sql(self, expression: exp.WithTableHint) -> str:
1966        return f"WITH ({self.expressions(expression, flat=True)})"
def indextablehint_sql(self, expression: sqlglot.expressions.IndexTableHint) -> str:
1968    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
1969        this = f"{self.sql(expression, 'this')} INDEX"
1970        target = self.sql(expression, "target")
1971        target = f" FOR {target}" if target else ""
1972        return f"{this}{target} ({self.expressions(expression, flat=True)})"
def historicaldata_sql(self, expression: sqlglot.expressions.HistoricalData) -> str:
1974    def historicaldata_sql(self, expression: exp.HistoricalData) -> str:
1975        this = self.sql(expression, "this")
1976        kind = self.sql(expression, "kind")
1977        expr = self.sql(expression, "expression")
1978        return f"{this} ({kind} => {expr})"
def table_parts(self, expression: sqlglot.expressions.Table) -> str:
1980    def table_parts(self, expression: exp.Table) -> str:
1981        return ".".join(
1982            self.sql(part)
1983            for part in (
1984                expression.args.get("catalog"),
1985                expression.args.get("db"),
1986                expression.args.get("this"),
1987            )
1988            if part is not None
1989        )
def table_sql(self, expression: sqlglot.expressions.Table, sep: str = ' AS ') -> str:
1991    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
1992        table = self.table_parts(expression)
1993        only = "ONLY " if expression.args.get("only") else ""
1994        partition = self.sql(expression, "partition")
1995        partition = f" {partition}" if partition else ""
1996        version = self.sql(expression, "version")
1997        version = f" {version}" if version else ""
1998        alias = self.sql(expression, "alias")
1999        alias = f"{sep}{alias}" if alias else ""
2000
2001        sample = self.sql(expression, "sample")
2002        if self.dialect.ALIAS_POST_TABLESAMPLE:
2003            sample_pre_alias = sample
2004            sample_post_alias = ""
2005        else:
2006            sample_pre_alias = ""
2007            sample_post_alias = sample
2008
2009        hints = self.expressions(expression, key="hints", sep=" ")
2010        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
2011        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
2012        joins = self.indent(
2013            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
2014        )
2015        laterals = self.expressions(expression, key="laterals", sep="")
2016
2017        file_format = self.sql(expression, "format")
2018        if file_format:
2019            pattern = self.sql(expression, "pattern")
2020            pattern = f", PATTERN => {pattern}" if pattern else ""
2021            file_format = f" (FILE_FORMAT => {file_format}{pattern})"
2022
2023        ordinality = expression.args.get("ordinality") or ""
2024        if ordinality:
2025            ordinality = f" WITH ORDINALITY{alias}"
2026            alias = ""
2027
2028        when = self.sql(expression, "when")
2029        if when:
2030            table = f"{table} {when}"
2031
2032        changes = self.sql(expression, "changes")
2033        changes = f" {changes}" if changes else ""
2034
2035        rows_from = self.expressions(expression, key="rows_from")
2036        if rows_from:
2037            table = f"ROWS FROM {self.wrap(rows_from)}"
2038
2039        return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}"
def tablefromrows_sql(self, expression: sqlglot.expressions.TableFromRows) -> str:
2041    def tablefromrows_sql(self, expression: exp.TableFromRows) -> str:
2042        table = self.func("TABLE", expression.this)
2043        alias = self.sql(expression, "alias")
2044        alias = f" AS {alias}" if alias else ""
2045        sample = self.sql(expression, "sample")
2046        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
2047        joins = self.indent(
2048            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
2049        )
2050        return f"{table}{alias}{pivots}{sample}{joins}"
def tablesample_sql( self, expression: sqlglot.expressions.TableSample, tablesample_keyword: Optional[str] = None) -> str:
2052    def tablesample_sql(
2053        self,
2054        expression: exp.TableSample,
2055        tablesample_keyword: t.Optional[str] = None,
2056    ) -> str:
2057        method = self.sql(expression, "method")
2058        method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else ""
2059        numerator = self.sql(expression, "bucket_numerator")
2060        denominator = self.sql(expression, "bucket_denominator")
2061        field = self.sql(expression, "bucket_field")
2062        field = f" ON {field}" if field else ""
2063        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
2064        seed = self.sql(expression, "seed")
2065        seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else ""
2066
2067        size = self.sql(expression, "size")
2068        if size and self.TABLESAMPLE_SIZE_IS_ROWS:
2069            size = f"{size} ROWS"
2070
2071        percent = self.sql(expression, "percent")
2072        if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT:
2073            percent = f"{percent} PERCENT"
2074
2075        expr = f"{bucket}{percent}{size}"
2076        if self.TABLESAMPLE_REQUIRES_PARENS:
2077            expr = f"({expr})"
2078
2079        return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}"
def pivot_sql(self, expression: sqlglot.expressions.Pivot) -> str:
2081    def pivot_sql(self, expression: exp.Pivot) -> str:
2082        expressions = self.expressions(expression, flat=True)
2083        direction = "UNPIVOT" if expression.unpivot else "PIVOT"
2084
2085        group = self.sql(expression, "group")
2086
2087        if expression.this:
2088            this = self.sql(expression, "this")
2089            if not expressions:
2090                return f"UNPIVOT {this}"
2091
2092            on = f"{self.seg('ON')} {expressions}"
2093            into = self.sql(expression, "into")
2094            into = f"{self.seg('INTO')} {into}" if into else ""
2095            using = self.expressions(expression, key="using", flat=True)
2096            using = f"{self.seg('USING')} {using}" if using else ""
2097            return f"{direction} {this}{on}{into}{using}{group}"
2098
2099        alias = self.sql(expression, "alias")
2100        alias = f" AS {alias}" if alias else ""
2101
2102        fields = self.expressions(
2103            expression,
2104            "fields",
2105            sep=" ",
2106            dynamic=True,
2107            new_line=True,
2108            skip_first=True,
2109            skip_last=True,
2110        )
2111
2112        include_nulls = expression.args.get("include_nulls")
2113        if include_nulls is not None:
2114            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
2115        else:
2116            nulls = ""
2117
2118        default_on_null = self.sql(expression, "default_on_null")
2119        default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else ""
2120        return f"{self.seg(direction)}{nulls}({expressions} FOR {fields}{default_on_null}{group}){alias}"
def version_sql(self, expression: sqlglot.expressions.Version) -> str:
2122    def version_sql(self, expression: exp.Version) -> str:
2123        this = f"FOR {expression.name}"
2124        kind = expression.text("kind")
2125        expr = self.sql(expression, "expression")
2126        return f"{this} {kind} {expr}"
def tuple_sql(self, expression: sqlglot.expressions.Tuple) -> str:
2128    def tuple_sql(self, expression: exp.Tuple) -> str:
2129        return f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})"
def update_sql(self, expression: sqlglot.expressions.Update) -> str:
2131    def update_sql(self, expression: exp.Update) -> str:
2132        this = self.sql(expression, "this")
2133        set_sql = self.expressions(expression, flat=True)
2134        from_sql = self.sql(expression, "from")
2135        where_sql = self.sql(expression, "where")
2136        returning = self.sql(expression, "returning")
2137        order = self.sql(expression, "order")
2138        limit = self.sql(expression, "limit")
2139        if self.RETURNING_END:
2140            expression_sql = f"{from_sql}{where_sql}{returning}"
2141        else:
2142            expression_sql = f"{returning}{from_sql}{where_sql}"
2143        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
2144        return self.prepend_ctes(expression, sql)
def values_sql( self, expression: sqlglot.expressions.Values, values_as_table: bool = True) -> str:
2146    def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str:
2147        values_as_table = values_as_table and self.VALUES_AS_TABLE
2148
2149        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
2150        if values_as_table or not expression.find_ancestor(exp.From, exp.Join):
2151            args = self.expressions(expression)
2152            alias = self.sql(expression, "alias")
2153            values = f"VALUES{self.seg('')}{args}"
2154            values = (
2155                f"({values})"
2156                if self.WRAP_DERIVED_VALUES
2157                and (alias or isinstance(expression.parent, (exp.From, exp.Table)))
2158                else values
2159            )
2160            return f"{values} AS {alias}" if alias else values
2161
2162        # Converts `VALUES...` expression into a series of select unions.
2163        alias_node = expression.args.get("alias")
2164        column_names = alias_node and alias_node.columns
2165
2166        selects: t.List[exp.Query] = []
2167
2168        for i, tup in enumerate(expression.expressions):
2169            row = tup.expressions
2170
2171            if i == 0 and column_names:
2172                row = [
2173                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
2174                ]
2175
2176            selects.append(exp.Select(expressions=row))
2177
2178        if self.pretty:
2179            # This may result in poor performance for large-cardinality `VALUES` tables, due to
2180            # the deep nesting of the resulting exp.Unions. If this is a problem, either increase
2181            # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`.
2182            query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects)
2183            return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False))
2184
2185        alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else ""
2186        unions = " UNION ALL ".join(self.sql(select) for select in selects)
2187        return f"({unions}){alias}"
def var_sql(self, expression: sqlglot.expressions.Var) -> str:
2189    def var_sql(self, expression: exp.Var) -> str:
2190        return self.sql(expression, "this")
@unsupported_args('expressions')
def into_sql(self, expression: sqlglot.expressions.Into) -> str:
2192    @unsupported_args("expressions")
2193    def into_sql(self, expression: exp.Into) -> str:
2194        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
2195        unlogged = " UNLOGGED" if expression.args.get("unlogged") else ""
2196        return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"
def from_sql(self, expression: sqlglot.expressions.From) -> str:
2198    def from_sql(self, expression: exp.From) -> str:
2199        return f"{self.seg('FROM')} {self.sql(expression, 'this')}"
def groupingsets_sql(self, expression: sqlglot.expressions.GroupingSets) -> str:
2201    def groupingsets_sql(self, expression: exp.GroupingSets) -> str:
2202        grouping_sets = self.expressions(expression, indent=False)
2203        return f"GROUPING SETS {self.wrap(grouping_sets)}"
def rollup_sql(self, expression: sqlglot.expressions.Rollup) -> str:
2205    def rollup_sql(self, expression: exp.Rollup) -> str:
2206        expressions = self.expressions(expression, indent=False)
2207        return f"ROLLUP {self.wrap(expressions)}" if expressions else "WITH ROLLUP"
def cube_sql(self, expression: sqlglot.expressions.Cube) -> str:
2209    def cube_sql(self, expression: exp.Cube) -> str:
2210        expressions = self.expressions(expression, indent=False)
2211        return f"CUBE {self.wrap(expressions)}" if expressions else "WITH CUBE"
def group_sql(self, expression: sqlglot.expressions.Group) -> str:
2213    def group_sql(self, expression: exp.Group) -> str:
2214        group_by_all = expression.args.get("all")
2215        if group_by_all is True:
2216            modifier = " ALL"
2217        elif group_by_all is False:
2218            modifier = " DISTINCT"
2219        else:
2220            modifier = ""
2221
2222        group_by = self.op_expressions(f"GROUP BY{modifier}", expression)
2223
2224        grouping_sets = self.expressions(expression, key="grouping_sets")
2225        cube = self.expressions(expression, key="cube")
2226        rollup = self.expressions(expression, key="rollup")
2227
2228        groupings = csv(
2229            self.seg(grouping_sets) if grouping_sets else "",
2230            self.seg(cube) if cube else "",
2231            self.seg(rollup) if rollup else "",
2232            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
2233            sep=self.GROUPINGS_SEP,
2234        )
2235
2236        if (
2237            expression.expressions
2238            and groupings
2239            and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP")
2240        ):
2241            group_by = f"{group_by}{self.GROUPINGS_SEP}"
2242
2243        return f"{group_by}{groupings}"
def having_sql(self, expression: sqlglot.expressions.Having) -> str:
2245    def having_sql(self, expression: exp.Having) -> str:
2246        this = self.indent(self.sql(expression, "this"))
2247        return f"{self.seg('HAVING')}{self.sep()}{this}"
def connect_sql(self, expression: sqlglot.expressions.Connect) -> str:
2249    def connect_sql(self, expression: exp.Connect) -> str:
2250        start = self.sql(expression, "start")
2251        start = self.seg(f"START WITH {start}") if start else ""
2252        nocycle = " NOCYCLE" if expression.args.get("nocycle") else ""
2253        connect = self.sql(expression, "connect")
2254        connect = self.seg(f"CONNECT BY{nocycle} {connect}")
2255        return start + connect
def prior_sql(self, expression: sqlglot.expressions.Prior) -> str:
2257    def prior_sql(self, expression: exp.Prior) -> str:
2258        return f"PRIOR {self.sql(expression, 'this')}"
def join_sql(self, expression: sqlglot.expressions.Join) -> str:
2260    def join_sql(self, expression: exp.Join) -> str:
2261        if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"):
2262            side = None
2263        else:
2264            side = expression.side
2265
2266        op_sql = " ".join(
2267            op
2268            for op in (
2269                expression.method,
2270                "GLOBAL" if expression.args.get("global") else None,
2271                side,
2272                expression.kind,
2273                expression.hint if self.JOIN_HINTS else None,
2274            )
2275            if op
2276        )
2277        match_cond = self.sql(expression, "match_condition")
2278        match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else ""
2279        on_sql = self.sql(expression, "on")
2280        using = expression.args.get("using")
2281
2282        if not on_sql and using:
2283            on_sql = csv(*(self.sql(column) for column in using))
2284
2285        this = expression.this
2286        this_sql = self.sql(this)
2287
2288        exprs = self.expressions(expression)
2289        if exprs:
2290            this_sql = f"{this_sql},{self.seg(exprs)}"
2291
2292        if on_sql:
2293            on_sql = self.indent(on_sql, skip_first=True)
2294            space = self.seg(" " * self.pad) if self.pretty else " "
2295            if using:
2296                on_sql = f"{space}USING ({on_sql})"
2297            else:
2298                on_sql = f"{space}ON {on_sql}"
2299        elif not op_sql:
2300            if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None:
2301                return f" {this_sql}"
2302
2303            return f", {this_sql}"
2304
2305        if op_sql != "STRAIGHT_JOIN":
2306            op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
2307
2308        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
2309        return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}{pivots}"
def lambda_sql( self, expression: sqlglot.expressions.Lambda, arrow_sep: str = '->') -> str:
2311    def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->") -> str:
2312        args = self.expressions(expression, flat=True)
2313        args = f"({args})" if len(args.split(",")) > 1 else args
2314        return f"{args} {arrow_sep} {self.sql(expression, 'this')}"
def lateral_op(self, expression: sqlglot.expressions.Lateral) -> str:
2316    def lateral_op(self, expression: exp.Lateral) -> str:
2317        cross_apply = expression.args.get("cross_apply")
2318
2319        # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/
2320        if cross_apply is True:
2321            op = "INNER JOIN "
2322        elif cross_apply is False:
2323            op = "LEFT JOIN "
2324        else:
2325            op = ""
2326
2327        return f"{op}LATERAL"
def lateral_sql(self, expression: sqlglot.expressions.Lateral) -> str:
2329    def lateral_sql(self, expression: exp.Lateral) -> str:
2330        this = self.sql(expression, "this")
2331
2332        if expression.args.get("view"):
2333            alias = expression.args["alias"]
2334            columns = self.expressions(alias, key="columns", flat=True)
2335            table = f" {alias.name}" if alias.name else ""
2336            columns = f" AS {columns}" if columns else ""
2337            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
2338            return f"{op_sql}{self.sep()}{this}{table}{columns}"
2339
2340        alias = self.sql(expression, "alias")
2341        alias = f" AS {alias}" if alias else ""
2342
2343        ordinality = expression.args.get("ordinality") or ""
2344        if ordinality:
2345            ordinality = f" WITH ORDINALITY{alias}"
2346            alias = ""
2347
2348        return f"{self.lateral_op(expression)} {this}{alias}{ordinality}"
def limit_sql(self, expression: sqlglot.expressions.Limit, top: bool = False) -> str:
2350    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
2351        this = self.sql(expression, "this")
2352
2353        args = [
2354            self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e
2355            for e in (expression.args.get(k) for k in ("offset", "expression"))
2356            if e
2357        ]
2358
2359        args_sql = ", ".join(self.sql(e) for e in args)
2360        args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql
2361        expressions = self.expressions(expression, flat=True)
2362        limit_options = self.sql(expression, "limit_options")
2363        expressions = f" BY {expressions}" if expressions else ""
2364
2365        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{limit_options}{expressions}"
def offset_sql(self, expression: sqlglot.expressions.Offset) -> str:
2367    def offset_sql(self, expression: exp.Offset) -> str:
2368        this = self.sql(expression, "this")
2369        value = expression.expression
2370        value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value
2371        expressions = self.expressions(expression, flat=True)
2372        expressions = f" BY {expressions}" if expressions else ""
2373        return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"
def setitem_sql(self, expression: sqlglot.expressions.SetItem) -> str:
2375    def setitem_sql(self, expression: exp.SetItem) -> str:
2376        kind = self.sql(expression, "kind")
2377        kind = f"{kind} " if kind else ""
2378        this = self.sql(expression, "this")
2379        expressions = self.expressions(expression)
2380        collate = self.sql(expression, "collate")
2381        collate = f" COLLATE {collate}" if collate else ""
2382        global_ = "GLOBAL " if expression.args.get("global") else ""
2383        return f"{global_}{kind}{this}{expressions}{collate}"
def set_sql(self, expression: sqlglot.expressions.Set) -> str:
2385    def set_sql(self, expression: exp.Set) -> str:
2386        expressions = f" {self.expressions(expression, flat=True)}"
2387        tag = " TAG" if expression.args.get("tag") else ""
2388        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"
def pragma_sql(self, expression: sqlglot.expressions.Pragma) -> str:
2390    def pragma_sql(self, expression: exp.Pragma) -> str:
2391        return f"PRAGMA {self.sql(expression, 'this')}"
def lock_sql(self, expression: sqlglot.expressions.Lock) -> str:
2393    def lock_sql(self, expression: exp.Lock) -> str:
2394        if not self.LOCKING_READS_SUPPORTED:
2395            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
2396            return ""
2397
2398        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
2399        expressions = self.expressions(expression, flat=True)
2400        expressions = f" OF {expressions}" if expressions else ""
2401        wait = expression.args.get("wait")
2402
2403        if wait is not None:
2404            if isinstance(wait, exp.Literal):
2405                wait = f" WAIT {self.sql(wait)}"
2406            else:
2407                wait = " NOWAIT" if wait else " SKIP LOCKED"
2408
2409        return f"{lock_type}{expressions}{wait or ''}"
def literal_sql(self, expression: sqlglot.expressions.Literal) -> str:
2411    def literal_sql(self, expression: exp.Literal) -> str:
2412        text = expression.this or ""
2413        if expression.is_string:
2414            text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}"
2415        return text
def escape_str(self, text: str, escape_backslash: bool = True) -> str:
2417    def escape_str(self, text: str, escape_backslash: bool = True) -> str:
2418        if self.dialect.ESCAPED_SEQUENCES:
2419            to_escaped = self.dialect.ESCAPED_SEQUENCES
2420            text = "".join(
2421                to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text
2422            )
2423
2424        return self._replace_line_breaks(text).replace(
2425            self.dialect.QUOTE_END, self._escaped_quote_end
2426        )
def loaddata_sql(self, expression: sqlglot.expressions.LoadData) -> str:
2428    def loaddata_sql(self, expression: exp.LoadData) -> str:
2429        local = " LOCAL" if expression.args.get("local") else ""
2430        inpath = f" INPATH {self.sql(expression, 'inpath')}"
2431        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
2432        this = f" INTO TABLE {self.sql(expression, 'this')}"
2433        partition = self.sql(expression, "partition")
2434        partition = f" {partition}" if partition else ""
2435        input_format = self.sql(expression, "input_format")
2436        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
2437        serde = self.sql(expression, "serde")
2438        serde = f" SERDE {serde}" if serde else ""
2439        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"
def null_sql(self, *_) -> str:
2441    def null_sql(self, *_) -> str:
2442        return "NULL"
def boolean_sql(self, expression: sqlglot.expressions.Boolean) -> str:
2444    def boolean_sql(self, expression: exp.Boolean) -> str:
2445        return "TRUE" if expression.this else "FALSE"
def order_sql(self, expression: sqlglot.expressions.Order, flat: bool = False) -> str:
2447    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
2448        this = self.sql(expression, "this")
2449        this = f"{this} " if this else this
2450        siblings = "SIBLINGS " if expression.args.get("siblings") else ""
2451        return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat)  # type: ignore
def withfill_sql(self, expression: sqlglot.expressions.WithFill) -> str:
2453    def withfill_sql(self, expression: exp.WithFill) -> str:
2454        from_sql = self.sql(expression, "from")
2455        from_sql = f" FROM {from_sql}" if from_sql else ""
2456        to_sql = self.sql(expression, "to")
2457        to_sql = f" TO {to_sql}" if to_sql else ""
2458        step_sql = self.sql(expression, "step")
2459        step_sql = f" STEP {step_sql}" if step_sql else ""
2460        interpolated_values = [
2461            f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}"
2462            if isinstance(e, exp.Alias)
2463            else self.sql(e, "this")
2464            for e in expression.args.get("interpolate") or []
2465        ]
2466        interpolate = (
2467            f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else ""
2468        )
2469        return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}"
def cluster_sql(self, expression: sqlglot.expressions.Cluster) -> str:
2471    def cluster_sql(self, expression: exp.Cluster) -> str:
2472        return self.op_expressions("CLUSTER BY", expression)
def distribute_sql(self, expression: sqlglot.expressions.Distribute) -> str:
2474    def distribute_sql(self, expression: exp.Distribute) -> str:
2475        return self.op_expressions("DISTRIBUTE BY", expression)
def sort_sql(self, expression: sqlglot.expressions.Sort) -> str:
2477    def sort_sql(self, expression: exp.Sort) -> str:
2478        return self.op_expressions("SORT BY", expression)
def ordered_sql(self, expression: sqlglot.expressions.Ordered) -> str:
2480    def ordered_sql(self, expression: exp.Ordered) -> str:
2481        desc = expression.args.get("desc")
2482        asc = not desc
2483
2484        nulls_first = expression.args.get("nulls_first")
2485        nulls_last = not nulls_first
2486        nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large"
2487        nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small"
2488        nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last"
2489
2490        this = self.sql(expression, "this")
2491
2492        sort_order = " DESC" if desc else (" ASC" if desc is False else "")
2493        nulls_sort_change = ""
2494        if nulls_first and (
2495            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
2496        ):
2497            nulls_sort_change = " NULLS FIRST"
2498        elif (
2499            nulls_last
2500            and ((asc and nulls_are_small) or (desc and nulls_are_large))
2501            and not nulls_are_last
2502        ):
2503            nulls_sort_change = " NULLS LAST"
2504
2505        # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it
2506        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
2507            window = expression.find_ancestor(exp.Window, exp.Select)
2508            if isinstance(window, exp.Window) and window.args.get("spec"):
2509                self.unsupported(
2510                    f"'{nulls_sort_change.strip()}' translation not supported in window functions"
2511                )
2512                nulls_sort_change = ""
2513            elif self.NULL_ORDERING_SUPPORTED is False and (
2514                (asc and nulls_sort_change == " NULLS LAST")
2515                or (desc and nulls_sort_change == " NULLS FIRST")
2516            ):
2517                # BigQuery does not allow these ordering/nulls combinations when used under
2518                # an aggregation func or under a window containing one
2519                ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select)
2520
2521                if isinstance(ancestor, exp.Window):
2522                    ancestor = ancestor.this
2523                if isinstance(ancestor, exp.AggFunc):
2524                    self.unsupported(
2525                        f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order"
2526                    )
2527                    nulls_sort_change = ""
2528            elif self.NULL_ORDERING_SUPPORTED is None:
2529                if expression.this.is_int:
2530                    self.unsupported(
2531                        f"'{nulls_sort_change.strip()}' translation not supported with positional ordering"
2532                    )
2533                elif not isinstance(expression.this, exp.Rand):
2534                    null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else ""
2535                    this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}"
2536                nulls_sort_change = ""
2537
2538        with_fill = self.sql(expression, "with_fill")
2539        with_fill = f" {with_fill}" if with_fill else ""
2540
2541        return f"{this}{sort_order}{nulls_sort_change}{with_fill}"
def matchrecognizemeasure_sql(self, expression: sqlglot.expressions.MatchRecognizeMeasure) -> str:
2543    def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str:
2544        window_frame = self.sql(expression, "window_frame")
2545        window_frame = f"{window_frame} " if window_frame else ""
2546
2547        this = self.sql(expression, "this")
2548
2549        return f"{window_frame}{this}"
def matchrecognize_sql(self, expression: sqlglot.expressions.MatchRecognize) -> str:
2551    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
2552        partition = self.partition_by_sql(expression)
2553        order = self.sql(expression, "order")
2554        measures = self.expressions(expression, key="measures")
2555        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
2556        rows = self.sql(expression, "rows")
2557        rows = self.seg(rows) if rows else ""
2558        after = self.sql(expression, "after")
2559        after = self.seg(after) if after else ""
2560        pattern = self.sql(expression, "pattern")
2561        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
2562        definition_sqls = [
2563            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
2564            for definition in expression.args.get("define", [])
2565        ]
2566        definitions = self.expressions(sqls=definition_sqls)
2567        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
2568        body = "".join(
2569            (
2570                partition,
2571                order,
2572                measures,
2573                rows,
2574                after,
2575                pattern,
2576                define,
2577            )
2578        )
2579        alias = self.sql(expression, "alias")
2580        alias = f" {alias}" if alias else ""
2581        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"
def query_modifiers(self, expression: sqlglot.expressions.Expression, *sqls: str) -> str:
2583    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
2584        limit = expression.args.get("limit")
2585
2586        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
2587            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
2588        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
2589            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
2590
2591        return csv(
2592            *sqls,
2593            *[self.sql(join) for join in expression.args.get("joins") or []],
2594            self.sql(expression, "match"),
2595            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
2596            self.sql(expression, "prewhere"),
2597            self.sql(expression, "where"),
2598            self.sql(expression, "connect"),
2599            self.sql(expression, "group"),
2600            self.sql(expression, "having"),
2601            *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()],
2602            self.sql(expression, "order"),
2603            *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit),
2604            *self.after_limit_modifiers(expression),
2605            self.options_modifier(expression),
2606            self.for_modifiers(expression),
2607            sep="",
2608        )
def options_modifier(self, expression: sqlglot.expressions.Expression) -> str:
2610    def options_modifier(self, expression: exp.Expression) -> str:
2611        options = self.expressions(expression, key="options")
2612        return f" {options}" if options else ""
def for_modifiers(self, expression: sqlglot.expressions.Expression) -> str:
2614    def for_modifiers(self, expression: exp.Expression) -> str:
2615        for_modifiers = self.expressions(expression, key="for")
2616        return f"{self.sep()}FOR XML{self.seg(for_modifiers)}" if for_modifiers else ""
def queryoption_sql(self, expression: sqlglot.expressions.QueryOption) -> str:
2618    def queryoption_sql(self, expression: exp.QueryOption) -> str:
2619        self.unsupported("Unsupported query option.")
2620        return ""
def offset_limit_modifiers( self, expression: sqlglot.expressions.Expression, fetch: bool, limit: Union[sqlglot.expressions.Fetch, sqlglot.expressions.Limit, NoneType]) -> List[str]:
2622    def offset_limit_modifiers(
2623        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
2624    ) -> t.List[str]:
2625        return [
2626            self.sql(expression, "offset") if fetch else self.sql(limit),
2627            self.sql(limit) if fetch else self.sql(expression, "offset"),
2628        ]
def after_limit_modifiers(self, expression: sqlglot.expressions.Expression) -> List[str]:
2630    def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]:
2631        locks = self.expressions(expression, key="locks", sep=" ")
2632        locks = f" {locks}" if locks else ""
2633        return [locks, self.sql(expression, "sample")]
def select_sql(self, expression: sqlglot.expressions.Select) -> str:
2635    def select_sql(self, expression: exp.Select) -> str:
2636        into = expression.args.get("into")
2637        if not self.SUPPORTS_SELECT_INTO and into:
2638            into.pop()
2639
2640        hint = self.sql(expression, "hint")
2641        distinct = self.sql(expression, "distinct")
2642        distinct = f" {distinct}" if distinct else ""
2643        kind = self.sql(expression, "kind")
2644
2645        limit = expression.args.get("limit")
2646        if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP:
2647            top = self.limit_sql(limit, top=True)
2648            limit.pop()
2649        else:
2650            top = ""
2651
2652        expressions = self.expressions(expression)
2653
2654        if kind:
2655            if kind in self.SELECT_KINDS:
2656                kind = f" AS {kind}"
2657            else:
2658                if kind == "STRUCT":
2659                    expressions = self.expressions(
2660                        sqls=[
2661                            self.sql(
2662                                exp.Struct(
2663                                    expressions=[
2664                                        exp.PropertyEQ(this=e.args.get("alias"), expression=e.this)
2665                                        if isinstance(e, exp.Alias)
2666                                        else e
2667                                        for e in expression.expressions
2668                                    ]
2669                                )
2670                            )
2671                        ]
2672                    )
2673                kind = ""
2674
2675        operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ")
2676        operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else ""
2677
2678        # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata
2679        # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first.
2680        top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}"
2681        expressions = f"{self.sep()}{expressions}" if expressions else expressions
2682        sql = self.query_modifiers(
2683            expression,
2684            f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}",
2685            self.sql(expression, "into", comment=False),
2686            self.sql(expression, "from", comment=False),
2687        )
2688
2689        # If both the CTE and SELECT clauses have comments, generate the latter earlier
2690        if expression.args.get("with"):
2691            sql = self.maybe_comment(sql, expression)
2692            expression.pop_comments()
2693
2694        sql = self.prepend_ctes(expression, sql)
2695
2696        if not self.SUPPORTS_SELECT_INTO and into:
2697            if into.args.get("temporary"):
2698                table_kind = " TEMPORARY"
2699            elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"):
2700                table_kind = " UNLOGGED"
2701            else:
2702                table_kind = ""
2703            sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}"
2704
2705        return sql
def schema_sql(self, expression: sqlglot.expressions.Schema) -> str:
2707    def schema_sql(self, expression: exp.Schema) -> str:
2708        this = self.sql(expression, "this")
2709        sql = self.schema_columns_sql(expression)
2710        return f"{this} {sql}" if this and sql else this or sql
def schema_columns_sql(self, expression: sqlglot.expressions.Schema) -> str:
2712    def schema_columns_sql(self, expression: exp.Schema) -> str:
2713        if expression.expressions:
2714            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
2715        return ""
def star_sql(self, expression: sqlglot.expressions.Star) -> str:
2717    def star_sql(self, expression: exp.Star) -> str:
2718        except_ = self.expressions(expression, key="except", flat=True)
2719        except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else ""
2720        replace = self.expressions(expression, key="replace", flat=True)
2721        replace = f"{self.seg('REPLACE')} ({replace})" if replace else ""
2722        rename = self.expressions(expression, key="rename", flat=True)
2723        rename = f"{self.seg('RENAME')} ({rename})" if rename else ""
2724        return f"*{except_}{replace}{rename}"
def parameter_sql(self, expression: sqlglot.expressions.Parameter) -> str:
2726    def parameter_sql(self, expression: exp.Parameter) -> str:
2727        this = self.sql(expression, "this")
2728        return f"{self.PARAMETER_TOKEN}{this}"
def sessionparameter_sql(self, expression: sqlglot.expressions.SessionParameter) -> str:
2730    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
2731        this = self.sql(expression, "this")
2732        kind = expression.text("kind")
2733        if kind:
2734            kind = f"{kind}."
2735        return f"@@{kind}{this}"
def placeholder_sql(self, expression: sqlglot.expressions.Placeholder) -> str:
2737    def placeholder_sql(self, expression: exp.Placeholder) -> str:
2738        return f"{self.NAMED_PLACEHOLDER_TOKEN}{expression.name}" if expression.this else "?"
def subquery_sql(self, expression: sqlglot.expressions.Subquery, sep: str = ' AS ') -> str:
2740    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
2741        alias = self.sql(expression, "alias")
2742        alias = f"{sep}{alias}" if alias else ""
2743        sample = self.sql(expression, "sample")
2744        if self.dialect.ALIAS_POST_TABLESAMPLE and sample:
2745            alias = f"{sample}{alias}"
2746
2747            # Set to None so it's not generated again by self.query_modifiers()
2748            expression.set("sample", None)
2749
2750        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
2751        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
2752        return self.prepend_ctes(expression, sql)
def qualify_sql(self, expression: sqlglot.expressions.Qualify) -> str:
2754    def qualify_sql(self, expression: exp.Qualify) -> str:
2755        this = self.indent(self.sql(expression, "this"))
2756        return f"{self.seg('QUALIFY')}{self.sep()}{this}"
def unnest_sql(self, expression: sqlglot.expressions.Unnest) -> str:
2758    def unnest_sql(self, expression: exp.Unnest) -> str:
2759        args = self.expressions(expression, flat=True)
2760
2761        alias = expression.args.get("alias")
2762        offset = expression.args.get("offset")
2763
2764        if self.UNNEST_WITH_ORDINALITY:
2765            if alias and isinstance(offset, exp.Expression):
2766                alias.append("columns", offset)
2767
2768        if alias and self.dialect.UNNEST_COLUMN_ONLY:
2769            columns = alias.columns
2770            alias = self.sql(columns[0]) if columns else ""
2771        else:
2772            alias = self.sql(alias)
2773
2774        alias = f" AS {alias}" if alias else alias
2775        if self.UNNEST_WITH_ORDINALITY:
2776            suffix = f" WITH ORDINALITY{alias}" if offset else alias
2777        else:
2778            if isinstance(offset, exp.Expression):
2779                suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}"
2780            elif offset:
2781                suffix = f"{alias} WITH OFFSET"
2782            else:
2783                suffix = alias
2784
2785        return f"UNNEST({args}){suffix}"
def prewhere_sql(self, expression: sqlglot.expressions.PreWhere) -> str:
2787    def prewhere_sql(self, expression: exp.PreWhere) -> str:
2788        return ""
def where_sql(self, expression: sqlglot.expressions.Where) -> str:
2790    def where_sql(self, expression: exp.Where) -> str:
2791        this = self.indent(self.sql(expression, "this"))
2792        return f"{self.seg('WHERE')}{self.sep()}{this}"
def window_sql(self, expression: sqlglot.expressions.Window) -> str:
2794    def window_sql(self, expression: exp.Window) -> str:
2795        this = self.sql(expression, "this")
2796        partition = self.partition_by_sql(expression)
2797        order = expression.args.get("order")
2798        order = self.order_sql(order, flat=True) if order else ""
2799        spec = self.sql(expression, "spec")
2800        alias = self.sql(expression, "alias")
2801        over = self.sql(expression, "over") or "OVER"
2802
2803        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
2804
2805        first = expression.args.get("first")
2806        if first is None:
2807            first = ""
2808        else:
2809            first = "FIRST" if first else "LAST"
2810
2811        if not partition and not order and not spec and alias:
2812            return f"{this} {alias}"
2813
2814        args = self.format_args(
2815            *[arg for arg in (alias, first, partition, order, spec) if arg], sep=" "
2816        )
2817        return f"{this} ({args})"
def partition_by_sql( self, expression: sqlglot.expressions.Window | sqlglot.expressions.MatchRecognize) -> str:
2819    def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str:
2820        partition = self.expressions(expression, key="partition_by", flat=True)
2821        return f"PARTITION BY {partition}" if partition else ""
def windowspec_sql(self, expression: sqlglot.expressions.WindowSpec) -> str:
2823    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
2824        kind = self.sql(expression, "kind")
2825        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
2826        end = (
2827            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
2828            or "CURRENT ROW"
2829        )
2830
2831        window_spec = f"{kind} BETWEEN {start} AND {end}"
2832
2833        exclude = self.sql(expression, "exclude")
2834        if exclude:
2835            if self.SUPPORTS_WINDOW_EXCLUDE:
2836                window_spec += f" EXCLUDE {exclude}"
2837            else:
2838                self.unsupported("EXCLUDE clause is not supported in the WINDOW clause")
2839
2840        return window_spec
def withingroup_sql(self, expression: sqlglot.expressions.WithinGroup) -> str:
2842    def withingroup_sql(self, expression: exp.WithinGroup) -> str:
2843        this = self.sql(expression, "this")
2844        expression_sql = self.sql(expression, "expression")[1:]  # order has a leading space
2845        return f"{this} WITHIN GROUP ({expression_sql})"
def between_sql(self, expression: sqlglot.expressions.Between) -> str:
2847    def between_sql(self, expression: exp.Between) -> str:
2848        this = self.sql(expression, "this")
2849        low = self.sql(expression, "low")
2850        high = self.sql(expression, "high")
2851        return f"{this} BETWEEN {low} AND {high}"
def bracket_offset_expressions( self, expression: sqlglot.expressions.Bracket, index_offset: Optional[int] = None) -> List[sqlglot.expressions.Expression]:
2853    def bracket_offset_expressions(
2854        self, expression: exp.Bracket, index_offset: t.Optional[int] = None
2855    ) -> t.List[exp.Expression]:
2856        return apply_index_offset(
2857            expression.this,
2858            expression.expressions,
2859            (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0),
2860            dialect=self.dialect,
2861        )
def bracket_sql(self, expression: sqlglot.expressions.Bracket) -> str:
2863    def bracket_sql(self, expression: exp.Bracket) -> str:
2864        expressions = self.bracket_offset_expressions(expression)
2865        expressions_sql = ", ".join(self.sql(e) for e in expressions)
2866        return f"{self.sql(expression, 'this')}[{expressions_sql}]"
def all_sql(self, expression: sqlglot.expressions.All) -> str:
2868    def all_sql(self, expression: exp.All) -> str:
2869        return f"ALL {self.wrap(expression)}"
def any_sql(self, expression: sqlglot.expressions.Any) -> str:
2871    def any_sql(self, expression: exp.Any) -> str:
2872        this = self.sql(expression, "this")
2873        if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)):
2874            if isinstance(expression.this, exp.UNWRAPPED_QUERIES):
2875                this = self.wrap(this)
2876            return f"ANY{this}"
2877        return f"ANY {this}"
def exists_sql(self, expression: sqlglot.expressions.Exists) -> str:
2879    def exists_sql(self, expression: exp.Exists) -> str:
2880        return f"EXISTS{self.wrap(expression)}"
def case_sql(self, expression: sqlglot.expressions.Case) -> str:
2882    def case_sql(self, expression: exp.Case) -> str:
2883        this = self.sql(expression, "this")
2884        statements = [f"CASE {this}" if this else "CASE"]
2885
2886        for e in expression.args["ifs"]:
2887            statements.append(f"WHEN {self.sql(e, 'this')}")
2888            statements.append(f"THEN {self.sql(e, 'true')}")
2889
2890        default = self.sql(expression, "default")
2891
2892        if default:
2893            statements.append(f"ELSE {default}")
2894
2895        statements.append("END")
2896
2897        if self.pretty and self.too_wide(statements):
2898            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
2899
2900        return " ".join(statements)
def constraint_sql(self, expression: sqlglot.expressions.Constraint) -> str:
2902    def constraint_sql(self, expression: exp.Constraint) -> str:
2903        this = self.sql(expression, "this")
2904        expressions = self.expressions(expression, flat=True)
2905        return f"CONSTRAINT {this} {expressions}"
def nextvaluefor_sql(self, expression: sqlglot.expressions.NextValueFor) -> str:
2907    def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str:
2908        order = expression.args.get("order")
2909        order = f" OVER ({self.order_sql(order, flat=True)})" if order else ""
2910        return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}"
def extract_sql(self, expression: sqlglot.expressions.Extract) -> str:
2912    def extract_sql(self, expression: exp.Extract) -> str:
2913        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
2914        expression_sql = self.sql(expression, "expression")
2915        return f"EXTRACT({this} FROM {expression_sql})"
def trim_sql(self, expression: sqlglot.expressions.Trim) -> str:
2917    def trim_sql(self, expression: exp.Trim) -> str:
2918        trim_type = self.sql(expression, "position")
2919
2920        if trim_type == "LEADING":
2921            func_name = "LTRIM"
2922        elif trim_type == "TRAILING":
2923            func_name = "RTRIM"
2924        else:
2925            func_name = "TRIM"
2926
2927        return self.func(func_name, expression.this, expression.expression)
def convert_concat_args( self, expression: sqlglot.expressions.Concat | sqlglot.expressions.ConcatWs) -> List[sqlglot.expressions.Expression]:
2929    def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]:
2930        args = expression.expressions
2931        if isinstance(expression, exp.ConcatWs):
2932            args = args[1:]  # Skip the delimiter
2933
2934        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
2935            args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args]
2936
2937        if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"):
2938            args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args]
2939
2940        return args
def concat_sql(self, expression: sqlglot.expressions.Concat) -> str:
2942    def concat_sql(self, expression: exp.Concat) -> str:
2943        expressions = self.convert_concat_args(expression)
2944
2945        # Some dialects don't allow a single-argument CONCAT call
2946        if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1:
2947            return self.sql(expressions[0])
2948
2949        return self.func("CONCAT", *expressions)
def concatws_sql(self, expression: sqlglot.expressions.ConcatWs) -> str:
2951    def concatws_sql(self, expression: exp.ConcatWs) -> str:
2952        return self.func(
2953            "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression)
2954        )
def check_sql(self, expression: sqlglot.expressions.Check) -> str:
2956    def check_sql(self, expression: exp.Check) -> str:
2957        this = self.sql(expression, key="this")
2958        return f"CHECK ({this})"
def foreignkey_sql(self, expression: sqlglot.expressions.ForeignKey) -> str:
2960    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
2961        expressions = self.expressions(expression, flat=True)
2962        expressions = f" ({expressions})" if expressions else ""
2963        reference = self.sql(expression, "reference")
2964        reference = f" {reference}" if reference else ""
2965        delete = self.sql(expression, "delete")
2966        delete = f" ON DELETE {delete}" if delete else ""
2967        update = self.sql(expression, "update")
2968        update = f" ON UPDATE {update}" if update else ""
2969        options = self.expressions(expression, key="options", flat=True, sep=" ")
2970        options = f" {options}" if options else ""
2971        return f"FOREIGN KEY{expressions}{reference}{delete}{update}{options}"
def primarykey_sql(self, expression: sqlglot.expressions.ForeignKey) -> str:
2973    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
2974        expressions = self.expressions(expression, flat=True)
2975        options = self.expressions(expression, key="options", flat=True, sep=" ")
2976        options = f" {options}" if options else ""
2977        return f"PRIMARY KEY ({expressions}){options}"
def if_sql(self, expression: sqlglot.expressions.If) -> str:
2979    def if_sql(self, expression: exp.If) -> str:
2980        return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false")))
def matchagainst_sql(self, expression: sqlglot.expressions.MatchAgainst) -> str:
2982    def matchagainst_sql(self, expression: exp.MatchAgainst) -> str:
2983        modifier = expression.args.get("modifier")
2984        modifier = f" {modifier}" if modifier else ""
2985        return f"{self.func('MATCH', *expression.expressions)} AGAINST({self.sql(expression, 'this')}{modifier})"
def jsonkeyvalue_sql(self, expression: sqlglot.expressions.JSONKeyValue) -> str:
2987    def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str:
2988        return f"{self.sql(expression, 'this')}{self.JSON_KEY_VALUE_PAIR_SEP} {self.sql(expression, 'expression')}"
def jsonpath_sql(self, expression: sqlglot.expressions.JSONPath) -> str:
2990    def jsonpath_sql(self, expression: exp.JSONPath) -> str:
2991        path = self.expressions(expression, sep="", flat=True).lstrip(".")
2992
2993        if expression.args.get("escape"):
2994            path = self.escape_str(path)
2995
2996        if self.QUOTE_JSON_PATH:
2997            path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"
2998
2999        return path
def json_path_part(self, expression: int | str | sqlglot.expressions.JSONPathPart) -> str:
3001    def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str:
3002        if isinstance(expression, exp.JSONPathPart):
3003            transform = self.TRANSFORMS.get(expression.__class__)
3004            if not callable(transform):
3005                self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}")
3006                return ""
3007
3008            return transform(self, expression)
3009
3010        if isinstance(expression, int):
3011            return str(expression)
3012
3013        if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE:
3014            escaped = expression.replace("'", "\\'")
3015            escaped = f"\\'{expression}\\'"
3016        else:
3017            escaped = expression.replace('"', '\\"')
3018            escaped = f'"{escaped}"'
3019
3020        return escaped
def formatjson_sql(self, expression: sqlglot.expressions.FormatJson) -> str:
3022    def formatjson_sql(self, expression: exp.FormatJson) -> str:
3023        return f"{self.sql(expression, 'this')} FORMAT JSON"
def jsonobject_sql( self, expression: sqlglot.expressions.JSONObject | sqlglot.expressions.JSONObjectAgg) -> str:
3025    def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str:
3026        null_handling = expression.args.get("null_handling")
3027        null_handling = f" {null_handling}" if null_handling else ""
3028
3029        unique_keys = expression.args.get("unique_keys")
3030        if unique_keys is not None:
3031            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
3032        else:
3033            unique_keys = ""
3034
3035        return_type = self.sql(expression, "return_type")
3036        return_type = f" RETURNING {return_type}" if return_type else ""
3037        encoding = self.sql(expression, "encoding")
3038        encoding = f" ENCODING {encoding}" if encoding else ""
3039
3040        return self.func(
3041            "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG",
3042            *expression.expressions,
3043            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
3044        )
def jsonobjectagg_sql(self, expression: sqlglot.expressions.JSONObjectAgg) -> str:
3046    def jsonobjectagg_sql(self, expression: exp.JSONObjectAgg) -> str:
3047        return self.jsonobject_sql(expression)
def jsonarray_sql(self, expression: sqlglot.expressions.JSONArray) -> str:
3049    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
3050        null_handling = expression.args.get("null_handling")
3051        null_handling = f" {null_handling}" if null_handling else ""
3052        return_type = self.sql(expression, "return_type")
3053        return_type = f" RETURNING {return_type}" if return_type else ""
3054        strict = " STRICT" if expression.args.get("strict") else ""
3055        return self.func(
3056            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
3057        )
def jsonarrayagg_sql(self, expression: sqlglot.expressions.JSONArrayAgg) -> str:
3059    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
3060        this = self.sql(expression, "this")
3061        order = self.sql(expression, "order")
3062        null_handling = expression.args.get("null_handling")
3063        null_handling = f" {null_handling}" if null_handling else ""
3064        return_type = self.sql(expression, "return_type")
3065        return_type = f" RETURNING {return_type}" if return_type else ""
3066        strict = " STRICT" if expression.args.get("strict") else ""
3067        return self.func(
3068            "JSON_ARRAYAGG",
3069            this,
3070            suffix=f"{order}{null_handling}{return_type}{strict})",
3071        )
def jsoncolumndef_sql(self, expression: sqlglot.expressions.JSONColumnDef) -> str:
3073    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
3074        path = self.sql(expression, "path")
3075        path = f" PATH {path}" if path else ""
3076        nested_schema = self.sql(expression, "nested_schema")
3077
3078        if nested_schema:
3079            return f"NESTED{path} {nested_schema}"
3080
3081        this = self.sql(expression, "this")
3082        kind = self.sql(expression, "kind")
3083        kind = f" {kind}" if kind else ""
3084        return f"{this}{kind}{path}"
def jsonschema_sql(self, expression: sqlglot.expressions.JSONSchema) -> str:
3086    def jsonschema_sql(self, expression: exp.JSONSchema) -> str:
3087        return self.func("COLUMNS", *expression.expressions)
def jsontable_sql(self, expression: sqlglot.expressions.JSONTable) -> str:
3089    def jsontable_sql(self, expression: exp.JSONTable) -> str:
3090        this = self.sql(expression, "this")
3091        path = self.sql(expression, "path")
3092        path = f", {path}" if path else ""
3093        error_handling = expression.args.get("error_handling")
3094        error_handling = f" {error_handling}" if error_handling else ""
3095        empty_handling = expression.args.get("empty_handling")
3096        empty_handling = f" {empty_handling}" if empty_handling else ""
3097        schema = self.sql(expression, "schema")
3098        return self.func(
3099            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
3100        )
def openjsoncolumndef_sql(self, expression: sqlglot.expressions.OpenJSONColumnDef) -> str:
3102    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
3103        this = self.sql(expression, "this")
3104        kind = self.sql(expression, "kind")
3105        path = self.sql(expression, "path")
3106        path = f" {path}" if path else ""
3107        as_json = " AS JSON" if expression.args.get("as_json") else ""
3108        return f"{this} {kind}{path}{as_json}"
def openjson_sql(self, expression: sqlglot.expressions.OpenJSON) -> str:
3110    def openjson_sql(self, expression: exp.OpenJSON) -> str:
3111        this = self.sql(expression, "this")
3112        path = self.sql(expression, "path")
3113        path = f", {path}" if path else ""
3114        expressions = self.expressions(expression)
3115        with_ = (
3116            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
3117            if expressions
3118            else ""
3119        )
3120        return f"OPENJSON({this}{path}){with_}"
def in_sql(self, expression: sqlglot.expressions.In) -> str:
3122    def in_sql(self, expression: exp.In) -> str:
3123        query = expression.args.get("query")
3124        unnest = expression.args.get("unnest")
3125        field = expression.args.get("field")
3126        is_global = " GLOBAL" if expression.args.get("is_global") else ""
3127
3128        if query:
3129            in_sql = self.sql(query)
3130        elif unnest:
3131            in_sql = self.in_unnest_op(unnest)
3132        elif field:
3133            in_sql = self.sql(field)
3134        else:
3135            in_sql = f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})"
3136
3137        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"
def in_unnest_op(self, unnest: sqlglot.expressions.Unnest) -> str:
3139    def in_unnest_op(self, unnest: exp.Unnest) -> str:
3140        return f"(SELECT {self.sql(unnest)})"
def interval_sql(self, expression: sqlglot.expressions.Interval) -> str:
3142    def interval_sql(self, expression: exp.Interval) -> str:
3143        unit = self.sql(expression, "unit")
3144        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
3145            unit = self.TIME_PART_SINGULARS.get(unit, unit)
3146        unit = f" {unit}" if unit else ""
3147
3148        if self.SINGLE_STRING_INTERVAL:
3149            this = expression.this.name if expression.this else ""
3150            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
3151
3152        this = self.sql(expression, "this")
3153        if this:
3154            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
3155            this = f" {this}" if unwrapped else f" ({this})"
3156
3157        return f"INTERVAL{this}{unit}"
def return_sql(self, expression: sqlglot.expressions.Return) -> str:
3159    def return_sql(self, expression: exp.Return) -> str:
3160        return f"RETURN {self.sql(expression, 'this')}"
def reference_sql(self, expression: sqlglot.expressions.Reference) -> str:
3162    def reference_sql(self, expression: exp.Reference) -> str:
3163        this = self.sql(expression, "this")
3164        expressions = self.expressions(expression, flat=True)
3165        expressions = f"({expressions})" if expressions else ""
3166        options = self.expressions(expression, key="options", flat=True, sep=" ")
3167        options = f" {options}" if options else ""
3168        return f"REFERENCES {this}{expressions}{options}"
def anonymous_sql(self, expression: sqlglot.expressions.Anonymous) -> str:
3170    def anonymous_sql(self, expression: exp.Anonymous) -> str:
3171        # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive
3172        parent = expression.parent
3173        is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression
3174        return self.func(
3175            self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified
3176        )
def paren_sql(self, expression: sqlglot.expressions.Paren) -> str:
3178    def paren_sql(self, expression: exp.Paren) -> str:
3179        sql = self.seg(self.indent(self.sql(expression, "this")), sep="")
3180        return f"({sql}{self.seg(')', sep='')}"
def neg_sql(self, expression: sqlglot.expressions.Neg) -> str:
3182    def neg_sql(self, expression: exp.Neg) -> str:
3183        # This makes sure we don't convert "- - 5" to "--5", which is a comment
3184        this_sql = self.sql(expression, "this")
3185        sep = " " if this_sql[0] == "-" else ""
3186        return f"-{sep}{this_sql}"
def not_sql(self, expression: sqlglot.expressions.Not) -> str:
3188    def not_sql(self, expression: exp.Not) -> str:
3189        return f"NOT {self.sql(expression, 'this')}"
def alias_sql(self, expression: sqlglot.expressions.Alias) -> str:
3191    def alias_sql(self, expression: exp.Alias) -> str:
3192        alias = self.sql(expression, "alias")
3193        alias = f" AS {alias}" if alias else ""
3194        return f"{self.sql(expression, 'this')}{alias}"
def pivotalias_sql(self, expression: sqlglot.expressions.PivotAlias) -> str:
3196    def pivotalias_sql(self, expression: exp.PivotAlias) -> str:
3197        alias = expression.args["alias"]
3198
3199        parent = expression.parent
3200        pivot = parent and parent.parent
3201
3202        if isinstance(pivot, exp.Pivot) and pivot.unpivot:
3203            identifier_alias = isinstance(alias, exp.Identifier)
3204            literal_alias = isinstance(alias, exp.Literal)
3205
3206            if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
3207                alias.replace(exp.Literal.string(alias.output_name))
3208            elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
3209                alias.replace(exp.to_identifier(alias.output_name))
3210
3211        return self.alias_sql(expression)
def aliases_sql(self, expression: sqlglot.expressions.Aliases) -> str:
3213    def aliases_sql(self, expression: exp.Aliases) -> str:
3214        return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})"
def atindex_sql(self, expression: sqlglot.expressions.AtTimeZone) -> str:
3216    def atindex_sql(self, expression: exp.AtTimeZone) -> str:
3217        this = self.sql(expression, "this")
3218        index = self.sql(expression, "expression")
3219        return f"{this} AT {index}"
def attimezone_sql(self, expression: sqlglot.expressions.AtTimeZone) -> str:
3221    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
3222        this = self.sql(expression, "this")
3223        zone = self.sql(expression, "zone")
3224        return f"{this} AT TIME ZONE {zone}"
def fromtimezone_sql(self, expression: sqlglot.expressions.FromTimeZone) -> str:
3226    def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str:
3227        this = self.sql(expression, "this")
3228        zone = self.sql(expression, "zone")
3229        return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'"
def add_sql(self, expression: sqlglot.expressions.Add) -> str:
3231    def add_sql(self, expression: exp.Add) -> str:
3232        return self.binary(expression, "+")
def and_sql( self, expression: sqlglot.expressions.And, stack: Optional[List[str | sqlglot.expressions.Expression]] = None) -> str:
3234    def and_sql(
3235        self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None
3236    ) -> str:
3237        return self.connector_sql(expression, "AND", stack)
def or_sql( self, expression: sqlglot.expressions.Or, stack: Optional[List[str | sqlglot.expressions.Expression]] = None) -> str:
3239    def or_sql(
3240        self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None
3241    ) -> str:
3242        return self.connector_sql(expression, "OR", stack)
def xor_sql( self, expression: sqlglot.expressions.Xor, stack: Optional[List[str | sqlglot.expressions.Expression]] = None) -> str:
3244    def xor_sql(
3245        self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None
3246    ) -> str:
3247        return self.connector_sql(expression, "XOR", stack)
def connector_sql( self, expression: sqlglot.expressions.Connector, op: str, stack: Optional[List[str | sqlglot.expressions.Expression]] = None) -> str:
3249    def connector_sql(
3250        self,
3251        expression: exp.Connector,
3252        op: str,
3253        stack: t.Optional[t.List[str | exp.Expression]] = None,
3254    ) -> str:
3255        if stack is not None:
3256            if expression.expressions:
3257                stack.append(self.expressions(expression, sep=f" {op} "))
3258            else:
3259                stack.append(expression.right)
3260                if expression.comments and self.comments:
3261                    for comment in expression.comments:
3262                        if comment:
3263                            op += f" /*{self.sanitize_comment(comment)}*/"
3264                stack.extend((op, expression.left))
3265            return op
3266
3267        stack = [expression]
3268        sqls: t.List[str] = []
3269        ops = set()
3270
3271        while stack:
3272            node = stack.pop()
3273            if isinstance(node, exp.Connector):
3274                ops.add(getattr(self, f"{node.key}_sql")(node, stack))
3275            else:
3276                sql = self.sql(node)
3277                if sqls and sqls[-1] in ops:
3278                    sqls[-1] += f" {sql}"
3279                else:
3280                    sqls.append(sql)
3281
3282        sep = "\n" if self.pretty and self.too_wide(sqls) else " "
3283        return sep.join(sqls)
def bitwiseand_sql(self, expression: sqlglot.expressions.BitwiseAnd) -> str:
3285    def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str:
3286        return self.binary(expression, "&")
def bitwiseleftshift_sql(self, expression: sqlglot.expressions.BitwiseLeftShift) -> str:
3288    def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str:
3289        return self.binary(expression, "<<")
def bitwisenot_sql(self, expression: sqlglot.expressions.BitwiseNot) -> str:
3291    def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str:
3292        return f"~{self.sql(expression, 'this')}"
def bitwiseor_sql(self, expression: sqlglot.expressions.BitwiseOr) -> str:
3294    def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str:
3295        return self.binary(expression, "|")
def bitwiserightshift_sql(self, expression: sqlglot.expressions.BitwiseRightShift) -> str:
3297    def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str:
3298        return self.binary(expression, ">>")
def bitwisexor_sql(self, expression: sqlglot.expressions.BitwiseXor) -> str:
3300    def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str:
3301        return self.binary(expression, "^")
def cast_sql( self, expression: sqlglot.expressions.Cast, safe_prefix: Optional[str] = None) -> str:
3303    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
3304        format_sql = self.sql(expression, "format")
3305        format_sql = f" FORMAT {format_sql}" if format_sql else ""
3306        to_sql = self.sql(expression, "to")
3307        to_sql = f" {to_sql}" if to_sql else ""
3308        action = self.sql(expression, "action")
3309        action = f" {action}" if action else ""
3310        default = self.sql(expression, "default")
3311        default = f" DEFAULT {default} ON CONVERSION ERROR" if default else ""
3312        return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{default}{format_sql}{action})"
def currentdate_sql(self, expression: sqlglot.expressions.CurrentDate) -> str:
3314    def currentdate_sql(self, expression: exp.CurrentDate) -> str:
3315        zone = self.sql(expression, "this")
3316        return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE"
def collate_sql(self, expression: sqlglot.expressions.Collate) -> str:
3318    def collate_sql(self, expression: exp.Collate) -> str:
3319        if self.COLLATE_IS_FUNC:
3320            return self.function_fallback_sql(expression)
3321        return self.binary(expression, "COLLATE")
def command_sql(self, expression: sqlglot.expressions.Command) -> str:
3323    def command_sql(self, expression: exp.Command) -> str:
3324        return f"{self.sql(expression, 'this')} {expression.text('expression').strip()}"
def comment_sql(self, expression: sqlglot.expressions.Comment) -> str:
3326    def comment_sql(self, expression: exp.Comment) -> str:
3327        this = self.sql(expression, "this")
3328        kind = expression.args["kind"]
3329        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
3330        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
3331        expression_sql = self.sql(expression, "expression")
3332        return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"
def mergetreettlaction_sql(self, expression: sqlglot.expressions.MergeTreeTTLAction) -> str:
3334    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
3335        this = self.sql(expression, "this")
3336        delete = " DELETE" if expression.args.get("delete") else ""
3337        recompress = self.sql(expression, "recompress")
3338        recompress = f" RECOMPRESS {recompress}" if recompress else ""
3339        to_disk = self.sql(expression, "to_disk")
3340        to_disk = f" TO DISK {to_disk}" if to_disk else ""
3341        to_volume = self.sql(expression, "to_volume")
3342        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
3343        return f"{this}{delete}{recompress}{to_disk}{to_volume}"
def mergetreettl_sql(self, expression: sqlglot.expressions.MergeTreeTTL) -> str:
3345    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
3346        where = self.sql(expression, "where")
3347        group = self.sql(expression, "group")
3348        aggregates = self.expressions(expression, key="aggregates")
3349        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
3350
3351        if not (where or group or aggregates) and len(expression.expressions) == 1:
3352            return f"TTL {self.expressions(expression, flat=True)}"
3353
3354        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"
def transaction_sql(self, expression: sqlglot.expressions.Transaction) -> str:
3356    def transaction_sql(self, expression: exp.Transaction) -> str:
3357        return "BEGIN"
def commit_sql(self, expression: sqlglot.expressions.Commit) -> str:
3359    def commit_sql(self, expression: exp.Commit) -> str:
3360        chain = expression.args.get("chain")
3361        if chain is not None:
3362            chain = " AND CHAIN" if chain else " AND NO CHAIN"
3363
3364        return f"COMMIT{chain or ''}"
def rollback_sql(self, expression: sqlglot.expressions.Rollback) -> str:
3366    def rollback_sql(self, expression: exp.Rollback) -> str:
3367        savepoint = expression.args.get("savepoint")
3368        savepoint = f" TO {savepoint}" if savepoint else ""
3369        return f"ROLLBACK{savepoint}"
def altercolumn_sql(self, expression: sqlglot.expressions.AlterColumn) -> str:
3371    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
3372        this = self.sql(expression, "this")
3373
3374        dtype = self.sql(expression, "dtype")
3375        if dtype:
3376            collate = self.sql(expression, "collate")
3377            collate = f" COLLATE {collate}" if collate else ""
3378            using = self.sql(expression, "using")
3379            using = f" USING {using}" if using else ""
3380            alter_set_type = self.ALTER_SET_TYPE + " " if self.ALTER_SET_TYPE else ""
3381            return f"ALTER COLUMN {this} {alter_set_type}{dtype}{collate}{using}"
3382
3383        default = self.sql(expression, "default")
3384        if default:
3385            return f"ALTER COLUMN {this} SET DEFAULT {default}"
3386
3387        comment = self.sql(expression, "comment")
3388        if comment:
3389            return f"ALTER COLUMN {this} COMMENT {comment}"
3390
3391        visible = expression.args.get("visible")
3392        if visible:
3393            return f"ALTER COLUMN {this} SET {visible}"
3394
3395        allow_null = expression.args.get("allow_null")
3396        drop = expression.args.get("drop")
3397
3398        if not drop and not allow_null:
3399            self.unsupported("Unsupported ALTER COLUMN syntax")
3400
3401        if allow_null is not None:
3402            keyword = "DROP" if drop else "SET"
3403            return f"ALTER COLUMN {this} {keyword} NOT NULL"
3404
3405        return f"ALTER COLUMN {this} DROP DEFAULT"
def alterindex_sql(self, expression: sqlglot.expressions.AlterIndex) -> str:
3407    def alterindex_sql(self, expression: exp.AlterIndex) -> str:
3408        this = self.sql(expression, "this")
3409
3410        visible = expression.args.get("visible")
3411        visible_sql = "VISIBLE" if visible else "INVISIBLE"
3412
3413        return f"ALTER INDEX {this} {visible_sql}"
def alterdiststyle_sql(self, expression: sqlglot.expressions.AlterDistStyle) -> str:
3415    def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str:
3416        this = self.sql(expression, "this")
3417        if not isinstance(expression.this, exp.Var):
3418            this = f"KEY DISTKEY {this}"
3419        return f"ALTER DISTSTYLE {this}"
def altersortkey_sql(self, expression: sqlglot.expressions.AlterSortKey) -> str:
3421    def altersortkey_sql(self, expression: exp.AlterSortKey) -> str:
3422        compound = " COMPOUND" if expression.args.get("compound") else ""
3423        this = self.sql(expression, "this")
3424        expressions = self.expressions(expression, flat=True)
3425        expressions = f"({expressions})" if expressions else ""
3426        return f"ALTER{compound} SORTKEY {this or expressions}"
def alterrename_sql(self, expression: sqlglot.expressions.AlterRename) -> str:
3428    def alterrename_sql(self, expression: exp.AlterRename) -> str:
3429        if not self.RENAME_TABLE_WITH_DB:
3430            # Remove db from tables
3431            expression = expression.transform(
3432                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
3433            ).assert_is(exp.AlterRename)
3434        this = self.sql(expression, "this")
3435        return f"RENAME TO {this}"
def renamecolumn_sql(self, expression: sqlglot.expressions.RenameColumn) -> str:
3437    def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
3438        exists = " IF EXISTS" if expression.args.get("exists") else ""
3439        old_column = self.sql(expression, "this")
3440        new_column = self.sql(expression, "to")
3441        return f"RENAME COLUMN{exists} {old_column} TO {new_column}"
def alterset_sql(self, expression: sqlglot.expressions.AlterSet) -> str:
3443    def alterset_sql(self, expression: exp.AlterSet) -> str:
3444        exprs = self.expressions(expression, flat=True)
3445        if self.ALTER_SET_WRAPPED:
3446            exprs = f"({exprs})"
3447
3448        return f"SET {exprs}"
def alter_sql(self, expression: sqlglot.expressions.Alter) -> str:
3450    def alter_sql(self, expression: exp.Alter) -> str:
3451        actions = expression.args["actions"]
3452
3453        if not self.dialect.ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN and isinstance(
3454            actions[0], exp.ColumnDef
3455        ):
3456            actions_sql = self.expressions(expression, key="actions", flat=True)
3457            actions_sql = f"ADD {actions_sql}"
3458        else:
3459            actions_list = []
3460            for action in actions:
3461                if isinstance(action, (exp.ColumnDef, exp.Schema)):
3462                    action_sql = self.add_column_sql(action)
3463                else:
3464                    action_sql = self.sql(action)
3465                    if isinstance(action, exp.Query):
3466                        action_sql = f"AS {action_sql}"
3467
3468                actions_list.append(action_sql)
3469
3470            actions_sql = self.format_args(*actions_list)
3471
3472        exists = " IF EXISTS" if expression.args.get("exists") else ""
3473        on_cluster = self.sql(expression, "cluster")
3474        on_cluster = f" {on_cluster}" if on_cluster else ""
3475        only = " ONLY" if expression.args.get("only") else ""
3476        options = self.expressions(expression, key="options")
3477        options = f", {options}" if options else ""
3478        kind = self.sql(expression, "kind")
3479        not_valid = " NOT VALID" if expression.args.get("not_valid") else ""
3480
3481        return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions_sql}{not_valid}{options}"
def add_column_sql(self, expression: sqlglot.expressions.Expression) -> str:
3483    def add_column_sql(self, expression: exp.Expression) -> str:
3484        sql = self.sql(expression)
3485        if isinstance(expression, exp.Schema):
3486            column_text = " COLUMNS"
3487        elif isinstance(expression, exp.ColumnDef) and self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD:
3488            column_text = " COLUMN"
3489        else:
3490            column_text = ""
3491
3492        return f"ADD{column_text} {sql}"
def droppartition_sql(self, expression: sqlglot.expressions.DropPartition) -> str:
3494    def droppartition_sql(self, expression: exp.DropPartition) -> str:
3495        expressions = self.expressions(expression)
3496        exists = " IF EXISTS " if expression.args.get("exists") else " "
3497        return f"DROP{exists}{expressions}"
def addconstraint_sql(self, expression: sqlglot.expressions.AddConstraint) -> str:
3499    def addconstraint_sql(self, expression: exp.AddConstraint) -> str:
3500        return f"ADD {self.expressions(expression)}"
def addpartition_sql(self, expression: sqlglot.expressions.AddPartition) -> str:
3502    def addpartition_sql(self, expression: exp.AddPartition) -> str:
3503        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
3504        return f"ADD {exists}{self.sql(expression.this)}"
def distinct_sql(self, expression: sqlglot.expressions.Distinct) -> str:
3506    def distinct_sql(self, expression: exp.Distinct) -> str:
3507        this = self.expressions(expression, flat=True)
3508
3509        if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1:
3510            case = exp.case()
3511            for arg in expression.expressions:
3512                case = case.when(arg.is_(exp.null()), exp.null())
3513            this = self.sql(case.else_(f"({this})"))
3514
3515        this = f" {this}" if this else ""
3516
3517        on = self.sql(expression, "on")
3518        on = f" ON {on}" if on else ""
3519        return f"DISTINCT{this}{on}"
def ignorenulls_sql(self, expression: sqlglot.expressions.IgnoreNulls) -> str:
3521    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
3522        return self._embed_ignore_nulls(expression, "IGNORE NULLS")
def respectnulls_sql(self, expression: sqlglot.expressions.RespectNulls) -> str:
3524    def respectnulls_sql(self, expression: exp.RespectNulls) -> str:
3525        return self._embed_ignore_nulls(expression, "RESPECT NULLS")
def havingmax_sql(self, expression: sqlglot.expressions.HavingMax) -> str:
3527    def havingmax_sql(self, expression: exp.HavingMax) -> str:
3528        this_sql = self.sql(expression, "this")
3529        expression_sql = self.sql(expression, "expression")
3530        kind = "MAX" if expression.args.get("max") else "MIN"
3531        return f"{this_sql} HAVING {kind} {expression_sql}"
def intdiv_sql(self, expression: sqlglot.expressions.IntDiv) -> str:
3533    def intdiv_sql(self, expression: exp.IntDiv) -> str:
3534        return self.sql(
3535            exp.Cast(
3536                this=exp.Div(this=expression.this, expression=expression.expression),
3537                to=exp.DataType(this=exp.DataType.Type.INT),
3538            )
3539        )
def dpipe_sql(self, expression: sqlglot.expressions.DPipe) -> str:
3541    def dpipe_sql(self, expression: exp.DPipe) -> str:
3542        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
3543            return self.func(
3544                "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten())
3545            )
3546        return self.binary(expression, "||")
def div_sql(self, expression: sqlglot.expressions.Div) -> str:
3548    def div_sql(self, expression: exp.Div) -> str:
3549        l, r = expression.left, expression.right
3550
3551        if not self.dialect.SAFE_DIVISION and expression.args.get("safe"):
3552            r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0)))
3553
3554        if self.dialect.TYPED_DIVISION and not expression.args.get("typed"):
3555            if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES):
3556                l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE))
3557
3558        elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"):
3559            if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES):
3560                return self.sql(
3561                    exp.cast(
3562                        l / r,
3563                        to=exp.DataType.Type.BIGINT,
3564                    )
3565                )
3566
3567        return self.binary(expression, "/")
def safedivide_sql(self, expression: sqlglot.expressions.SafeDivide) -> str:
3569    def safedivide_sql(self, expression: exp.SafeDivide) -> str:
3570        n = exp._wrap(expression.this, exp.Binary)
3571        d = exp._wrap(expression.expression, exp.Binary)
3572        return self.sql(exp.If(this=d.neq(0), true=n / d, false=exp.Null()))
def overlaps_sql(self, expression: sqlglot.expressions.Overlaps) -> str:
3574    def overlaps_sql(self, expression: exp.Overlaps) -> str:
3575        return self.binary(expression, "OVERLAPS")
def distance_sql(self, expression: sqlglot.expressions.Distance) -> str:
3577    def distance_sql(self, expression: exp.Distance) -> str:
3578        return self.binary(expression, "<->")
def dot_sql(self, expression: sqlglot.expressions.Dot) -> str:
3580    def dot_sql(self, expression: exp.Dot) -> str:
3581        return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}"
def eq_sql(self, expression: sqlglot.expressions.EQ) -> str:
3583    def eq_sql(self, expression: exp.EQ) -> str:
3584        return self.binary(expression, "=")
def propertyeq_sql(self, expression: sqlglot.expressions.PropertyEQ) -> str:
3586    def propertyeq_sql(self, expression: exp.PropertyEQ) -> str:
3587        return self.binary(expression, ":=")
def escape_sql(self, expression: sqlglot.expressions.Escape) -> str:
3589    def escape_sql(self, expression: exp.Escape) -> str:
3590        return self.binary(expression, "ESCAPE")
def glob_sql(self, expression: sqlglot.expressions.Glob) -> str:
3592    def glob_sql(self, expression: exp.Glob) -> str:
3593        return self.binary(expression, "GLOB")
def gt_sql(self, expression: sqlglot.expressions.GT) -> str:
3595    def gt_sql(self, expression: exp.GT) -> str:
3596        return self.binary(expression, ">")
def gte_sql(self, expression: sqlglot.expressions.GTE) -> str:
3598    def gte_sql(self, expression: exp.GTE) -> str:
3599        return self.binary(expression, ">=")
def ilike_sql(self, expression: sqlglot.expressions.ILike) -> str:
3601    def ilike_sql(self, expression: exp.ILike) -> str:
3602        return self.binary(expression, "ILIKE")
def ilikeany_sql(self, expression: sqlglot.expressions.ILikeAny) -> str:
3604    def ilikeany_sql(self, expression: exp.ILikeAny) -> str:
3605        return self.binary(expression, "ILIKE ANY")
def is_sql(self, expression: sqlglot.expressions.Is) -> str:
3607    def is_sql(self, expression: exp.Is) -> str:
3608        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
3609            return self.sql(
3610                expression.this if expression.expression.this else exp.not_(expression.this)
3611            )
3612        return self.binary(expression, "IS")
def like_sql(self, expression: sqlglot.expressions.Like) -> str:
3614    def like_sql(self, expression: exp.Like) -> str:
3615        return self.binary(expression, "LIKE")
def likeany_sql(self, expression: sqlglot.expressions.LikeAny) -> str:
3617    def likeany_sql(self, expression: exp.LikeAny) -> str:
3618        return self.binary(expression, "LIKE ANY")
def similarto_sql(self, expression: sqlglot.expressions.SimilarTo) -> str:
3620    def similarto_sql(self, expression: exp.SimilarTo) -> str:
3621        return self.binary(expression, "SIMILAR TO")
def lt_sql(self, expression: sqlglot.expressions.LT) -> str:
3623    def lt_sql(self, expression: exp.LT) -> str:
3624        return self.binary(expression, "<")
def lte_sql(self, expression: sqlglot.expressions.LTE) -> str:
3626    def lte_sql(self, expression: exp.LTE) -> str:
3627        return self.binary(expression, "<=")
def mod_sql(self, expression: sqlglot.expressions.Mod) -> str:
3629    def mod_sql(self, expression: exp.Mod) -> str:
3630        return self.binary(expression, "%")
def mul_sql(self, expression: sqlglot.expressions.Mul) -> str:
3632    def mul_sql(self, expression: exp.Mul) -> str:
3633        return self.binary(expression, "*")
def neq_sql(self, expression: sqlglot.expressions.NEQ) -> str:
3635    def neq_sql(self, expression: exp.NEQ) -> str:
3636        return self.binary(expression, "<>")
def nullsafeeq_sql(self, expression: sqlglot.expressions.NullSafeEQ) -> str:
3638    def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str:
3639        return self.binary(expression, "IS NOT DISTINCT FROM")
def nullsafeneq_sql(self, expression: sqlglot.expressions.NullSafeNEQ) -> str:
3641    def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str:
3642        return self.binary(expression, "IS DISTINCT FROM")
def slice_sql(self, expression: sqlglot.expressions.Slice) -> str:
3644    def slice_sql(self, expression: exp.Slice) -> str:
3645        return self.binary(expression, ":")
def sub_sql(self, expression: sqlglot.expressions.Sub) -> str:
3647    def sub_sql(self, expression: exp.Sub) -> str:
3648        return self.binary(expression, "-")
def trycast_sql(self, expression: sqlglot.expressions.TryCast) -> str:
3650    def trycast_sql(self, expression: exp.TryCast) -> str:
3651        return self.cast_sql(expression, safe_prefix="TRY_")
def jsoncast_sql(self, expression: sqlglot.expressions.JSONCast) -> str:
3653    def jsoncast_sql(self, expression: exp.JSONCast) -> str:
3654        return self.cast_sql(expression)
def try_sql(self, expression: sqlglot.expressions.Try) -> str:
3656    def try_sql(self, expression: exp.Try) -> str:
3657        if not self.TRY_SUPPORTED:
3658            self.unsupported("Unsupported TRY function")
3659            return self.sql(expression, "this")
3660
3661        return self.func("TRY", expression.this)
def log_sql(self, expression: sqlglot.expressions.Log) -> str:
3663    def log_sql(self, expression: exp.Log) -> str:
3664        this = expression.this
3665        expr = expression.expression
3666
3667        if self.dialect.LOG_BASE_FIRST is False:
3668            this, expr = expr, this
3669        elif self.dialect.LOG_BASE_FIRST is None and expr:
3670            if this.name in ("2", "10"):
3671                return self.func(f"LOG{this.name}", expr)
3672
3673            self.unsupported(f"Unsupported logarithm with base {self.sql(this)}")
3674
3675        return self.func("LOG", this, expr)
def use_sql(self, expression: sqlglot.expressions.Use) -> str:
3677    def use_sql(self, expression: exp.Use) -> str:
3678        kind = self.sql(expression, "kind")
3679        kind = f" {kind}" if kind else ""
3680        this = self.sql(expression, "this") or self.expressions(expression, flat=True)
3681        this = f" {this}" if this else ""
3682        return f"USE{kind}{this}"
def binary(self, expression: sqlglot.expressions.Binary, op: str) -> str:
3684    def binary(self, expression: exp.Binary, op: str) -> str:
3685        sqls: t.List[str] = []
3686        stack: t.List[t.Union[str, exp.Expression]] = [expression]
3687        binary_type = type(expression)
3688
3689        while stack:
3690            node = stack.pop()
3691
3692            if type(node) is binary_type:
3693                op_func = node.args.get("operator")
3694                if op_func:
3695                    op = f"OPERATOR({self.sql(op_func)})"
3696
3697                stack.append(node.right)
3698                stack.append(f" {self.maybe_comment(op, comments=node.comments)} ")
3699                stack.append(node.left)
3700            else:
3701                sqls.append(self.sql(node))
3702
3703        return "".join(sqls)
def ceil_floor( self, expression: sqlglot.expressions.Ceil | sqlglot.expressions.Floor) -> str:
3705    def ceil_floor(self, expression: exp.Ceil | exp.Floor) -> str:
3706        to_clause = self.sql(expression, "to")
3707        if to_clause:
3708            return f"{expression.sql_name()}({self.sql(expression, 'this')} TO {to_clause})"
3709
3710        return self.function_fallback_sql(expression)
def function_fallback_sql(self, expression: sqlglot.expressions.Func) -> str:
3712    def function_fallback_sql(self, expression: exp.Func) -> str:
3713        args = []
3714
3715        for key in expression.arg_types:
3716            arg_value = expression.args.get(key)
3717
3718            if isinstance(arg_value, list):
3719                for value in arg_value:
3720                    args.append(value)
3721            elif arg_value is not None:
3722                args.append(arg_value)
3723
3724        if self.dialect.PRESERVE_ORIGINAL_NAMES:
3725            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
3726        else:
3727            name = expression.sql_name()
3728
3729        return self.func(name, *args)
def func( self, name: str, *args: Union[str, sqlglot.expressions.Expression, NoneType], prefix: str = '(', suffix: str = ')', normalize: bool = True) -> str:
3731    def func(
3732        self,
3733        name: str,
3734        *args: t.Optional[exp.Expression | str],
3735        prefix: str = "(",
3736        suffix: str = ")",
3737        normalize: bool = True,
3738    ) -> str:
3739        name = self.normalize_func(name) if normalize else name
3740        return f"{name}{prefix}{self.format_args(*args)}{suffix}"
def format_args( self, *args: Union[str, sqlglot.expressions.Expression, NoneType], sep: str = ', ') -> str:
3742    def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str:
3743        arg_sqls = tuple(
3744            self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool)
3745        )
3746        if self.pretty and self.too_wide(arg_sqls):
3747            return self.indent(
3748                "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True
3749            )
3750        return sep.join(arg_sqls)
def too_wide(self, args: Iterable) -> bool:
3752    def too_wide(self, args: t.Iterable) -> bool:
3753        return sum(len(arg) for arg in args) > self.max_text_width
def format_time( self, expression: sqlglot.expressions.Expression, inverse_time_mapping: Optional[Dict[str, str]] = None, inverse_time_trie: Optional[Dict] = None) -> Optional[str]:
3755    def format_time(
3756        self,
3757        expression: exp.Expression,
3758        inverse_time_mapping: t.Optional[t.Dict[str, str]] = None,
3759        inverse_time_trie: t.Optional[t.Dict] = None,
3760    ) -> t.Optional[str]:
3761        return format_time(
3762            self.sql(expression, "format"),
3763            inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING,
3764            inverse_time_trie or self.dialect.INVERSE_TIME_TRIE,
3765        )
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, skip_last: bool = False, sep: str = ', ', prefix: str = '', dynamic: bool = False, new_line: bool = False) -> str:
3767    def expressions(
3768        self,
3769        expression: t.Optional[exp.Expression] = None,
3770        key: t.Optional[str] = None,
3771        sqls: t.Optional[t.Collection[str | exp.Expression]] = None,
3772        flat: bool = False,
3773        indent: bool = True,
3774        skip_first: bool = False,
3775        skip_last: bool = False,
3776        sep: str = ", ",
3777        prefix: str = "",
3778        dynamic: bool = False,
3779        new_line: bool = False,
3780    ) -> str:
3781        expressions = expression.args.get(key or "expressions") if expression else sqls
3782
3783        if not expressions:
3784            return ""
3785
3786        if flat:
3787            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
3788
3789        num_sqls = len(expressions)
3790        result_sqls = []
3791
3792        for i, e in enumerate(expressions):
3793            sql = self.sql(e, comment=False)
3794            if not sql:
3795                continue
3796
3797            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
3798
3799            if self.pretty:
3800                if self.leading_comma:
3801                    result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}")
3802                else:
3803                    result_sqls.append(
3804                        f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}"
3805                    )
3806            else:
3807                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
3808
3809        if self.pretty and (not dynamic or self.too_wide(result_sqls)):
3810            if new_line:
3811                result_sqls.insert(0, "")
3812                result_sqls.append("")
3813            result_sql = "\n".join(s.rstrip() for s in result_sqls)
3814        else:
3815            result_sql = "".join(result_sqls)
3816
3817        return (
3818            self.indent(result_sql, skip_first=skip_first, skip_last=skip_last)
3819            if indent
3820            else result_sql
3821        )
def op_expressions( self, op: str, expression: sqlglot.expressions.Expression, flat: bool = False) -> str:
3823    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
3824        flat = flat or isinstance(expression.parent, exp.Properties)
3825        expressions_sql = self.expressions(expression, flat=flat)
3826        if flat:
3827            return f"{op} {expressions_sql}"
3828        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"
def naked_property(self, expression: sqlglot.expressions.Property) -> str:
3830    def naked_property(self, expression: exp.Property) -> str:
3831        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
3832        if not property_name:
3833            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
3834        return f"{property_name} {self.sql(expression, 'this')}"
def tag_sql(self, expression: sqlglot.expressions.Tag) -> str:
3836    def tag_sql(self, expression: exp.Tag) -> str:
3837        return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}"
def token_sql(self, token_type: sqlglot.tokens.TokenType) -> str:
3839    def token_sql(self, token_type: TokenType) -> str:
3840        return self.TOKEN_MAPPING.get(token_type, token_type.name)
def userdefinedfunction_sql(self, expression: sqlglot.expressions.UserDefinedFunction) -> str:
3842    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
3843        this = self.sql(expression, "this")
3844        expressions = self.no_identify(self.expressions, expression)
3845        expressions = (
3846            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
3847        )
3848        return f"{this}{expressions}" if expressions.strip() != "" else this
def joinhint_sql(self, expression: sqlglot.expressions.JoinHint) -> str:
3850    def joinhint_sql(self, expression: exp.JoinHint) -> str:
3851        this = self.sql(expression, "this")
3852        expressions = self.expressions(expression, flat=True)
3853        return f"{this}({expressions})"
def kwarg_sql(self, expression: sqlglot.expressions.Kwarg) -> str:
3855    def kwarg_sql(self, expression: exp.Kwarg) -> str:
3856        return self.binary(expression, "=>")
def when_sql(self, expression: sqlglot.expressions.When) -> str:
3858    def when_sql(self, expression: exp.When) -> str:
3859        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
3860        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
3861        condition = self.sql(expression, "condition")
3862        condition = f" AND {condition}" if condition else ""
3863
3864        then_expression = expression.args.get("then")
3865        if isinstance(then_expression, exp.Insert):
3866            this = self.sql(then_expression, "this")
3867            this = f"INSERT {this}" if this else "INSERT"
3868            then = self.sql(then_expression, "expression")
3869            then = f"{this} VALUES {then}" if then else this
3870        elif isinstance(then_expression, exp.Update):
3871            if isinstance(then_expression.args.get("expressions"), exp.Star):
3872                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
3873            else:
3874                then = f"UPDATE SET{self.sep()}{self.expressions(then_expression)}"
3875        else:
3876            then = self.sql(then_expression)
3877        return f"WHEN {matched}{source}{condition} THEN {then}"
def whens_sql(self, expression: sqlglot.expressions.Whens) -> str:
3879    def whens_sql(self, expression: exp.Whens) -> str:
3880        return self.expressions(expression, sep=" ", indent=False)
def merge_sql(self, expression: sqlglot.expressions.Merge) -> str:
3882    def merge_sql(self, expression: exp.Merge) -> str:
3883        table = expression.this
3884        table_alias = ""
3885
3886        hints = table.args.get("hints")
3887        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
3888            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
3889            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
3890
3891        this = self.sql(table)
3892        using = f"USING {self.sql(expression, 'using')}"
3893        on = f"ON {self.sql(expression, 'on')}"
3894        whens = self.sql(expression, "whens")
3895
3896        returning = self.sql(expression, "returning")
3897        if returning:
3898            whens = f"{whens}{returning}"
3899
3900        sep = self.sep()
3901
3902        return self.prepend_ctes(
3903            expression,
3904            f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}",
3905        )
@unsupported_args('format')
def tochar_sql(self, expression: sqlglot.expressions.ToChar) -> str:
3907    @unsupported_args("format")
3908    def tochar_sql(self, expression: exp.ToChar) -> str:
3909        return self.sql(exp.cast(expression.this, exp.DataType.Type.TEXT))
def tonumber_sql(self, expression: sqlglot.expressions.ToNumber) -> str:
3911    def tonumber_sql(self, expression: exp.ToNumber) -> str:
3912        if not self.SUPPORTS_TO_NUMBER:
3913            self.unsupported("Unsupported TO_NUMBER function")
3914            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
3915
3916        fmt = expression.args.get("format")
3917        if not fmt:
3918            self.unsupported("Conversion format is required for TO_NUMBER")
3919            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
3920
3921        return self.func("TO_NUMBER", expression.this, fmt)
def dictproperty_sql(self, expression: sqlglot.expressions.DictProperty) -> str:
3923    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
3924        this = self.sql(expression, "this")
3925        kind = self.sql(expression, "kind")
3926        settings_sql = self.expressions(expression, key="settings", sep=" ")
3927        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
3928        return f"{this}({kind}{args})"
def dictrange_sql(self, expression: sqlglot.expressions.DictRange) -> str:
3930    def dictrange_sql(self, expression: exp.DictRange) -> str:
3931        this = self.sql(expression, "this")
3932        max = self.sql(expression, "max")
3933        min = self.sql(expression, "min")
3934        return f"{this}(MIN {min} MAX {max})"
def dictsubproperty_sql(self, expression: sqlglot.expressions.DictSubProperty) -> str:
3936    def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str:
3937        return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}"
def duplicatekeyproperty_sql(self, expression: sqlglot.expressions.DuplicateKeyProperty) -> str:
3939    def duplicatekeyproperty_sql(self, expression: exp.DuplicateKeyProperty) -> str:
3940        return f"DUPLICATE KEY ({self.expressions(expression, flat=True)})"
def uniquekeyproperty_sql(self, expression: sqlglot.expressions.UniqueKeyProperty) -> str:
3943    def uniquekeyproperty_sql(self, expression: exp.UniqueKeyProperty) -> str:
3944        return f"UNIQUE KEY ({self.expressions(expression, flat=True)})"
def distributedbyproperty_sql(self, expression: sqlglot.expressions.DistributedByProperty) -> str:
3947    def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str:
3948        expressions = self.expressions(expression, flat=True)
3949        expressions = f" {self.wrap(expressions)}" if expressions else ""
3950        buckets = self.sql(expression, "buckets")
3951        kind = self.sql(expression, "kind")
3952        buckets = f" BUCKETS {buckets}" if buckets else ""
3953        order = self.sql(expression, "order")
3954        return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}"
def oncluster_sql(self, expression: sqlglot.expressions.OnCluster) -> str:
3956    def oncluster_sql(self, expression: exp.OnCluster) -> str:
3957        return ""
def clusteredbyproperty_sql(self, expression: sqlglot.expressions.ClusteredByProperty) -> str:
3959    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
3960        expressions = self.expressions(expression, key="expressions", flat=True)
3961        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
3962        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
3963        buckets = self.sql(expression, "buckets")
3964        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"
def anyvalue_sql(self, expression: sqlglot.expressions.AnyValue) -> str:
3966    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
3967        this = self.sql(expression, "this")
3968        having = self.sql(expression, "having")
3969
3970        if having:
3971            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
3972
3973        return self.func("ANY_VALUE", this)
def querytransform_sql(self, expression: sqlglot.expressions.QueryTransform) -> str:
3975    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
3976        transform = self.func("TRANSFORM", *expression.expressions)
3977        row_format_before = self.sql(expression, "row_format_before")
3978        row_format_before = f" {row_format_before}" if row_format_before else ""
3979        record_writer = self.sql(expression, "record_writer")
3980        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
3981        using = f" USING {self.sql(expression, 'command_script')}"
3982        schema = self.sql(expression, "schema")
3983        schema = f" AS {schema}" if schema else ""
3984        row_format_after = self.sql(expression, "row_format_after")
3985        row_format_after = f" {row_format_after}" if row_format_after else ""
3986        record_reader = self.sql(expression, "record_reader")
3987        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
3988        return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}"
def indexconstraintoption_sql(self, expression: sqlglot.expressions.IndexConstraintOption) -> str:
3990    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
3991        key_block_size = self.sql(expression, "key_block_size")
3992        if key_block_size:
3993            return f"KEY_BLOCK_SIZE = {key_block_size}"
3994
3995        using = self.sql(expression, "using")
3996        if using:
3997            return f"USING {using}"
3998
3999        parser = self.sql(expression, "parser")
4000        if parser:
4001            return f"WITH PARSER {parser}"
4002
4003        comment = self.sql(expression, "comment")
4004        if comment:
4005            return f"COMMENT {comment}"
4006
4007        visible = expression.args.get("visible")
4008        if visible is not None:
4009            return "VISIBLE" if visible else "INVISIBLE"
4010
4011        engine_attr = self.sql(expression, "engine_attr")
4012        if engine_attr:
4013            return f"ENGINE_ATTRIBUTE = {engine_attr}"
4014
4015        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
4016        if secondary_engine_attr:
4017            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
4018
4019        self.unsupported("Unsupported index constraint option.")
4020        return ""
def checkcolumnconstraint_sql(self, expression: sqlglot.expressions.CheckColumnConstraint) -> str:
4022    def checkcolumnconstraint_sql(self, expression: exp.CheckColumnConstraint) -> str:
4023        enforced = " ENFORCED" if expression.args.get("enforced") else ""
4024        return f"CHECK ({self.sql(expression, 'this')}){enforced}"
def indexcolumnconstraint_sql(self, expression: sqlglot.expressions.IndexColumnConstraint) -> str:
4026    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
4027        kind = self.sql(expression, "kind")
4028        kind = f"{kind} INDEX" if kind else "INDEX"
4029        this = self.sql(expression, "this")
4030        this = f" {this}" if this else ""
4031        index_type = self.sql(expression, "index_type")
4032        index_type = f" USING {index_type}" if index_type else ""
4033        expressions = self.expressions(expression, flat=True)
4034        expressions = f" ({expressions})" if expressions else ""
4035        options = self.expressions(expression, key="options", sep=" ")
4036        options = f" {options}" if options else ""
4037        return f"{kind}{this}{index_type}{expressions}{options}"
def nvl2_sql(self, expression: sqlglot.expressions.Nvl2) -> str:
4039    def nvl2_sql(self, expression: exp.Nvl2) -> str:
4040        if self.NVL2_SUPPORTED:
4041            return self.function_fallback_sql(expression)
4042
4043        case = exp.Case().when(
4044            expression.this.is_(exp.null()).not_(copy=False),
4045            expression.args["true"],
4046            copy=False,
4047        )
4048        else_cond = expression.args.get("false")
4049        if else_cond:
4050            case.else_(else_cond, copy=False)
4051
4052        return self.sql(case)
def comprehension_sql(self, expression: sqlglot.expressions.Comprehension) -> str:
4054    def comprehension_sql(self, expression: exp.Comprehension) -> str:
4055        this = self.sql(expression, "this")
4056        expr = self.sql(expression, "expression")
4057        iterator = self.sql(expression, "iterator")
4058        condition = self.sql(expression, "condition")
4059        condition = f" IF {condition}" if condition else ""
4060        return f"{this} FOR {expr} IN {iterator}{condition}"
def columnprefix_sql(self, expression: sqlglot.expressions.ColumnPrefix) -> str:
4062    def columnprefix_sql(self, expression: exp.ColumnPrefix) -> str:
4063        return f"{self.sql(expression, 'this')}({self.sql(expression, 'expression')})"
def opclass_sql(self, expression: sqlglot.expressions.Opclass) -> str:
4065    def opclass_sql(self, expression: exp.Opclass) -> str:
4066        return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}"
def predict_sql(self, expression: sqlglot.expressions.Predict) -> str:
4068    def predict_sql(self, expression: exp.Predict) -> str:
4069        model = self.sql(expression, "this")
4070        model = f"MODEL {model}"
4071        table = self.sql(expression, "expression")
4072        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
4073        parameters = self.sql(expression, "params_struct")
4074        return self.func("PREDICT", model, table, parameters or None)
def forin_sql(self, expression: sqlglot.expressions.ForIn) -> str:
4076    def forin_sql(self, expression: exp.ForIn) -> str:
4077        this = self.sql(expression, "this")
4078        expression_sql = self.sql(expression, "expression")
4079        return f"FOR {this} DO {expression_sql}"
def refresh_sql(self, expression: sqlglot.expressions.Refresh) -> str:
4081    def refresh_sql(self, expression: exp.Refresh) -> str:
4082        this = self.sql(expression, "this")
4083        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
4084        return f"REFRESH {table}{this}"
def toarray_sql(self, expression: sqlglot.expressions.ToArray) -> str:
4086    def toarray_sql(self, expression: exp.ToArray) -> str:
4087        arg = expression.this
4088        if not arg.type:
4089            from sqlglot.optimizer.annotate_types import annotate_types
4090
4091            arg = annotate_types(arg, dialect=self.dialect)
4092
4093        if arg.is_type(exp.DataType.Type.ARRAY):
4094            return self.sql(arg)
4095
4096        cond_for_null = arg.is_(exp.null())
4097        return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False)))
def tsordstotime_sql(self, expression: sqlglot.expressions.TsOrDsToTime) -> str:
4099    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
4100        this = expression.this
4101        time_format = self.format_time(expression)
4102
4103        if time_format:
4104            return self.sql(
4105                exp.cast(
4106                    exp.StrToTime(this=this, format=expression.args["format"]),
4107                    exp.DataType.Type.TIME,
4108                )
4109            )
4110
4111        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
4112            return self.sql(this)
4113
4114        return self.sql(exp.cast(this, exp.DataType.Type.TIME))
def tsordstotimestamp_sql(self, expression: sqlglot.expressions.TsOrDsToTimestamp) -> str:
4116    def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str:
4117        this = expression.this
4118        if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP):
4119            return self.sql(this)
4120
4121        return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect))
def tsordstodatetime_sql(self, expression: sqlglot.expressions.TsOrDsToDatetime) -> str:
4123    def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str:
4124        this = expression.this
4125        if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME):
4126            return self.sql(this)
4127
4128        return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect))
def tsordstodate_sql(self, expression: sqlglot.expressions.TsOrDsToDate) -> str:
4130    def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:
4131        this = expression.this
4132        time_format = self.format_time(expression)
4133
4134        if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT):
4135            return self.sql(
4136                exp.cast(
4137                    exp.StrToTime(this=this, format=expression.args["format"]),
4138                    exp.DataType.Type.DATE,
4139                )
4140            )
4141
4142        if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE):
4143            return self.sql(this)
4144
4145        return self.sql(exp.cast(this, exp.DataType.Type.DATE))
def unixdate_sql(self, expression: sqlglot.expressions.UnixDate) -> str:
4147    def unixdate_sql(self, expression: exp.UnixDate) -> str:
4148        return self.sql(
4149            exp.func(
4150                "DATEDIFF",
4151                expression.this,
4152                exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE),
4153                "day",
4154            )
4155        )
def lastday_sql(self, expression: sqlglot.expressions.LastDay) -> str:
4157    def lastday_sql(self, expression: exp.LastDay) -> str:
4158        if self.LAST_DAY_SUPPORTS_DATE_PART:
4159            return self.function_fallback_sql(expression)
4160
4161        unit = expression.text("unit")
4162        if unit and unit != "MONTH":
4163            self.unsupported("Date parts are not supported in LAST_DAY.")
4164
4165        return self.func("LAST_DAY", expression.this)
def dateadd_sql(self, expression: sqlglot.expressions.DateAdd) -> str:
4167    def dateadd_sql(self, expression: exp.DateAdd) -> str:
4168        from sqlglot.dialects.dialect import unit_to_str
4169
4170        return self.func(
4171            "DATE_ADD", expression.this, expression.expression, unit_to_str(expression)
4172        )
def arrayany_sql(self, expression: sqlglot.expressions.ArrayAny) -> str:
4174    def arrayany_sql(self, expression: exp.ArrayAny) -> str:
4175        if self.CAN_IMPLEMENT_ARRAY_ANY:
4176            filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression)
4177            filtered_not_empty = exp.ArraySize(this=filtered).neq(0)
4178            original_is_empty = exp.ArraySize(this=expression.this).eq(0)
4179            return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty)))
4180
4181        from sqlglot.dialects import Dialect
4182
4183        # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect
4184        if self.dialect.__class__ != Dialect:
4185            self.unsupported("ARRAY_ANY is unsupported")
4186
4187        return self.function_fallback_sql(expression)
def struct_sql(self, expression: sqlglot.expressions.Struct) -> str:
4189    def struct_sql(self, expression: exp.Struct) -> str:
4190        expression.set(
4191            "expressions",
4192            [
4193                exp.alias_(e.expression, e.name if e.this.is_string else e.this)
4194                if isinstance(e, exp.PropertyEQ)
4195                else e
4196                for e in expression.expressions
4197            ],
4198        )
4199
4200        return self.function_fallback_sql(expression)
def partitionrange_sql(self, expression: sqlglot.expressions.PartitionRange) -> str:
4202    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
4203        low = self.sql(expression, "this")
4204        high = self.sql(expression, "expression")
4205
4206        return f"{low} TO {high}"
def truncatetable_sql(self, expression: sqlglot.expressions.TruncateTable) -> str:
4208    def truncatetable_sql(self, expression: exp.TruncateTable) -> str:
4209        target = "DATABASE" if expression.args.get("is_database") else "TABLE"
4210        tables = f" {self.expressions(expression)}"
4211
4212        exists = " IF EXISTS" if expression.args.get("exists") else ""
4213
4214        on_cluster = self.sql(expression, "cluster")
4215        on_cluster = f" {on_cluster}" if on_cluster else ""
4216
4217        identity = self.sql(expression, "identity")
4218        identity = f" {identity} IDENTITY" if identity else ""
4219
4220        option = self.sql(expression, "option")
4221        option = f" {option}" if option else ""
4222
4223        partition = self.sql(expression, "partition")
4224        partition = f" {partition}" if partition else ""
4225
4226        return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"
def convert_sql(self, expression: sqlglot.expressions.Convert) -> str:
4230    def convert_sql(self, expression: exp.Convert) -> str:
4231        to = expression.this
4232        value = expression.expression
4233        style = expression.args.get("style")
4234        safe = expression.args.get("safe")
4235        strict = expression.args.get("strict")
4236
4237        if not to or not value:
4238            return ""
4239
4240        # Retrieve length of datatype and override to default if not specified
4241        if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES:
4242            to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
4243
4244        transformed: t.Optional[exp.Expression] = None
4245        cast = exp.Cast if strict else exp.TryCast
4246
4247        # Check whether a conversion with format (T-SQL calls this 'style') is applicable
4248        if isinstance(style, exp.Literal) and style.is_int:
4249            from sqlglot.dialects.tsql import TSQL
4250
4251            style_value = style.name
4252            converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value)
4253            if not converted_style:
4254                self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}")
4255
4256            fmt = exp.Literal.string(converted_style)
4257
4258            if to.this == exp.DataType.Type.DATE:
4259                transformed = exp.StrToDate(this=value, format=fmt)
4260            elif to.this in (exp.DataType.Type.DATETIME, exp.DataType.Type.DATETIME2):
4261                transformed = exp.StrToTime(this=value, format=fmt)
4262            elif to.this in self.PARAMETERIZABLE_TEXT_TYPES:
4263                transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe)
4264            elif to.this == exp.DataType.Type.TEXT:
4265                transformed = exp.TimeToStr(this=value, format=fmt)
4266
4267        if not transformed:
4268            transformed = cast(this=value, to=to, safe=safe)
4269
4270        return self.sql(transformed)
def copyparameter_sql(self, expression: sqlglot.expressions.CopyParameter) -> str:
4338    def copyparameter_sql(self, expression: exp.CopyParameter) -> str:
4339        option = self.sql(expression, "this")
4340
4341        if expression.expressions:
4342            upper = option.upper()
4343
4344            # Snowflake FILE_FORMAT options are separated by whitespace
4345            sep = " " if upper == "FILE_FORMAT" else ", "
4346
4347            # Databricks copy/format options do not set their list of values with EQ
4348            op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = "
4349            values = self.expressions(expression, flat=True, sep=sep)
4350            return f"{option}{op}({values})"
4351
4352        value = self.sql(expression, "expression")
4353
4354        if not value:
4355            return option
4356
4357        op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " "
4358
4359        return f"{option}{op}{value}"
def credentials_sql(self, expression: sqlglot.expressions.Credentials) -> str:
4361    def credentials_sql(self, expression: exp.Credentials) -> str:
4362        cred_expr = expression.args.get("credentials")
4363        if isinstance(cred_expr, exp.Literal):
4364            # Redshift case: CREDENTIALS <string>
4365            credentials = self.sql(expression, "credentials")
4366            credentials = f"CREDENTIALS {credentials}" if credentials else ""
4367        else:
4368            # Snowflake case: CREDENTIALS = (...)
4369            credentials = self.expressions(expression, key="credentials", flat=True, sep=" ")
4370            credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else ""
4371
4372        storage = self.sql(expression, "storage")
4373        storage = f"STORAGE_INTEGRATION = {storage}" if storage else ""
4374
4375        encryption = self.expressions(expression, key="encryption", flat=True, sep=" ")
4376        encryption = f" ENCRYPTION = ({encryption})" if encryption else ""
4377
4378        iam_role = self.sql(expression, "iam_role")
4379        iam_role = f"IAM_ROLE {iam_role}" if iam_role else ""
4380
4381        region = self.sql(expression, "region")
4382        region = f" REGION {region}" if region else ""
4383
4384        return f"{credentials}{storage}{encryption}{iam_role}{region}"
def copy_sql(self, expression: sqlglot.expressions.Copy) -> str:
4386    def copy_sql(self, expression: exp.Copy) -> str:
4387        this = self.sql(expression, "this")
4388        this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}"
4389
4390        credentials = self.sql(expression, "credentials")
4391        credentials = self.seg(credentials) if credentials else ""
4392        kind = self.seg("FROM" if expression.args.get("kind") else "TO")
4393        files = self.expressions(expression, key="files", flat=True)
4394
4395        sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " "
4396        params = self.expressions(
4397            expression,
4398            key="params",
4399            sep=sep,
4400            new_line=True,
4401            skip_last=True,
4402            skip_first=True,
4403            indent=self.COPY_PARAMS_ARE_WRAPPED,
4404        )
4405
4406        if params:
4407            if self.COPY_PARAMS_ARE_WRAPPED:
4408                params = f" WITH ({params})"
4409            elif not self.pretty:
4410                params = f" {params}"
4411
4412        return f"COPY{this}{kind} {files}{credentials}{params}"
def semicolon_sql(self, expression: sqlglot.expressions.Semicolon) -> str:
4414    def semicolon_sql(self, expression: exp.Semicolon) -> str:
4415        return ""
def datadeletionproperty_sql(self, expression: sqlglot.expressions.DataDeletionProperty) -> str:
4417    def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str:
4418        on_sql = "ON" if expression.args.get("on") else "OFF"
4419        filter_col: t.Optional[str] = self.sql(expression, "filter_column")
4420        filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None
4421        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
4422        retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None
4423
4424        if filter_col or retention_period:
4425            on_sql = self.func("ON", filter_col, retention_period)
4426
4427        return f"DATA_DELETION={on_sql}"
def maskingpolicycolumnconstraint_sql( self, expression: sqlglot.expressions.MaskingPolicyColumnConstraint) -> str:
4429    def maskingpolicycolumnconstraint_sql(
4430        self, expression: exp.MaskingPolicyColumnConstraint
4431    ) -> str:
4432        this = self.sql(expression, "this")
4433        expressions = self.expressions(expression, flat=True)
4434        expressions = f" USING ({expressions})" if expressions else ""
4435        return f"MASKING POLICY {this}{expressions}"
def gapfill_sql(self, expression: sqlglot.expressions.GapFill) -> str:
4437    def gapfill_sql(self, expression: exp.GapFill) -> str:
4438        this = self.sql(expression, "this")
4439        this = f"TABLE {this}"
4440        return self.func("GAP_FILL", this, *[v for k, v in expression.args.items() if k != "this"])
def scope_resolution(self, rhs: str, scope_name: str) -> str:
4442    def scope_resolution(self, rhs: str, scope_name: str) -> str:
4443        return self.func("SCOPE_RESOLUTION", scope_name or None, rhs)
def scoperesolution_sql(self, expression: sqlglot.expressions.ScopeResolution) -> str:
4445    def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str:
4446        this = self.sql(expression, "this")
4447        expr = expression.expression
4448
4449        if isinstance(expr, exp.Func):
4450            # T-SQL's CLR functions are case sensitive
4451            expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})"
4452        else:
4453            expr = self.sql(expression, "expression")
4454
4455        return self.scope_resolution(expr, this)
def parsejson_sql(self, expression: sqlglot.expressions.ParseJSON) -> str:
4457    def parsejson_sql(self, expression: exp.ParseJSON) -> str:
4458        if self.PARSE_JSON_NAME is None:
4459            return self.sql(expression.this)
4460
4461        return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression)
def rand_sql(self, expression: sqlglot.expressions.Rand) -> str:
4463    def rand_sql(self, expression: exp.Rand) -> str:
4464        lower = self.sql(expression, "lower")
4465        upper = self.sql(expression, "upper")
4466
4467        if lower and upper:
4468            return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}"
4469        return self.func("RAND", expression.this)
def changes_sql(self, expression: sqlglot.expressions.Changes) -> str:
4471    def changes_sql(self, expression: exp.Changes) -> str:
4472        information = self.sql(expression, "information")
4473        information = f"INFORMATION => {information}"
4474        at_before = self.sql(expression, "at_before")
4475        at_before = f"{self.seg('')}{at_before}" if at_before else ""
4476        end = self.sql(expression, "end")
4477        end = f"{self.seg('')}{end}" if end else ""
4478
4479        return f"CHANGES ({information}){at_before}{end}"
def pad_sql(self, expression: sqlglot.expressions.Pad) -> str:
4481    def pad_sql(self, expression: exp.Pad) -> str:
4482        prefix = "L" if expression.args.get("is_left") else "R"
4483
4484        fill_pattern = self.sql(expression, "fill_pattern") or None
4485        if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED:
4486            fill_pattern = "' '"
4487
4488        return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)
def summarize_sql(self, expression: sqlglot.expressions.Summarize) -> str:
4490    def summarize_sql(self, expression: exp.Summarize) -> str:
4491        table = " TABLE" if expression.args.get("table") else ""
4492        return f"SUMMARIZE{table} {self.sql(expression.this)}"
def explodinggenerateseries_sql(self, expression: sqlglot.expressions.ExplodingGenerateSeries) -> str:
4494    def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str:
4495        generate_series = exp.GenerateSeries(**expression.args)
4496
4497        parent = expression.parent
4498        if isinstance(parent, (exp.Alias, exp.TableAlias)):
4499            parent = parent.parent
4500
4501        if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)):
4502            return self.sql(exp.Unnest(expressions=[generate_series]))
4503
4504        if isinstance(parent, exp.Select):
4505            self.unsupported("GenerateSeries projection unnesting is not supported.")
4506
4507        return self.sql(generate_series)
def arrayconcat_sql( self, expression: sqlglot.expressions.ArrayConcat, name: str = 'ARRAY_CONCAT') -> str:
4509    def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str:
4510        exprs = expression.expressions
4511        if not self.ARRAY_CONCAT_IS_VAR_LEN:
4512            rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs)
4513        else:
4514            rhs = self.expressions(expression)
4515
4516        return self.func(name, expression.this, rhs or None)
def converttimezone_sql(self, expression: sqlglot.expressions.ConvertTimezone) -> str:
4518    def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str:
4519        if self.SUPPORTS_CONVERT_TIMEZONE:
4520            return self.function_fallback_sql(expression)
4521
4522        source_tz = expression.args.get("source_tz")
4523        target_tz = expression.args.get("target_tz")
4524        timestamp = expression.args.get("timestamp")
4525
4526        if source_tz and timestamp:
4527            timestamp = exp.AtTimeZone(
4528                this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz
4529            )
4530
4531        expr = exp.AtTimeZone(this=timestamp, zone=target_tz)
4532
4533        return self.sql(expr)
def json_sql(self, expression: sqlglot.expressions.JSON) -> str:
4535    def json_sql(self, expression: exp.JSON) -> str:
4536        this = self.sql(expression, "this")
4537        this = f" {this}" if this else ""
4538
4539        _with = expression.args.get("with")
4540
4541        if _with is None:
4542            with_sql = ""
4543        elif not _with:
4544            with_sql = " WITHOUT"
4545        else:
4546            with_sql = " WITH"
4547
4548        unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else ""
4549
4550        return f"JSON{this}{with_sql}{unique_sql}"
def jsonvalue_sql(self, expression: sqlglot.expressions.JSONValue) -> str:
4552    def jsonvalue_sql(self, expression: exp.JSONValue) -> str:
4553        def _generate_on_options(arg: t.Any) -> str:
4554            return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}"
4555
4556        path = self.sql(expression, "path")
4557        returning = self.sql(expression, "returning")
4558        returning = f" RETURNING {returning}" if returning else ""
4559
4560        on_condition = self.sql(expression, "on_condition")
4561        on_condition = f" {on_condition}" if on_condition else ""
4562
4563        return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}")
def conditionalinsert_sql(self, expression: sqlglot.expressions.ConditionalInsert) -> str:
4565    def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str:
4566        else_ = "ELSE " if expression.args.get("else_") else ""
4567        condition = self.sql(expression, "expression")
4568        condition = f"WHEN {condition} THEN " if condition else else_
4569        insert = self.sql(expression, "this")[len("INSERT") :].strip()
4570        return f"{condition}{insert}"
def multitableinserts_sql(self, expression: sqlglot.expressions.MultitableInserts) -> str:
4572    def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str:
4573        kind = self.sql(expression, "kind")
4574        expressions = self.seg(self.expressions(expression, sep=" "))
4575        res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}"
4576        return res
def oncondition_sql(self, expression: sqlglot.expressions.OnCondition) -> str:
4578    def oncondition_sql(self, expression: exp.OnCondition) -> str:
4579        # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR"
4580        empty = expression.args.get("empty")
4581        empty = (
4582            f"DEFAULT {empty} ON EMPTY"
4583            if isinstance(empty, exp.Expression)
4584            else self.sql(expression, "empty")
4585        )
4586
4587        error = expression.args.get("error")
4588        error = (
4589            f"DEFAULT {error} ON ERROR"
4590            if isinstance(error, exp.Expression)
4591            else self.sql(expression, "error")
4592        )
4593
4594        if error and empty:
4595            error = (
4596                f"{empty} {error}"
4597                if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR
4598                else f"{error} {empty}"
4599            )
4600            empty = ""
4601
4602        null = self.sql(expression, "null")
4603
4604        return f"{empty}{error}{null}"
def jsonextractquote_sql(self, expression: sqlglot.expressions.JSONExtractQuote) -> str:
4606    def jsonextractquote_sql(self, expression: exp.JSONExtractQuote) -> str:
4607        scalar = " ON SCALAR STRING" if expression.args.get("scalar") else ""
4608        return f"{self.sql(expression, 'option')} QUOTES{scalar}"
def jsonexists_sql(self, expression: sqlglot.expressions.JSONExists) -> str:
4610    def jsonexists_sql(self, expression: exp.JSONExists) -> str:
4611        this = self.sql(expression, "this")
4612        path = self.sql(expression, "path")
4613
4614        passing = self.expressions(expression, "passing")
4615        passing = f" PASSING {passing}" if passing else ""
4616
4617        on_condition = self.sql(expression, "on_condition")
4618        on_condition = f" {on_condition}" if on_condition else ""
4619
4620        path = f"{path}{passing}{on_condition}"
4621
4622        return self.func("JSON_EXISTS", this, path)
def arrayagg_sql(self, expression: sqlglot.expressions.ArrayAgg) -> str:
4624    def arrayagg_sql(self, expression: exp.ArrayAgg) -> str:
4625        array_agg = self.function_fallback_sql(expression)
4626
4627        # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls
4628        # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB)
4629        if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"):
4630            parent = expression.parent
4631            if isinstance(parent, exp.Filter):
4632                parent_cond = parent.expression.this
4633                parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_()))
4634            else:
4635                this = expression.this
4636                # Do not add the filter if the input is not a column (e.g. literal, struct etc)
4637                if this.find(exp.Column):
4638                    # DISTINCT is already present in the agg function, do not propagate it to FILTER as well
4639                    this_sql = (
4640                        self.expressions(this)
4641                        if isinstance(this, exp.Distinct)
4642                        else self.sql(expression, "this")
4643                    )
4644
4645                    array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)"
4646
4647        return array_agg
def apply_sql(self, expression: sqlglot.expressions.Apply) -> str:
4649    def apply_sql(self, expression: exp.Apply) -> str:
4650        this = self.sql(expression, "this")
4651        expr = self.sql(expression, "expression")
4652
4653        return f"{this} APPLY({expr})"
def grant_sql(self, expression: sqlglot.expressions.Grant) -> str:
4655    def grant_sql(self, expression: exp.Grant) -> str:
4656        privileges_sql = self.expressions(expression, key="privileges", flat=True)
4657
4658        kind = self.sql(expression, "kind")
4659        kind = f" {kind}" if kind else ""
4660
4661        securable = self.sql(expression, "securable")
4662        securable = f" {securable}" if securable else ""
4663
4664        principals = self.expressions(expression, key="principals", flat=True)
4665
4666        grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else ""
4667
4668        return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}"
def grantprivilege_sql(self, expression: sqlglot.expressions.GrantPrivilege):
4670    def grantprivilege_sql(self, expression: exp.GrantPrivilege):
4671        this = self.sql(expression, "this")
4672        columns = self.expressions(expression, flat=True)
4673        columns = f"({columns})" if columns else ""
4674
4675        return f"{this}{columns}"
def grantprincipal_sql(self, expression: sqlglot.expressions.GrantPrincipal):
4677    def grantprincipal_sql(self, expression: exp.GrantPrincipal):
4678        this = self.sql(expression, "this")
4679
4680        kind = self.sql(expression, "kind")
4681        kind = f"{kind} " if kind else ""
4682
4683        return f"{kind}{this}"
def columns_sql(self, expression: sqlglot.expressions.Columns):
4685    def columns_sql(self, expression: exp.Columns):
4686        func = self.function_fallback_sql(expression)
4687        if expression.args.get("unpack"):
4688            func = f"*{func}"
4689
4690        return func
def overlay_sql(self, expression: sqlglot.expressions.Overlay):
4692    def overlay_sql(self, expression: exp.Overlay):
4693        this = self.sql(expression, "this")
4694        expr = self.sql(expression, "expression")
4695        from_sql = self.sql(expression, "from")
4696        for_sql = self.sql(expression, "for")
4697        for_sql = f" FOR {for_sql}" if for_sql else ""
4698
4699        return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})"
@unsupported_args('format')
def todouble_sql(self, expression: sqlglot.expressions.ToDouble) -> str:
4701    @unsupported_args("format")
4702    def todouble_sql(self, expression: exp.ToDouble) -> str:
4703        return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
def string_sql(self, expression: sqlglot.expressions.String) -> str:
4705    def string_sql(self, expression: exp.String) -> str:
4706        this = expression.this
4707        zone = expression.args.get("zone")
4708
4709        if zone:
4710            # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>)
4711            # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC
4712            # set for source_tz to transpile the time conversion before the STRING cast
4713            this = exp.ConvertTimezone(
4714                source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this
4715            )
4716
4717        return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR))
def median_sql(self, expression: sqlglot.expressions.Median):
4719    def median_sql(self, expression: exp.Median):
4720        if not self.SUPPORTS_MEDIAN:
4721            return self.sql(
4722                exp.PercentileCont(this=expression.this, expression=exp.Literal.number(0.5))
4723            )
4724
4725        return self.function_fallback_sql(expression)
def overflowtruncatebehavior_sql(self, expression: sqlglot.expressions.OverflowTruncateBehavior) -> str:
4727    def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str:
4728        filler = self.sql(expression, "this")
4729        filler = f" {filler}" if filler else ""
4730        with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT"
4731        return f"TRUNCATE{filler} {with_count}"
def unixseconds_sql(self, expression: sqlglot.expressions.UnixSeconds) -> str:
4733    def unixseconds_sql(self, expression: exp.UnixSeconds) -> str:
4734        if self.SUPPORTS_UNIX_SECONDS:
4735            return self.function_fallback_sql(expression)
4736
4737        start_ts = exp.cast(
4738            exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ
4739        )
4740
4741        return self.sql(
4742            exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS"))
4743        )
def arraysize_sql(self, expression: sqlglot.expressions.ArraySize) -> str:
4745    def arraysize_sql(self, expression: exp.ArraySize) -> str:
4746        dim = expression.expression
4747
4748        # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension)
4749        if dim and self.ARRAY_SIZE_DIM_REQUIRED is None:
4750            if not (dim.is_int and dim.name == "1"):
4751                self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH")
4752            dim = None
4753
4754        # If dimension is required but not specified, default initialize it
4755        if self.ARRAY_SIZE_DIM_REQUIRED and not dim:
4756            dim = exp.Literal.number(1)
4757
4758        return self.func(self.ARRAY_SIZE_NAME, expression.this, dim)
def attach_sql(self, expression: sqlglot.expressions.Attach) -> str:
4760    def attach_sql(self, expression: exp.Attach) -> str:
4761        this = self.sql(expression, "this")
4762        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
4763        expressions = self.expressions(expression)
4764        expressions = f" ({expressions})" if expressions else ""
4765
4766        return f"ATTACH{exists_sql} {this}{expressions}"
def detach_sql(self, expression: sqlglot.expressions.Detach) -> str:
4768    def detach_sql(self, expression: exp.Detach) -> str:
4769        this = self.sql(expression, "this")
4770        exists_sql = " IF EXISTS" if expression.args.get("exists") else ""
4771
4772        return f"DETACH{exists_sql} {this}"
def attachoption_sql(self, expression: sqlglot.expressions.AttachOption) -> str:
4774    def attachoption_sql(self, expression: exp.AttachOption) -> str:
4775        this = self.sql(expression, "this")
4776        value = self.sql(expression, "expression")
4777        value = f" {value}" if value else ""
4778        return f"{this}{value}"
def featuresattime_sql(self, expression: sqlglot.expressions.FeaturesAtTime) -> str:
4780    def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str:
4781        this_sql = self.sql(expression, "this")
4782        if isinstance(expression.this, exp.Table):
4783            this_sql = f"TABLE {this_sql}"
4784
4785        return self.func(
4786            "FEATURES_AT_TIME",
4787            this_sql,
4788            expression.args.get("time"),
4789            expression.args.get("num_rows"),
4790            expression.args.get("ignore_feature_nulls"),
4791        )
def watermarkcolumnconstraint_sql(self, expression: sqlglot.expressions.WatermarkColumnConstraint) -> str:
4793    def watermarkcolumnconstraint_sql(self, expression: exp.WatermarkColumnConstraint) -> str:
4794        return (
4795            f"WATERMARK FOR {self.sql(expression, 'this')} AS {self.sql(expression, 'expression')}"
4796        )
def encodeproperty_sql(self, expression: sqlglot.expressions.EncodeProperty) -> str:
4798    def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str:
4799        encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE"
4800        encode = f"{encode} {self.sql(expression, 'this')}"
4801
4802        properties = expression.args.get("properties")
4803        if properties:
4804            encode = f"{encode} {self.properties(properties)}"
4805
4806        return encode
def includeproperty_sql(self, expression: sqlglot.expressions.IncludeProperty) -> str:
4808    def includeproperty_sql(self, expression: exp.IncludeProperty) -> str:
4809        this = self.sql(expression, "this")
4810        include = f"INCLUDE {this}"
4811
4812        column_def = self.sql(expression, "column_def")
4813        if column_def:
4814            include = f"{include} {column_def}"
4815
4816        alias = self.sql(expression, "alias")
4817        if alias:
4818            include = f"{include} AS {alias}"
4819
4820        return include
def xmlelement_sql(self, expression: sqlglot.expressions.XMLElement) -> str:
4822    def xmlelement_sql(self, expression: exp.XMLElement) -> str:
4823        name = f"NAME {self.sql(expression, 'this')}"
4824        return self.func("XMLELEMENT", name, *expression.expressions)
def xmlkeyvalueoption_sql(self, expression: sqlglot.expressions.XMLKeyValueOption) -> str:
4826    def xmlkeyvalueoption_sql(self, expression: exp.XMLKeyValueOption) -> str:
4827        this = self.sql(expression, "this")
4828        expr = self.sql(expression, "expression")
4829        expr = f"({expr})" if expr else ""
4830        return f"{this}{expr}"
def partitionbyrangeproperty_sql(self, expression: sqlglot.expressions.PartitionByRangeProperty) -> str:
4832    def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str:
4833        partitions = self.expressions(expression, "partition_expressions")
4834        create = self.expressions(expression, "create_expressions")
4835        return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}"
def partitionbyrangepropertydynamic_sql( self, expression: sqlglot.expressions.PartitionByRangePropertyDynamic) -> str:
4837    def partitionbyrangepropertydynamic_sql(
4838        self, expression: exp.PartitionByRangePropertyDynamic
4839    ) -> str:
4840        start = self.sql(expression, "start")
4841        end = self.sql(expression, "end")
4842
4843        every = expression.args["every"]
4844        if isinstance(every, exp.Interval) and every.this.is_string:
4845            every.this.replace(exp.Literal.number(every.name))
4846
4847        return f"START {self.wrap(start)} END {self.wrap(end)} EVERY {self.wrap(self.sql(every))}"
def unpivotcolumns_sql(self, expression: sqlglot.expressions.UnpivotColumns) -> str:
4849    def unpivotcolumns_sql(self, expression: exp.UnpivotColumns) -> str:
4850        name = self.sql(expression, "this")
4851        values = self.expressions(expression, flat=True)
4852
4853        return f"NAME {name} VALUE {values}"
def analyzesample_sql(self, expression: sqlglot.expressions.AnalyzeSample) -> str:
4855    def analyzesample_sql(self, expression: exp.AnalyzeSample) -> str:
4856        kind = self.sql(expression, "kind")
4857        sample = self.sql(expression, "sample")
4858        return f"SAMPLE {sample} {kind}"
def analyzestatistics_sql(self, expression: sqlglot.expressions.AnalyzeStatistics) -> str:
4860    def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str:
4861        kind = self.sql(expression, "kind")
4862        option = self.sql(expression, "option")
4863        option = f" {option}" if option else ""
4864        this = self.sql(expression, "this")
4865        this = f" {this}" if this else ""
4866        columns = self.expressions(expression)
4867        columns = f" {columns}" if columns else ""
4868        return f"{kind}{option} STATISTICS{this}{columns}"
def analyzehistogram_sql(self, expression: sqlglot.expressions.AnalyzeHistogram) -> str:
4870    def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str:
4871        this = self.sql(expression, "this")
4872        columns = self.expressions(expression)
4873        inner_expression = self.sql(expression, "expression")
4874        inner_expression = f" {inner_expression}" if inner_expression else ""
4875        update_options = self.sql(expression, "update_options")
4876        update_options = f" {update_options} UPDATE" if update_options else ""
4877        return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}"
def analyzedelete_sql(self, expression: sqlglot.expressions.AnalyzeDelete) -> str:
4879    def analyzedelete_sql(self, expression: exp.AnalyzeDelete) -> str:
4880        kind = self.sql(expression, "kind")
4881        kind = f" {kind}" if kind else ""
4882        return f"DELETE{kind} STATISTICS"
def analyzelistchainedrows_sql(self, expression: sqlglot.expressions.AnalyzeListChainedRows) -> str:
4884    def analyzelistchainedrows_sql(self, expression: exp.AnalyzeListChainedRows) -> str:
4885        inner_expression = self.sql(expression, "expression")
4886        return f"LIST CHAINED ROWS{inner_expression}"
def analyzevalidate_sql(self, expression: sqlglot.expressions.AnalyzeValidate) -> str:
4888    def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str:
4889        kind = self.sql(expression, "kind")
4890        this = self.sql(expression, "this")
4891        this = f" {this}" if this else ""
4892        inner_expression = self.sql(expression, "expression")
4893        return f"VALIDATE {kind}{this}{inner_expression}"
def analyze_sql(self, expression: sqlglot.expressions.Analyze) -> str:
4895    def analyze_sql(self, expression: exp.Analyze) -> str:
4896        options = self.expressions(expression, key="options", sep=" ")
4897        options = f" {options}" if options else ""
4898        kind = self.sql(expression, "kind")
4899        kind = f" {kind}" if kind else ""
4900        this = self.sql(expression, "this")
4901        this = f" {this}" if this else ""
4902        mode = self.sql(expression, "mode")
4903        mode = f" {mode}" if mode else ""
4904        properties = self.sql(expression, "properties")
4905        properties = f" {properties}" if properties else ""
4906        partition = self.sql(expression, "partition")
4907        partition = f" {partition}" if partition else ""
4908        inner_expression = self.sql(expression, "expression")
4909        inner_expression = f" {inner_expression}" if inner_expression else ""
4910        return f"ANALYZE{options}{kind}{this}{partition}{mode}{inner_expression}{properties}"
def xmltable_sql(self, expression: sqlglot.expressions.XMLTable) -> str:
4912    def xmltable_sql(self, expression: exp.XMLTable) -> str:
4913        this = self.sql(expression, "this")
4914        namespaces = self.expressions(expression, key="namespaces")
4915        namespaces = f"XMLNAMESPACES({namespaces}), " if namespaces else ""
4916        passing = self.expressions(expression, key="passing")
4917        passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else ""
4918        columns = self.expressions(expression, key="columns")
4919        columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else ""
4920        by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else ""
4921        return f"XMLTABLE({self.sep('')}{self.indent(namespaces + this + passing + by_ref + columns)}{self.seg(')', sep='')}"
def xmlnamespace_sql(self, expression: sqlglot.expressions.XMLNamespace) -> str:
4923    def xmlnamespace_sql(self, expression: exp.XMLNamespace) -> str:
4924        this = self.sql(expression, "this")
4925        return this if isinstance(expression.this, exp.Alias) else f"DEFAULT {this}"
def export_sql(self, expression: sqlglot.expressions.Export) -> str:
4927    def export_sql(self, expression: exp.Export) -> str:
4928        this = self.sql(expression, "this")
4929        connection = self.sql(expression, "connection")
4930        connection = f"WITH CONNECTION {connection} " if connection else ""
4931        options = self.sql(expression, "options")
4932        return f"EXPORT DATA {connection}{options} AS {this}"
def declare_sql(self, expression: sqlglot.expressions.Declare) -> str:
4934    def declare_sql(self, expression: exp.Declare) -> str:
4935        return f"DECLARE {self.expressions(expression, flat=True)}"
def declareitem_sql(self, expression: sqlglot.expressions.DeclareItem) -> str:
4937    def declareitem_sql(self, expression: exp.DeclareItem) -> str:
4938        variable = self.sql(expression, "this")
4939        default = self.sql(expression, "default")
4940        default = f" = {default}" if default else ""
4941
4942        kind = self.sql(expression, "kind")
4943        if isinstance(expression.args.get("kind"), exp.Schema):
4944            kind = f"TABLE {kind}"
4945
4946        return f"{variable} AS {kind}{default}"
def recursivewithsearch_sql(self, expression: sqlglot.expressions.RecursiveWithSearch) -> str:
4948    def recursivewithsearch_sql(self, expression: exp.RecursiveWithSearch) -> str:
4949        kind = self.sql(expression, "kind")
4950        this = self.sql(expression, "this")
4951        set = self.sql(expression, "expression")
4952        using = self.sql(expression, "using")
4953        using = f" USING {using}" if using else ""
4954
4955        kind_sql = kind if kind == "CYCLE" else f"SEARCH {kind} FIRST BY"
4956
4957        return f"{kind_sql} {this} SET {set}{using}"
def parameterizedagg_sql(self, expression: sqlglot.expressions.ParameterizedAgg) -> str:
4959    def parameterizedagg_sql(self, expression: exp.ParameterizedAgg) -> str:
4960        params = self.expressions(expression, key="params", flat=True)
4961        return self.func(expression.name, *expression.expressions) + f"({params})"
def anonymousaggfunc_sql(self, expression: sqlglot.expressions.AnonymousAggFunc) -> str:
4963    def anonymousaggfunc_sql(self, expression: exp.AnonymousAggFunc) -> str:
4964        return self.func(expression.name, *expression.expressions)
def combinedaggfunc_sql(self, expression: sqlglot.expressions.CombinedAggFunc) -> str:
4966    def combinedaggfunc_sql(self, expression: exp.CombinedAggFunc) -> str:
4967        return self.anonymousaggfunc_sql(expression)
def combinedparameterizedagg_sql(self, expression: sqlglot.expressions.CombinedParameterizedAgg) -> str:
4969    def combinedparameterizedagg_sql(self, expression: exp.CombinedParameterizedAgg) -> str:
4970        return self.parameterizedagg_sql(expression)
def show_sql(self, expression: sqlglot.expressions.Show) -> str:
4972    def show_sql(self, expression: exp.Show) -> str:
4973        self.unsupported("Unsupported SHOW statement")
4974        return ""
def get_put_sql( self, expression: sqlglot.expressions.Put | sqlglot.expressions.Get) -> str:
4976    def get_put_sql(self, expression: exp.Put | exp.Get) -> str:
4977        # Snowflake GET/PUT statements:
4978        #   PUT <file> <internalStage> <properties>
4979        #   GET <internalStage> <file> <properties>
4980        props = expression.args.get("properties")
4981        props_sql = self.properties(props, prefix=" ", sep=" ", wrapped=False) if props else ""
4982        this = self.sql(expression, "this")
4983        target = self.sql(expression, "target")
4984
4985        if isinstance(expression, exp.Put):
4986            return f"PUT {this} {target}{props_sql}"
4987        else:
4988            return f"GET {target} {this}{props_sql}"
def translatecharacters_sql(self, expression: sqlglot.expressions.TranslateCharacters):
4990    def translatecharacters_sql(self, expression: exp.TranslateCharacters):
4991        this = self.sql(expression, "this")
4992        expr = self.sql(expression, "expression")
4993        with_error = " WITH ERROR" if expression.args.get("with_error") else ""
4994        return f"TRANSLATE({this} USING {expr}{with_error})"