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

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.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None)
665    def __init__(
666        self,
667        pretty: t.Optional[bool] = None,
668        identify: str | bool = False,
669        normalize: bool = False,
670        pad: int = 2,
671        indent: int = 2,
672        normalize_functions: t.Optional[str | bool] = None,
673        unsupported_level: ErrorLevel = ErrorLevel.WARN,
674        max_unsupported: int = 3,
675        leading_comma: bool = False,
676        max_text_width: int = 80,
677        comments: bool = True,
678        dialect: DialectType = None,
679    ):
680        import sqlglot
681        from sqlglot.dialects import Dialect
682
683        self.pretty = pretty if pretty is not None else sqlglot.pretty
684        self.identify = identify
685        self.normalize = normalize
686        self.pad = pad
687        self._indent = indent
688        self.unsupported_level = unsupported_level
689        self.max_unsupported = max_unsupported
690        self.leading_comma = leading_comma
691        self.max_text_width = max_text_width
692        self.comments = comments
693        self.dialect = Dialect.get_or_raise(dialect)
694
695        # This is both a Dialect property and a Generator argument, so we prioritize the latter
696        self.normalize_functions = (
697            self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions
698        )
699
700        self.unsupported_messages: t.List[str] = []
701        self._escaped_quote_end: str = (
702            self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END
703        )
704        self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2
705
706        self._next_name = name_sequence("_t")
707
708        self._identifier_start = self.dialect.IDENTIFIER_START
709        self._identifier_end = self.dialect.IDENTIFIER_END
710
711        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.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.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.CopyGrantsProperty'>: <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.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.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.PivotAny'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ProjectionPolicyColumnConstraint'>: <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.TemporaryProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Tags'>: <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.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>>}
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
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
PARSE_JSON_NAME: Optional[str] = 'PARSE_JSON'
ARRAY_SIZE_NAME: str = 'ARRAY_LENGTH'
ARRAY_SIZE_DIM_REQUIRED: Optional[bool] = None
TYPE_MAPPING = {<Type.NCHAR: 'NCHAR'>: 'CHAR', <Type.NVARCHAR: 'NVARCHAR'>: 'VARCHAR', <Type.MEDIUMTEXT: 'MEDIUMTEXT'>: 'TEXT', <Type.LONGTEXT: 'LONGTEXT'>: 'TEXT', <Type.TINYTEXT: 'TINYTEXT'>: 'TEXT', <Type.MEDIUMBLOB: 'MEDIUMBLOB'>: 'BLOB', <Type.LONGBLOB: 'LONGBLOB'>: 'BLOB', <Type.TINYBLOB: 'TINYBLOB'>: 'BLOB', <Type.INET: 'INET'>: 'INET', <Type.ROWVERSION: 'ROWVERSION'>: 'VARBINARY'}
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.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.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.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'>}
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.NVARCHAR: 'NVARCHAR'>, <Type.CHAR: 'CHAR'>, <Type.VARCHAR: 'VARCHAR'>, <Type.NCHAR: 'NCHAR'>}
EXPRESSIONS_WITHOUT_NESTED_CTES: Set[Type[sqlglot.expressions.Expression]] = set()
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:
713    def generate(self, expression: exp.Expression, copy: bool = True) -> str:
714        """
715        Generates the SQL string corresponding to the given syntax tree.
716
717        Args:
718            expression: The syntax tree.
719            copy: Whether to copy the expression. The generator performs mutations so
720                it is safer to copy.
721
722        Returns:
723            The SQL string corresponding to `expression`.
724        """
725        if copy:
726            expression = expression.copy()
727
728        expression = self.preprocess(expression)
729
730        self.unsupported_messages = []
731        sql = self.sql(expression).strip()
732
733        if self.pretty:
734            sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n")
735
736        if self.unsupported_level == ErrorLevel.IGNORE:
737            return sql
738
739        if self.unsupported_level == ErrorLevel.WARN:
740            for msg in self.unsupported_messages:
741                logger.warning(msg)
742        elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages:
743            raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported))
744
745        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:
747    def preprocess(self, expression: exp.Expression) -> exp.Expression:
748        """Apply generic preprocessing transformations to a given expression."""
749        expression = self._move_ctes_to_top_level(expression)
750
751        if self.ENSURE_BOOLS:
752            from sqlglot.transforms import ensure_bools
753
754            expression = ensure_bools(expression)
755
756        return expression

Apply generic preprocessing transformations to a given expression.

def unsupported(self, message: str) -> None:
769    def unsupported(self, message: str) -> None:
770        if self.unsupported_level == ErrorLevel.IMMEDIATE:
771            raise UnsupportedError(message)
772        self.unsupported_messages.append(message)
def sep(self, sep: str = ' ') -> str:
774    def sep(self, sep: str = " ") -> str:
775        return f"{sep.strip()}\n" if self.pretty else sep
def seg(self, sql: str, sep: str = ' ') -> str:
777    def seg(self, sql: str, sep: str = " ") -> str:
778        return f"{self.sep(sep)}{sql}"
def pad_comment(self, comment: str) -> str:
780    def pad_comment(self, comment: str) -> str:
781        comment = " " + comment if comment[0].strip() else comment
782        comment = comment + " " if comment[-1].strip() else comment
783        return comment
def maybe_comment( self, sql: str, expression: Optional[sqlglot.expressions.Expression] = None, comments: Optional[List[str]] = None, separated: bool = False) -> str:
785    def maybe_comment(
786        self,
787        sql: str,
788        expression: t.Optional[exp.Expression] = None,
789        comments: t.Optional[t.List[str]] = None,
790        separated: bool = False,
791    ) -> str:
792        comments = (
793            ((expression and expression.comments) if comments is None else comments)  # type: ignore
794            if self.comments
795            else None
796        )
797
798        if not comments or isinstance(expression, self.EXCLUDE_COMMENTS):
799            return sql
800
801        comments_sql = " ".join(
802            f"/*{self.pad_comment(comment)}*/" for comment in comments if comment
803        )
804
805        if not comments_sql:
806            return sql
807
808        comments_sql = self._replace_line_breaks(comments_sql)
809
810        if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS):
811            return (
812                f"{self.sep()}{comments_sql}{sql}"
813                if not sql or sql[0].isspace()
814                else f"{comments_sql}{self.sep()}{sql}"
815            )
816
817        return f"{sql} {comments_sql}"
def wrap(self, expression: sqlglot.expressions.Expression | str) -> str:
819    def wrap(self, expression: exp.Expression | str) -> str:
820        this_sql = (
821            self.sql(expression)
822            if isinstance(expression, exp.UNWRAPPED_QUERIES)
823            else self.sql(expression, "this")
824        )
825        if not this_sql:
826            return "()"
827
828        this_sql = self.indent(this_sql, level=1, pad=0)
829        return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"
def no_identify(self, func: Callable[..., str], *args, **kwargs) -> str:
831    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
832        original = self.identify
833        self.identify = False
834        result = func(*args, **kwargs)
835        self.identify = original
836        return result
def normalize_func(self, name: str) -> str:
838    def normalize_func(self, name: str) -> str:
839        if self.normalize_functions == "upper" or self.normalize_functions is True:
840            return name.upper()
841        if self.normalize_functions == "lower":
842            return name.lower()
843        return name
def indent( self, sql: str, level: int = 0, pad: Optional[int] = None, skip_first: bool = False, skip_last: bool = False) -> str:
845    def indent(
846        self,
847        sql: str,
848        level: int = 0,
849        pad: t.Optional[int] = None,
850        skip_first: bool = False,
851        skip_last: bool = False,
852    ) -> str:
853        if not self.pretty or not sql:
854            return sql
855
856        pad = self.pad if pad is None else pad
857        lines = sql.split("\n")
858
859        return "\n".join(
860            (
861                line
862                if (skip_first and i == 0) or (skip_last and i == len(lines) - 1)
863                else f"{' ' * (level * self._indent + pad)}{line}"
864            )
865            for i, line in enumerate(lines)
866        )
def sql( self, expression: Union[str, sqlglot.expressions.Expression, NoneType], key: Optional[str] = None, comment: bool = True) -> str:
868    def sql(
869        self,
870        expression: t.Optional[str | exp.Expression],
871        key: t.Optional[str] = None,
872        comment: bool = True,
873    ) -> str:
874        if not expression:
875            return ""
876
877        if isinstance(expression, str):
878            return expression
879
880        if key:
881            value = expression.args.get(key)
882            if value:
883                return self.sql(value)
884            return ""
885
886        transform = self.TRANSFORMS.get(expression.__class__)
887
888        if callable(transform):
889            sql = transform(self, expression)
890        elif isinstance(expression, exp.Expression):
891            exp_handler_name = f"{expression.key}_sql"
892
893            if hasattr(self, exp_handler_name):
894                sql = getattr(self, exp_handler_name)(expression)
895            elif isinstance(expression, exp.Func):
896                sql = self.function_fallback_sql(expression)
897            elif isinstance(expression, exp.Property):
898                sql = self.property_sql(expression)
899            else:
900                raise ValueError(f"Unsupported expression type {expression.__class__.__name__}")
901        else:
902            raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}")
903
904        return self.maybe_comment(sql, expression) if self.comments and comment else sql
def uncache_sql(self, expression: sqlglot.expressions.Uncache) -> str:
906    def uncache_sql(self, expression: exp.Uncache) -> str:
907        table = self.sql(expression, "this")
908        exists_sql = " IF EXISTS" if expression.args.get("exists") else ""
909        return f"UNCACHE TABLE{exists_sql} {table}"
def cache_sql(self, expression: sqlglot.expressions.Cache) -> str:
911    def cache_sql(self, expression: exp.Cache) -> str:
912        lazy = " LAZY" if expression.args.get("lazy") else ""
913        table = self.sql(expression, "this")
914        options = expression.args.get("options")
915        options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else ""
916        sql = self.sql(expression, "expression")
917        sql = f" AS{self.sep()}{sql}" if sql else ""
918        sql = f"CACHE{lazy} TABLE {table}{options}{sql}"
919        return self.prepend_ctes(expression, sql)
def characterset_sql(self, expression: sqlglot.expressions.CharacterSet) -> str:
921    def characterset_sql(self, expression: exp.CharacterSet) -> str:
922        if isinstance(expression.parent, exp.Cast):
923            return f"CHAR CHARACTER SET {self.sql(expression, 'this')}"
924        default = "DEFAULT " if expression.args.get("default") else ""
925        return f"{default}CHARACTER SET={self.sql(expression, 'this')}"
def column_parts(self, expression: sqlglot.expressions.Column) -> str:
927    def column_parts(self, expression: exp.Column) -> str:
928        return ".".join(
929            self.sql(part)
930            for part in (
931                expression.args.get("catalog"),
932                expression.args.get("db"),
933                expression.args.get("table"),
934                expression.args.get("this"),
935            )
936            if part
937        )
def column_sql(self, expression: sqlglot.expressions.Column) -> str:
939    def column_sql(self, expression: exp.Column) -> str:
940        join_mark = " (+)" if expression.args.get("join_mark") else ""
941
942        if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS:
943            join_mark = ""
944            self.unsupported("Outer join syntax using the (+) operator is not supported.")
945
946        return f"{self.column_parts(expression)}{join_mark}"
def columnposition_sql(self, expression: sqlglot.expressions.ColumnPosition) -> str:
948    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
949        this = self.sql(expression, "this")
950        this = f" {this}" if this else ""
951        position = self.sql(expression, "position")
952        return f"{position}{this}"
def columndef_sql(self, expression: sqlglot.expressions.ColumnDef, sep: str = ' ') -> str:
954    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
955        column = self.sql(expression, "this")
956        kind = self.sql(expression, "kind")
957        constraints = self.expressions(expression, key="constraints", sep=" ", flat=True)
958        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
959        kind = f"{sep}{kind}" if kind else ""
960        constraints = f" {constraints}" if constraints else ""
961        position = self.sql(expression, "position")
962        position = f" {position}" if position else ""
963
964        if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE:
965            kind = ""
966
967        return f"{exists}{column}{kind}{constraints}{position}"
def columnconstraint_sql(self, expression: sqlglot.expressions.ColumnConstraint) -> str:
969    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
970        this = self.sql(expression, "this")
971        kind_sql = self.sql(expression, "kind").strip()
972        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql
def computedcolumnconstraint_sql(self, expression: sqlglot.expressions.ComputedColumnConstraint) -> str:
974    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
975        this = self.sql(expression, "this")
976        if expression.args.get("not_null"):
977            persisted = " PERSISTED NOT NULL"
978        elif expression.args.get("persisted"):
979            persisted = " PERSISTED"
980        else:
981            persisted = ""
982        return f"AS {this}{persisted}"
def autoincrementcolumnconstraint_sql(self, _) -> str:
984    def autoincrementcolumnconstraint_sql(self, _) -> str:
985        return self.token_sql(TokenType.AUTO_INCREMENT)
def compresscolumnconstraint_sql(self, expression: sqlglot.expressions.CompressColumnConstraint) -> str:
987    def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str:
988        if isinstance(expression.this, list):
989            this = self.wrap(self.expressions(expression, key="this", flat=True))
990        else:
991            this = self.sql(expression, "this")
992
993        return f"COMPRESS {this}"
def generatedasidentitycolumnconstraint_sql( self, expression: sqlglot.expressions.GeneratedAsIdentityColumnConstraint) -> str:
 995    def generatedasidentitycolumnconstraint_sql(
 996        self, expression: exp.GeneratedAsIdentityColumnConstraint
 997    ) -> str:
 998        this = ""
 999        if expression.this is not None:
1000            on_null = " ON NULL" if expression.args.get("on_null") else ""
1001            this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}"
1002
1003        start = expression.args.get("start")
1004        start = f"START WITH {start}" if start else ""
1005        increment = expression.args.get("increment")
1006        increment = f" INCREMENT BY {increment}" if increment else ""
1007        minvalue = expression.args.get("minvalue")
1008        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
1009        maxvalue = expression.args.get("maxvalue")
1010        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
1011        cycle = expression.args.get("cycle")
1012        cycle_sql = ""
1013
1014        if cycle is not None:
1015            cycle_sql = f"{' NO' if not cycle else ''} CYCLE"
1016            cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql
1017
1018        sequence_opts = ""
1019        if start or increment or cycle_sql:
1020            sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}"
1021            sequence_opts = f" ({sequence_opts.strip()})"
1022
1023        expr = self.sql(expression, "expression")
1024        expr = f"({expr})" if expr else "IDENTITY"
1025
1026        return f"GENERATED{this} AS {expr}{sequence_opts}"
def generatedasrowcolumnconstraint_sql( self, expression: sqlglot.expressions.GeneratedAsRowColumnConstraint) -> str:
1028    def generatedasrowcolumnconstraint_sql(
1029        self, expression: exp.GeneratedAsRowColumnConstraint
1030    ) -> str:
1031        start = "START" if expression.args.get("start") else "END"
1032        hidden = " HIDDEN" if expression.args.get("hidden") else ""
1033        return f"GENERATED ALWAYS AS ROW {start}{hidden}"
def periodforsystemtimeconstraint_sql( self, expression: sqlglot.expressions.PeriodForSystemTimeConstraint) -> str:
1035    def periodforsystemtimeconstraint_sql(
1036        self, expression: exp.PeriodForSystemTimeConstraint
1037    ) -> str:
1038        return f"PERIOD FOR SYSTEM_TIME ({self.sql(expression, 'this')}, {self.sql(expression, 'expression')})"
def notnullcolumnconstraint_sql(self, expression: sqlglot.expressions.NotNullColumnConstraint) -> str:
1040    def notnullcolumnconstraint_sql(self, expression: exp.NotNullColumnConstraint) -> str:
1041        return f"{'' if expression.args.get('allow_null') else 'NOT '}NULL"
def transformcolumnconstraint_sql(self, expression: sqlglot.expressions.TransformColumnConstraint) -> str:
1043    def transformcolumnconstraint_sql(self, expression: exp.TransformColumnConstraint) -> str:
1044        return f"AS {self.sql(expression, 'this')}"
def primarykeycolumnconstraint_sql(self, expression: sqlglot.expressions.PrimaryKeyColumnConstraint) -> str:
1046    def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str:
1047        desc = expression.args.get("desc")
1048        if desc is not None:
1049            return f"PRIMARY KEY{' DESC' if desc else ' ASC'}"
1050        return "PRIMARY KEY"
def uniquecolumnconstraint_sql(self, expression: sqlglot.expressions.UniqueColumnConstraint) -> str:
1052    def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str:
1053        this = self.sql(expression, "this")
1054        this = f" {this}" if this else ""
1055        index_type = expression.args.get("index_type")
1056        index_type = f" USING {index_type}" if index_type else ""
1057        on_conflict = self.sql(expression, "on_conflict")
1058        on_conflict = f" {on_conflict}" if on_conflict else ""
1059        nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else ""
1060        return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}"
def createable_sql( self, expression: sqlglot.expressions.Create, locations: DefaultDict) -> str:
1062    def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
1063        return self.sql(expression, "this")
def create_sql(self, expression: sqlglot.expressions.Create) -> str:
1065    def create_sql(self, expression: exp.Create) -> str:
1066        kind = self.sql(expression, "kind")
1067        kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind
1068        properties = expression.args.get("properties")
1069        properties_locs = self.locate_properties(properties) if properties else defaultdict()
1070
1071        this = self.createable_sql(expression, properties_locs)
1072
1073        properties_sql = ""
1074        if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get(
1075            exp.Properties.Location.POST_WITH
1076        ):
1077            properties_sql = self.sql(
1078                exp.Properties(
1079                    expressions=[
1080                        *properties_locs[exp.Properties.Location.POST_SCHEMA],
1081                        *properties_locs[exp.Properties.Location.POST_WITH],
1082                    ]
1083                )
1084            )
1085
1086            if properties_locs.get(exp.Properties.Location.POST_SCHEMA):
1087                properties_sql = self.sep() + properties_sql
1088            elif not self.pretty:
1089                # Standalone POST_WITH properties need a leading whitespace in non-pretty mode
1090                properties_sql = f" {properties_sql}"
1091
1092        begin = " BEGIN" if expression.args.get("begin") else ""
1093        end = " END" if expression.args.get("end") else ""
1094
1095        expression_sql = self.sql(expression, "expression")
1096        if expression_sql:
1097            expression_sql = f"{begin}{self.sep()}{expression_sql}{end}"
1098
1099            if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return):
1100                postalias_props_sql = ""
1101                if properties_locs.get(exp.Properties.Location.POST_ALIAS):
1102                    postalias_props_sql = self.properties(
1103                        exp.Properties(
1104                            expressions=properties_locs[exp.Properties.Location.POST_ALIAS]
1105                        ),
1106                        wrapped=False,
1107                    )
1108                postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else ""
1109                expression_sql = f" AS{postalias_props_sql}{expression_sql}"
1110
1111        postindex_props_sql = ""
1112        if properties_locs.get(exp.Properties.Location.POST_INDEX):
1113            postindex_props_sql = self.properties(
1114                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]),
1115                wrapped=False,
1116                prefix=" ",
1117            )
1118
1119        indexes = self.expressions(expression, key="indexes", indent=False, sep=" ")
1120        indexes = f" {indexes}" if indexes else ""
1121        index_sql = indexes + postindex_props_sql
1122
1123        replace = " OR REPLACE" if expression.args.get("replace") else ""
1124        refresh = " OR REFRESH" if expression.args.get("refresh") else ""
1125        unique = " UNIQUE" if expression.args.get("unique") else ""
1126
1127        clustered = expression.args.get("clustered")
1128        if clustered is None:
1129            clustered_sql = ""
1130        elif clustered:
1131            clustered_sql = " CLUSTERED COLUMNSTORE"
1132        else:
1133            clustered_sql = " NONCLUSTERED COLUMNSTORE"
1134
1135        postcreate_props_sql = ""
1136        if properties_locs.get(exp.Properties.Location.POST_CREATE):
1137            postcreate_props_sql = self.properties(
1138                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]),
1139                sep=" ",
1140                prefix=" ",
1141                wrapped=False,
1142            )
1143
1144        modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql))
1145
1146        postexpression_props_sql = ""
1147        if properties_locs.get(exp.Properties.Location.POST_EXPRESSION):
1148            postexpression_props_sql = self.properties(
1149                exp.Properties(
1150                    expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION]
1151                ),
1152                sep=" ",
1153                prefix=" ",
1154                wrapped=False,
1155            )
1156
1157        concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else ""
1158        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
1159        no_schema_binding = (
1160            " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else ""
1161        )
1162
1163        clone = self.sql(expression, "clone")
1164        clone = f" {clone}" if clone else ""
1165
1166        if kind in self.EXPRESSION_PRECEDES_PROPERTIES_CREATABLES:
1167            properties_expression = f"{expression_sql}{properties_sql}"
1168        else:
1169            properties_expression = f"{properties_sql}{expression_sql}"
1170
1171        expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_expression}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}"
1172        return self.prepend_ctes(expression, expression_sql)
def sequenceproperties_sql(self, expression: sqlglot.expressions.SequenceProperties) -> str:
1174    def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str:
1175        start = self.sql(expression, "start")
1176        start = f"START WITH {start}" if start else ""
1177        increment = self.sql(expression, "increment")
1178        increment = f" INCREMENT BY {increment}" if increment else ""
1179        minvalue = self.sql(expression, "minvalue")
1180        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
1181        maxvalue = self.sql(expression, "maxvalue")
1182        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
1183        owned = self.sql(expression, "owned")
1184        owned = f" OWNED BY {owned}" if owned else ""
1185
1186        cache = expression.args.get("cache")
1187        if cache is None:
1188            cache_str = ""
1189        elif cache is True:
1190            cache_str = " CACHE"
1191        else:
1192            cache_str = f" CACHE {cache}"
1193
1194        options = self.expressions(expression, key="options", flat=True, sep=" ")
1195        options = f" {options}" if options else ""
1196
1197        return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip()
def clone_sql(self, expression: sqlglot.expressions.Clone) -> str:
1199    def clone_sql(self, expression: exp.Clone) -> str:
1200        this = self.sql(expression, "this")
1201        shallow = "SHALLOW " if expression.args.get("shallow") else ""
1202        keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE"
1203        return f"{shallow}{keyword} {this}"
def describe_sql(self, expression: sqlglot.expressions.Describe) -> str:
1205    def describe_sql(self, expression: exp.Describe) -> str:
1206        style = expression.args.get("style")
1207        style = f" {style}" if style else ""
1208        partition = self.sql(expression, "partition")
1209        partition = f" {partition}" if partition else ""
1210        format = self.sql(expression, "format")
1211        format = f" {format}" if format else ""
1212
1213        return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}"
def heredoc_sql(self, expression: sqlglot.expressions.Heredoc) -> str:
1215    def heredoc_sql(self, expression: exp.Heredoc) -> str:
1216        tag = self.sql(expression, "tag")
1217        return f"${tag}${self.sql(expression, 'this')}${tag}$"
def prepend_ctes(self, expression: sqlglot.expressions.Expression, sql: str) -> str:
1219    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
1220        with_ = self.sql(expression, "with")
1221        if with_:
1222            sql = f"{with_}{self.sep()}{sql}"
1223        return sql
def with_sql(self, expression: sqlglot.expressions.With) -> str:
1225    def with_sql(self, expression: exp.With) -> str:
1226        sql = self.expressions(expression, flat=True)
1227        recursive = (
1228            "RECURSIVE "
1229            if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive")
1230            else ""
1231        )
1232
1233        return f"WITH {recursive}{sql}"
def cte_sql(self, expression: sqlglot.expressions.CTE) -> str:
1235    def cte_sql(self, expression: exp.CTE) -> str:
1236        alias = expression.args.get("alias")
1237        if alias:
1238            alias.add_comments(expression.pop_comments())
1239
1240        alias_sql = self.sql(expression, "alias")
1241
1242        materialized = expression.args.get("materialized")
1243        if materialized is False:
1244            materialized = "NOT MATERIALIZED "
1245        elif materialized:
1246            materialized = "MATERIALIZED "
1247
1248        return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}"
def tablealias_sql(self, expression: sqlglot.expressions.TableAlias) -> str:
1250    def tablealias_sql(self, expression: exp.TableAlias) -> str:
1251        alias = self.sql(expression, "this")
1252        columns = self.expressions(expression, key="columns", flat=True)
1253        columns = f"({columns})" if columns else ""
1254
1255        if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS:
1256            columns = ""
1257            self.unsupported("Named columns are not supported in table alias.")
1258
1259        if not alias and not self.dialect.UNNEST_COLUMN_ONLY:
1260            alias = self._next_name()
1261
1262        return f"{alias}{columns}"
def bitstring_sql(self, expression: sqlglot.expressions.BitString) -> str:
1264    def bitstring_sql(self, expression: exp.BitString) -> str:
1265        this = self.sql(expression, "this")
1266        if self.dialect.BIT_START:
1267            return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}"
1268        return f"{int(this, 2)}"
def hexstring_sql(self, expression: sqlglot.expressions.HexString) -> str:
1270    def hexstring_sql(self, expression: exp.HexString) -> str:
1271        this = self.sql(expression, "this")
1272        if self.dialect.HEX_START:
1273            return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"
1274        return f"{int(this, 16)}"
def bytestring_sql(self, expression: sqlglot.expressions.ByteString) -> str:
1276    def bytestring_sql(self, expression: exp.ByteString) -> str:
1277        this = self.sql(expression, "this")
1278        if self.dialect.BYTE_START:
1279            return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}"
1280        return this
def unicodestring_sql(self, expression: sqlglot.expressions.UnicodeString) -> str:
1282    def unicodestring_sql(self, expression: exp.UnicodeString) -> str:
1283        this = self.sql(expression, "this")
1284        escape = expression.args.get("escape")
1285
1286        if self.dialect.UNICODE_START:
1287            escape_substitute = r"\\\1"
1288            left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END
1289        else:
1290            escape_substitute = r"\\u\1"
1291            left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END
1292
1293        if escape:
1294            escape_pattern = re.compile(rf"{escape.name}(\d+)")
1295            escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else ""
1296        else:
1297            escape_pattern = ESCAPED_UNICODE_RE
1298            escape_sql = ""
1299
1300        if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE):
1301            this = escape_pattern.sub(escape_substitute, this)
1302
1303        return f"{left_quote}{this}{right_quote}{escape_sql}"
def rawstring_sql(self, expression: sqlglot.expressions.RawString) -> str:
1305    def rawstring_sql(self, expression: exp.RawString) -> str:
1306        string = self.escape_str(expression.this.replace("\\", "\\\\"), escape_backslash=False)
1307        return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}"
def datatypeparam_sql(self, expression: sqlglot.expressions.DataTypeParam) -> str:
1309    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
1310        this = self.sql(expression, "this")
1311        specifier = self.sql(expression, "expression")
1312        specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else ""
1313        return f"{this}{specifier}"
def datatype_sql(self, expression: sqlglot.expressions.DataType) -> str:
1315    def datatype_sql(self, expression: exp.DataType) -> str:
1316        nested = ""
1317        values = ""
1318        interior = self.expressions(expression, flat=True)
1319
1320        type_value = expression.this
1321        if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"):
1322            type_sql = self.sql(expression, "kind")
1323        else:
1324            type_sql = (
1325                self.TYPE_MAPPING.get(type_value, type_value.value)
1326                if isinstance(type_value, exp.DataType.Type)
1327                else type_value
1328            )
1329
1330        if interior:
1331            if expression.args.get("nested"):
1332                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
1333                if expression.args.get("values") is not None:
1334                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
1335                    values = self.expressions(expression, key="values", flat=True)
1336                    values = f"{delimiters[0]}{values}{delimiters[1]}"
1337            elif type_value == exp.DataType.Type.INTERVAL:
1338                nested = f" {interior}"
1339            else:
1340                nested = f"({interior})"
1341
1342        type_sql = f"{type_sql}{nested}{values}"
1343        if self.TZ_TO_WITH_TIME_ZONE and type_value in (
1344            exp.DataType.Type.TIMETZ,
1345            exp.DataType.Type.TIMESTAMPTZ,
1346        ):
1347            type_sql = f"{type_sql} WITH TIME ZONE"
1348
1349        return type_sql
def directory_sql(self, expression: sqlglot.expressions.Directory) -> str:
1351    def directory_sql(self, expression: exp.Directory) -> str:
1352        local = "LOCAL " if expression.args.get("local") else ""
1353        row_format = self.sql(expression, "row_format")
1354        row_format = f" {row_format}" if row_format else ""
1355        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"
def delete_sql(self, expression: sqlglot.expressions.Delete) -> str:
1357    def delete_sql(self, expression: exp.Delete) -> str:
1358        this = self.sql(expression, "this")
1359        this = f" FROM {this}" if this else ""
1360        using = self.sql(expression, "using")
1361        using = f" USING {using}" if using else ""
1362        cluster = self.sql(expression, "cluster")
1363        cluster = f" {cluster}" if cluster else ""
1364        where = self.sql(expression, "where")
1365        returning = self.sql(expression, "returning")
1366        limit = self.sql(expression, "limit")
1367        tables = self.expressions(expression, key="tables")
1368        tables = f" {tables}" if tables else ""
1369        if self.RETURNING_END:
1370            expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}"
1371        else:
1372            expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}"
1373        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")
def drop_sql(self, expression: sqlglot.expressions.Drop) -> str:
1375    def drop_sql(self, expression: exp.Drop) -> str:
1376        this = self.sql(expression, "this")
1377        expressions = self.expressions(expression, flat=True)
1378        expressions = f" ({expressions})" if expressions else ""
1379        kind = expression.args["kind"]
1380        kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind
1381        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
1382        concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else ""
1383        on_cluster = self.sql(expression, "cluster")
1384        on_cluster = f" {on_cluster}" if on_cluster else ""
1385        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
1386        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
1387        cascade = " CASCADE" if expression.args.get("cascade") else ""
1388        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
1389        purge = " PURGE" if expression.args.get("purge") else ""
1390        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:
1392    def set_operation(self, expression: exp.SetOperation) -> str:
1393        op_type = type(expression)
1394        op_name = op_type.key.upper()
1395
1396        distinct = expression.args.get("distinct")
1397        if (
1398            distinct is False
1399            and op_type in (exp.Except, exp.Intersect)
1400            and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE
1401        ):
1402            self.unsupported(f"{op_name} ALL is not supported")
1403
1404        default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type]
1405
1406        if distinct is None:
1407            distinct = default_distinct
1408            if distinct is None:
1409                self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified")
1410
1411        if distinct is default_distinct:
1412            kind = ""
1413        else:
1414            kind = " DISTINCT" if distinct else " ALL"
1415
1416        by_name = " BY NAME" if expression.args.get("by_name") else ""
1417        return f"{op_name}{kind}{by_name}"
def set_operations(self, expression: sqlglot.expressions.SetOperation) -> str:
1419    def set_operations(self, expression: exp.SetOperation) -> str:
1420        if not self.SET_OP_MODIFIERS:
1421            limit = expression.args.get("limit")
1422            order = expression.args.get("order")
1423
1424            if limit or order:
1425                select = self._move_ctes_to_top_level(
1426                    exp.subquery(expression, "_l_0", copy=False).select("*", copy=False)
1427                )
1428
1429                if limit:
1430                    select = select.limit(limit.pop(), copy=False)
1431                if order:
1432                    select = select.order_by(order.pop(), copy=False)
1433                return self.sql(select)
1434
1435        sqls: t.List[str] = []
1436        stack: t.List[t.Union[str, exp.Expression]] = [expression]
1437
1438        while stack:
1439            node = stack.pop()
1440
1441            if isinstance(node, exp.SetOperation):
1442                stack.append(node.expression)
1443                stack.append(
1444                    self.maybe_comment(
1445                        self.set_operation(node), comments=node.comments, separated=True
1446                    )
1447                )
1448                stack.append(node.this)
1449            else:
1450                sqls.append(self.sql(node))
1451
1452        this = self.sep().join(sqls)
1453        this = self.query_modifiers(expression, this)
1454        return self.prepend_ctes(expression, this)
def fetch_sql(self, expression: sqlglot.expressions.Fetch) -> str:
1456    def fetch_sql(self, expression: exp.Fetch) -> str:
1457        direction = expression.args.get("direction")
1458        direction = f" {direction}" if direction else ""
1459        count = self.sql(expression, "count")
1460        count = f" {count}" if count else ""
1461        if expression.args.get("percent"):
1462            count = f"{count} PERCENT"
1463        with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY"
1464        return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}"
def filter_sql(self, expression: sqlglot.expressions.Filter) -> str:
1466    def filter_sql(self, expression: exp.Filter) -> str:
1467        if self.AGGREGATE_FILTER_SUPPORTED:
1468            this = self.sql(expression, "this")
1469            where = self.sql(expression, "expression").strip()
1470            return f"{this} FILTER({where})"
1471
1472        agg = expression.this
1473        agg_arg = agg.this
1474        cond = expression.expression.this
1475        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
1476        return self.sql(agg)
def hint_sql(self, expression: sqlglot.expressions.Hint) -> str:
1478    def hint_sql(self, expression: exp.Hint) -> str:
1479        if not self.QUERY_HINTS:
1480            self.unsupported("Hints are not supported")
1481            return ""
1482
1483        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"
def indexparameters_sql(self, expression: sqlglot.expressions.IndexParameters) -> str:
1485    def indexparameters_sql(self, expression: exp.IndexParameters) -> str:
1486        using = self.sql(expression, "using")
1487        using = f" USING {using}" if using else ""
1488        columns = self.expressions(expression, key="columns", flat=True)
1489        columns = f"({columns})" if columns else ""
1490        partition_by = self.expressions(expression, key="partition_by", flat=True)
1491        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
1492        where = self.sql(expression, "where")
1493        include = self.expressions(expression, key="include", flat=True)
1494        if include:
1495            include = f" INCLUDE ({include})"
1496        with_storage = self.expressions(expression, key="with_storage", flat=True)
1497        with_storage = f" WITH ({with_storage})" if with_storage else ""
1498        tablespace = self.sql(expression, "tablespace")
1499        tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else ""
1500        on = self.sql(expression, "on")
1501        on = f" ON {on}" if on else ""
1502
1503        return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"
def index_sql(self, expression: sqlglot.expressions.Index) -> str:
1505    def index_sql(self, expression: exp.Index) -> str:
1506        unique = "UNIQUE " if expression.args.get("unique") else ""
1507        primary = "PRIMARY " if expression.args.get("primary") else ""
1508        amp = "AMP " if expression.args.get("amp") else ""
1509        name = self.sql(expression, "this")
1510        name = f"{name} " if name else ""
1511        table = self.sql(expression, "table")
1512        table = f"{self.INDEX_ON} {table}" if table else ""
1513
1514        index = "INDEX " if not table else ""
1515
1516        params = self.sql(expression, "params")
1517        return f"{unique}{primary}{amp}{index}{name}{table}{params}"
def identifier_sql(self, expression: sqlglot.expressions.Identifier) -> str:
1519    def identifier_sql(self, expression: exp.Identifier) -> str:
1520        text = expression.name
1521        lower = text.lower()
1522        text = lower if self.normalize and not expression.quoted else text
1523        text = text.replace(self._identifier_end, self._escaped_identifier_end)
1524        if (
1525            expression.quoted
1526            or self.dialect.can_identify(text, self.identify)
1527            or lower in self.RESERVED_KEYWORDS
1528            or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
1529        ):
1530            text = f"{self._identifier_start}{text}{self._identifier_end}"
1531        return text
def hex_sql(self, expression: sqlglot.expressions.Hex) -> str:
1533    def hex_sql(self, expression: exp.Hex) -> str:
1534        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
1535        if self.dialect.HEX_LOWERCASE:
1536            text = self.func("LOWER", text)
1537
1538        return text
def lowerhex_sql(self, expression: sqlglot.expressions.LowerHex) -> str:
1540    def lowerhex_sql(self, expression: exp.LowerHex) -> str:
1541        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
1542        if not self.dialect.HEX_LOWERCASE:
1543            text = self.func("LOWER", text)
1544        return text
def inputoutputformat_sql(self, expression: sqlglot.expressions.InputOutputFormat) -> str:
1546    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
1547        input_format = self.sql(expression, "input_format")
1548        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
1549        output_format = self.sql(expression, "output_format")
1550        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
1551        return self.sep().join((input_format, output_format))
def national_sql(self, expression: sqlglot.expressions.National, prefix: str = 'N') -> str:
1553    def national_sql(self, expression: exp.National, prefix: str = "N") -> str:
1554        string = self.sql(exp.Literal.string(expression.name))
1555        return f"{prefix}{string}"
def partition_sql(self, expression: sqlglot.expressions.Partition) -> str:
1557    def partition_sql(self, expression: exp.Partition) -> str:
1558        return f"PARTITION({self.expressions(expression, flat=True)})"
def properties_sql(self, expression: sqlglot.expressions.Properties) -> str:
1560    def properties_sql(self, expression: exp.Properties) -> str:
1561        root_properties = []
1562        with_properties = []
1563
1564        for p in expression.expressions:
1565            p_loc = self.PROPERTIES_LOCATION[p.__class__]
1566            if p_loc == exp.Properties.Location.POST_WITH:
1567                with_properties.append(p)
1568            elif p_loc == exp.Properties.Location.POST_SCHEMA:
1569                root_properties.append(p)
1570
1571        root_props = self.root_properties(exp.Properties(expressions=root_properties))
1572        with_props = self.with_properties(exp.Properties(expressions=with_properties))
1573
1574        if root_props and with_props and not self.pretty:
1575            with_props = " " + with_props
1576
1577        return root_props + with_props
def root_properties(self, properties: sqlglot.expressions.Properties) -> str:
1579    def root_properties(self, properties: exp.Properties) -> str:
1580        if properties.expressions:
1581            return self.expressions(properties, indent=False, sep=" ")
1582        return ""
def properties( self, properties: sqlglot.expressions.Properties, prefix: str = '', sep: str = ', ', suffix: str = '', wrapped: bool = True) -> str:
1584    def properties(
1585        self,
1586        properties: exp.Properties,
1587        prefix: str = "",
1588        sep: str = ", ",
1589        suffix: str = "",
1590        wrapped: bool = True,
1591    ) -> str:
1592        if properties.expressions:
1593            expressions = self.expressions(properties, sep=sep, indent=False)
1594            if expressions:
1595                expressions = self.wrap(expressions) if wrapped else expressions
1596                return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}"
1597        return ""
def with_properties(self, properties: sqlglot.expressions.Properties) -> str:
1599    def with_properties(self, properties: exp.Properties) -> str:
1600        return self.properties(properties, prefix=self.seg(self.WITH_PROPERTIES_PREFIX, sep=""))
def locate_properties(self, properties: sqlglot.expressions.Properties) -> DefaultDict:
1602    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
1603        properties_locs = defaultdict(list)
1604        for p in properties.expressions:
1605            p_loc = self.PROPERTIES_LOCATION[p.__class__]
1606            if p_loc != exp.Properties.Location.UNSUPPORTED:
1607                properties_locs[p_loc].append(p)
1608            else:
1609                self.unsupported(f"Unsupported property {p.key}")
1610
1611        return properties_locs
def property_name( self, expression: sqlglot.expressions.Property, string_key: bool = False) -> str:
1613    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
1614        if isinstance(expression.this, exp.Dot):
1615            return self.sql(expression, "this")
1616        return f"'{expression.name}'" if string_key else expression.name
def property_sql(self, expression: sqlglot.expressions.Property) -> str:
1618    def property_sql(self, expression: exp.Property) -> str:
1619        property_cls = expression.__class__
1620        if property_cls == exp.Property:
1621            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
1622
1623        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
1624        if not property_name:
1625            self.unsupported(f"Unsupported property {expression.key}")
1626
1627        return f"{property_name}={self.sql(expression, 'this')}"
def likeproperty_sql(self, expression: sqlglot.expressions.LikeProperty) -> str:
1629    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
1630        if self.SUPPORTS_CREATE_TABLE_LIKE:
1631            options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
1632            options = f" {options}" if options else ""
1633
1634            like = f"LIKE {self.sql(expression, 'this')}{options}"
1635            if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema):
1636                like = f"({like})"
1637
1638            return like
1639
1640        if expression.expressions:
1641            self.unsupported("Transpilation of LIKE property options is unsupported")
1642
1643        select = exp.select("*").from_(expression.this).limit(0)
1644        return f"AS {self.sql(select)}"
def fallbackproperty_sql(self, expression: sqlglot.expressions.FallbackProperty) -> str:
1646    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
1647        no = "NO " if expression.args.get("no") else ""
1648        protection = " PROTECTION" if expression.args.get("protection") else ""
1649        return f"{no}FALLBACK{protection}"
def journalproperty_sql(self, expression: sqlglot.expressions.JournalProperty) -> str:
1651    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
1652        no = "NO " if expression.args.get("no") else ""
1653        local = expression.args.get("local")
1654        local = f"{local} " if local else ""
1655        dual = "DUAL " if expression.args.get("dual") else ""
1656        before = "BEFORE " if expression.args.get("before") else ""
1657        after = "AFTER " if expression.args.get("after") else ""
1658        return f"{no}{local}{dual}{before}{after}JOURNAL"
def freespaceproperty_sql(self, expression: sqlglot.expressions.FreespaceProperty) -> str:
1660    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
1661        freespace = self.sql(expression, "this")
1662        percent = " PERCENT" if expression.args.get("percent") else ""
1663        return f"FREESPACE={freespace}{percent}"
def checksumproperty_sql(self, expression: sqlglot.expressions.ChecksumProperty) -> str:
1665    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
1666        if expression.args.get("default"):
1667            property = "DEFAULT"
1668        elif expression.args.get("on"):
1669            property = "ON"
1670        else:
1671            property = "OFF"
1672        return f"CHECKSUM={property}"
def mergeblockratioproperty_sql(self, expression: sqlglot.expressions.MergeBlockRatioProperty) -> str:
1674    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
1675        if expression.args.get("no"):
1676            return "NO MERGEBLOCKRATIO"
1677        if expression.args.get("default"):
1678            return "DEFAULT MERGEBLOCKRATIO"
1679
1680        percent = " PERCENT" if expression.args.get("percent") else ""
1681        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"
def datablocksizeproperty_sql(self, expression: sqlglot.expressions.DataBlocksizeProperty) -> str:
1683    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
1684        default = expression.args.get("default")
1685        minimum = expression.args.get("minimum")
1686        maximum = expression.args.get("maximum")
1687        if default or minimum or maximum:
1688            if default:
1689                prop = "DEFAULT"
1690            elif minimum:
1691                prop = "MINIMUM"
1692            else:
1693                prop = "MAXIMUM"
1694            return f"{prop} DATABLOCKSIZE"
1695        units = expression.args.get("units")
1696        units = f" {units}" if units else ""
1697        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"
def blockcompressionproperty_sql(self, expression: sqlglot.expressions.BlockCompressionProperty) -> str:
1699    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
1700        autotemp = expression.args.get("autotemp")
1701        always = expression.args.get("always")
1702        default = expression.args.get("default")
1703        manual = expression.args.get("manual")
1704        never = expression.args.get("never")
1705
1706        if autotemp is not None:
1707            prop = f"AUTOTEMP({self.expressions(autotemp)})"
1708        elif always:
1709            prop = "ALWAYS"
1710        elif default:
1711            prop = "DEFAULT"
1712        elif manual:
1713            prop = "MANUAL"
1714        elif never:
1715            prop = "NEVER"
1716        return f"BLOCKCOMPRESSION={prop}"
def isolatedloadingproperty_sql(self, expression: sqlglot.expressions.IsolatedLoadingProperty) -> str:
1718    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
1719        no = expression.args.get("no")
1720        no = " NO" if no else ""
1721        concurrent = expression.args.get("concurrent")
1722        concurrent = " CONCURRENT" if concurrent else ""
1723        target = self.sql(expression, "target")
1724        target = f" {target}" if target else ""
1725        return f"WITH{no}{concurrent} ISOLATED LOADING{target}"
def partitionboundspec_sql(self, expression: sqlglot.expressions.PartitionBoundSpec) -> str:
1727    def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str:
1728        if isinstance(expression.this, list):
1729            return f"IN ({self.expressions(expression, key='this', flat=True)})"
1730        if expression.this:
1731            modulus = self.sql(expression, "this")
1732            remainder = self.sql(expression, "expression")
1733            return f"WITH (MODULUS {modulus}, REMAINDER {remainder})"
1734
1735        from_expressions = self.expressions(expression, key="from_expressions", flat=True)
1736        to_expressions = self.expressions(expression, key="to_expressions", flat=True)
1737        return f"FROM ({from_expressions}) TO ({to_expressions})"
def partitionedofproperty_sql(self, expression: sqlglot.expressions.PartitionedOfProperty) -> str:
1739    def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str:
1740        this = self.sql(expression, "this")
1741
1742        for_values_or_default = expression.expression
1743        if isinstance(for_values_or_default, exp.PartitionBoundSpec):
1744            for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}"
1745        else:
1746            for_values_or_default = " DEFAULT"
1747
1748        return f"PARTITION OF {this}{for_values_or_default}"
def lockingproperty_sql(self, expression: sqlglot.expressions.LockingProperty) -> str:
1750    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
1751        kind = expression.args.get("kind")
1752        this = f" {self.sql(expression, 'this')}" if expression.this else ""
1753        for_or_in = expression.args.get("for_or_in")
1754        for_or_in = f" {for_or_in}" if for_or_in else ""
1755        lock_type = expression.args.get("lock_type")
1756        override = " OVERRIDE" if expression.args.get("override") else ""
1757        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"
def withdataproperty_sql(self, expression: sqlglot.expressions.WithDataProperty) -> str:
1759    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
1760        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
1761        statistics = expression.args.get("statistics")
1762        statistics_sql = ""
1763        if statistics is not None:
1764            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
1765        return f"{data_sql}{statistics_sql}"
def withsystemversioningproperty_sql( self, expression: sqlglot.expressions.WithSystemVersioningProperty) -> str:
1767    def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str:
1768        this = self.sql(expression, "this")
1769        this = f"HISTORY_TABLE={this}" if this else ""
1770        data_consistency: t.Optional[str] = self.sql(expression, "data_consistency")
1771        data_consistency = (
1772            f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None
1773        )
1774        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
1775        retention_period = (
1776            f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None
1777        )
1778
1779        if this:
1780            on_sql = self.func("ON", this, data_consistency, retention_period)
1781        else:
1782            on_sql = "ON" if expression.args.get("on") else "OFF"
1783
1784        sql = f"SYSTEM_VERSIONING={on_sql}"
1785
1786        return f"WITH({sql})" if expression.args.get("with") else sql
def insert_sql(self, expression: sqlglot.expressions.Insert) -> str:
1788    def insert_sql(self, expression: exp.Insert) -> str:
1789        hint = self.sql(expression, "hint")
1790        overwrite = expression.args.get("overwrite")
1791
1792        if isinstance(expression.this, exp.Directory):
1793            this = " OVERWRITE" if overwrite else " INTO"
1794        else:
1795            this = self.INSERT_OVERWRITE if overwrite else " INTO"
1796
1797        stored = self.sql(expression, "stored")
1798        stored = f" {stored}" if stored else ""
1799        alternative = expression.args.get("alternative")
1800        alternative = f" OR {alternative}" if alternative else ""
1801        ignore = " IGNORE" if expression.args.get("ignore") else ""
1802        is_function = expression.args.get("is_function")
1803        if is_function:
1804            this = f"{this} FUNCTION"
1805        this = f"{this} {self.sql(expression, 'this')}"
1806
1807        exists = " IF EXISTS" if expression.args.get("exists") else ""
1808        where = self.sql(expression, "where")
1809        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
1810        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
1811        on_conflict = self.sql(expression, "conflict")
1812        on_conflict = f" {on_conflict}" if on_conflict else ""
1813        by_name = " BY NAME" if expression.args.get("by_name") else ""
1814        returning = self.sql(expression, "returning")
1815
1816        if self.RETURNING_END:
1817            expression_sql = f"{expression_sql}{on_conflict}{returning}"
1818        else:
1819            expression_sql = f"{returning}{expression_sql}{on_conflict}"
1820
1821        partition_by = self.sql(expression, "partition")
1822        partition_by = f" {partition_by}" if partition_by else ""
1823        settings = self.sql(expression, "settings")
1824        settings = f" {settings}" if settings else ""
1825
1826        source = self.sql(expression, "source")
1827        source = f"TABLE {source}" if source else ""
1828
1829        sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}"
1830        return self.prepend_ctes(expression, sql)
def introducer_sql(self, expression: sqlglot.expressions.Introducer) -> str:
1832    def introducer_sql(self, expression: exp.Introducer) -> str:
1833        return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}"
def kill_sql(self, expression: sqlglot.expressions.Kill) -> str:
1835    def kill_sql(self, expression: exp.Kill) -> str:
1836        kind = self.sql(expression, "kind")
1837        kind = f" {kind}" if kind else ""
1838        this = self.sql(expression, "this")
1839        this = f" {this}" if this else ""
1840        return f"KILL{kind}{this}"
def pseudotype_sql(self, expression: sqlglot.expressions.PseudoType) -> str:
1842    def pseudotype_sql(self, expression: exp.PseudoType) -> str:
1843        return expression.name
def objectidentifier_sql(self, expression: sqlglot.expressions.ObjectIdentifier) -> str:
1845    def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str:
1846        return expression.name
def onconflict_sql(self, expression: sqlglot.expressions.OnConflict) -> str:
1848    def onconflict_sql(self, expression: exp.OnConflict) -> str:
1849        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
1850
1851        constraint = self.sql(expression, "constraint")
1852        constraint = f" ON CONSTRAINT {constraint}" if constraint else ""
1853
1854        conflict_keys = self.expressions(expression, key="conflict_keys", flat=True)
1855        conflict_keys = f"({conflict_keys}) " if conflict_keys else " "
1856        action = self.sql(expression, "action")
1857
1858        expressions = self.expressions(expression, flat=True)
1859        if expressions:
1860            set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
1861            expressions = f" {set_keyword}{expressions}"
1862
1863        return f"{conflict}{constraint}{conflict_keys}{action}{expressions}"
def returning_sql(self, expression: sqlglot.expressions.Returning) -> str:
1865    def returning_sql(self, expression: exp.Returning) -> str:
1866        return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}"
def rowformatdelimitedproperty_sql(self, expression: sqlglot.expressions.RowFormatDelimitedProperty) -> str:
1868    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
1869        fields = self.sql(expression, "fields")
1870        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
1871        escaped = self.sql(expression, "escaped")
1872        escaped = f" ESCAPED BY {escaped}" if escaped else ""
1873        items = self.sql(expression, "collection_items")
1874        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
1875        keys = self.sql(expression, "map_keys")
1876        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
1877        lines = self.sql(expression, "lines")
1878        lines = f" LINES TERMINATED BY {lines}" if lines else ""
1879        null = self.sql(expression, "null")
1880        null = f" NULL DEFINED AS {null}" if null else ""
1881        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"
def withtablehint_sql(self, expression: sqlglot.expressions.WithTableHint) -> str:
1883    def withtablehint_sql(self, expression: exp.WithTableHint) -> str:
1884        return f"WITH ({self.expressions(expression, flat=True)})"
def indextablehint_sql(self, expression: sqlglot.expressions.IndexTableHint) -> str:
1886    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
1887        this = f"{self.sql(expression, 'this')} INDEX"
1888        target = self.sql(expression, "target")
1889        target = f" FOR {target}" if target else ""
1890        return f"{this}{target} ({self.expressions(expression, flat=True)})"
def historicaldata_sql(self, expression: sqlglot.expressions.HistoricalData) -> str:
1892    def historicaldata_sql(self, expression: exp.HistoricalData) -> str:
1893        this = self.sql(expression, "this")
1894        kind = self.sql(expression, "kind")
1895        expr = self.sql(expression, "expression")
1896        return f"{this} ({kind} => {expr})"
def table_parts(self, expression: sqlglot.expressions.Table) -> str:
1898    def table_parts(self, expression: exp.Table) -> str:
1899        return ".".join(
1900            self.sql(part)
1901            for part in (
1902                expression.args.get("catalog"),
1903                expression.args.get("db"),
1904                expression.args.get("this"),
1905            )
1906            if part is not None
1907        )
def table_sql(self, expression: sqlglot.expressions.Table, sep: str = ' AS ') -> str:
1909    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
1910        table = self.table_parts(expression)
1911        only = "ONLY " if expression.args.get("only") else ""
1912        partition = self.sql(expression, "partition")
1913        partition = f" {partition}" if partition else ""
1914        version = self.sql(expression, "version")
1915        version = f" {version}" if version else ""
1916        alias = self.sql(expression, "alias")
1917        alias = f"{sep}{alias}" if alias else ""
1918
1919        sample = self.sql(expression, "sample")
1920        if self.dialect.ALIAS_POST_TABLESAMPLE:
1921            sample_pre_alias = sample
1922            sample_post_alias = ""
1923        else:
1924            sample_pre_alias = ""
1925            sample_post_alias = sample
1926
1927        hints = self.expressions(expression, key="hints", sep=" ")
1928        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
1929        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
1930        joins = self.indent(
1931            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
1932        )
1933        laterals = self.expressions(expression, key="laterals", sep="")
1934
1935        file_format = self.sql(expression, "format")
1936        if file_format:
1937            pattern = self.sql(expression, "pattern")
1938            pattern = f", PATTERN => {pattern}" if pattern else ""
1939            file_format = f" (FILE_FORMAT => {file_format}{pattern})"
1940
1941        ordinality = expression.args.get("ordinality") or ""
1942        if ordinality:
1943            ordinality = f" WITH ORDINALITY{alias}"
1944            alias = ""
1945
1946        when = self.sql(expression, "when")
1947        if when:
1948            table = f"{table} {when}"
1949
1950        changes = self.sql(expression, "changes")
1951        changes = f" {changes}" if changes else ""
1952
1953        rows_from = self.expressions(expression, key="rows_from")
1954        if rows_from:
1955            table = f"ROWS FROM {self.wrap(rows_from)}"
1956
1957        return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}"
def tablesample_sql( self, expression: sqlglot.expressions.TableSample, tablesample_keyword: Optional[str] = None) -> str:
1959    def tablesample_sql(
1960        self,
1961        expression: exp.TableSample,
1962        tablesample_keyword: t.Optional[str] = None,
1963    ) -> str:
1964        method = self.sql(expression, "method")
1965        method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else ""
1966        numerator = self.sql(expression, "bucket_numerator")
1967        denominator = self.sql(expression, "bucket_denominator")
1968        field = self.sql(expression, "bucket_field")
1969        field = f" ON {field}" if field else ""
1970        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
1971        seed = self.sql(expression, "seed")
1972        seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else ""
1973
1974        size = self.sql(expression, "size")
1975        if size and self.TABLESAMPLE_SIZE_IS_ROWS:
1976            size = f"{size} ROWS"
1977
1978        percent = self.sql(expression, "percent")
1979        if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT:
1980            percent = f"{percent} PERCENT"
1981
1982        expr = f"{bucket}{percent}{size}"
1983        if self.TABLESAMPLE_REQUIRES_PARENS:
1984            expr = f"({expr})"
1985
1986        return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}"
def pivot_sql(self, expression: sqlglot.expressions.Pivot) -> str:
1988    def pivot_sql(self, expression: exp.Pivot) -> str:
1989        expressions = self.expressions(expression, flat=True)
1990
1991        if expression.this:
1992            this = self.sql(expression, "this")
1993            if not expressions:
1994                return f"UNPIVOT {this}"
1995
1996            on = f"{self.seg('ON')} {expressions}"
1997            using = self.expressions(expression, key="using", flat=True)
1998            using = f"{self.seg('USING')} {using}" if using else ""
1999            group = self.sql(expression, "group")
2000            return f"PIVOT {this}{on}{using}{group}"
2001
2002        alias = self.sql(expression, "alias")
2003        alias = f" AS {alias}" if alias else ""
2004        direction = self.seg("UNPIVOT" if expression.unpivot else "PIVOT")
2005
2006        field = self.sql(expression, "field")
2007
2008        include_nulls = expression.args.get("include_nulls")
2009        if include_nulls is not None:
2010            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
2011        else:
2012            nulls = ""
2013
2014        default_on_null = self.sql(expression, "default_on_null")
2015        default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else ""
2016        return f"{direction}{nulls}({expressions} FOR {field}{default_on_null}){alias}"
def version_sql(self, expression: sqlglot.expressions.Version) -> str:
2018    def version_sql(self, expression: exp.Version) -> str:
2019        this = f"FOR {expression.name}"
2020        kind = expression.text("kind")
2021        expr = self.sql(expression, "expression")
2022        return f"{this} {kind} {expr}"
def tuple_sql(self, expression: sqlglot.expressions.Tuple) -> str:
2024    def tuple_sql(self, expression: exp.Tuple) -> str:
2025        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:
2027    def update_sql(self, expression: exp.Update) -> str:
2028        this = self.sql(expression, "this")
2029        set_sql = self.expressions(expression, flat=True)
2030        from_sql = self.sql(expression, "from")
2031        where_sql = self.sql(expression, "where")
2032        returning = self.sql(expression, "returning")
2033        order = self.sql(expression, "order")
2034        limit = self.sql(expression, "limit")
2035        if self.RETURNING_END:
2036            expression_sql = f"{from_sql}{where_sql}{returning}"
2037        else:
2038            expression_sql = f"{returning}{from_sql}{where_sql}"
2039        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
2040        return self.prepend_ctes(expression, sql)
def values_sql( self, expression: sqlglot.expressions.Values, values_as_table: bool = True) -> str:
2042    def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str:
2043        values_as_table = values_as_table and self.VALUES_AS_TABLE
2044
2045        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
2046        if values_as_table or not expression.find_ancestor(exp.From, exp.Join):
2047            args = self.expressions(expression)
2048            alias = self.sql(expression, "alias")
2049            values = f"VALUES{self.seg('')}{args}"
2050            values = (
2051                f"({values})"
2052                if self.WRAP_DERIVED_VALUES
2053                and (alias or isinstance(expression.parent, (exp.From, exp.Table)))
2054                else values
2055            )
2056            return f"{values} AS {alias}" if alias else values
2057
2058        # Converts `VALUES...` expression into a series of select unions.
2059        alias_node = expression.args.get("alias")
2060        column_names = alias_node and alias_node.columns
2061
2062        selects: t.List[exp.Query] = []
2063
2064        for i, tup in enumerate(expression.expressions):
2065            row = tup.expressions
2066
2067            if i == 0 and column_names:
2068                row = [
2069                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
2070                ]
2071
2072            selects.append(exp.Select(expressions=row))
2073
2074        if self.pretty:
2075            # This may result in poor performance for large-cardinality `VALUES` tables, due to
2076            # the deep nesting of the resulting exp.Unions. If this is a problem, either increase
2077            # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`.
2078            query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects)
2079            return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False))
2080
2081        alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else ""
2082        unions = " UNION ALL ".join(self.sql(select) for select in selects)
2083        return f"({unions}){alias}"
def var_sql(self, expression: sqlglot.expressions.Var) -> str:
2085    def var_sql(self, expression: exp.Var) -> str:
2086        return self.sql(expression, "this")
@unsupported_args('expressions')
def into_sql(self, expression: sqlglot.expressions.Into) -> str:
2088    @unsupported_args("expressions")
2089    def into_sql(self, expression: exp.Into) -> str:
2090        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
2091        unlogged = " UNLOGGED" if expression.args.get("unlogged") else ""
2092        return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"
def from_sql(self, expression: sqlglot.expressions.From) -> str:
2094    def from_sql(self, expression: exp.From) -> str:
2095        return f"{self.seg('FROM')} {self.sql(expression, 'this')}"
def groupingsets_sql(self, expression: sqlglot.expressions.GroupingSets) -> str:
2097    def groupingsets_sql(self, expression: exp.GroupingSets) -> str:
2098        grouping_sets = self.expressions(expression, indent=False)
2099        return f"GROUPING SETS {self.wrap(grouping_sets)}"
def rollup_sql(self, expression: sqlglot.expressions.Rollup) -> str:
2101    def rollup_sql(self, expression: exp.Rollup) -> str:
2102        expressions = self.expressions(expression, indent=False)
2103        return f"ROLLUP {self.wrap(expressions)}" if expressions else "WITH ROLLUP"
def cube_sql(self, expression: sqlglot.expressions.Cube) -> str:
2105    def cube_sql(self, expression: exp.Cube) -> str:
2106        expressions = self.expressions(expression, indent=False)
2107        return f"CUBE {self.wrap(expressions)}" if expressions else "WITH CUBE"
def group_sql(self, expression: sqlglot.expressions.Group) -> str:
2109    def group_sql(self, expression: exp.Group) -> str:
2110        group_by_all = expression.args.get("all")
2111        if group_by_all is True:
2112            modifier = " ALL"
2113        elif group_by_all is False:
2114            modifier = " DISTINCT"
2115        else:
2116            modifier = ""
2117
2118        group_by = self.op_expressions(f"GROUP BY{modifier}", expression)
2119
2120        grouping_sets = self.expressions(expression, key="grouping_sets")
2121        cube = self.expressions(expression, key="cube")
2122        rollup = self.expressions(expression, key="rollup")
2123
2124        groupings = csv(
2125            self.seg(grouping_sets) if grouping_sets else "",
2126            self.seg(cube) if cube else "",
2127            self.seg(rollup) if rollup else "",
2128            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
2129            sep=self.GROUPINGS_SEP,
2130        )
2131
2132        if (
2133            expression.expressions
2134            and groupings
2135            and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP")
2136        ):
2137            group_by = f"{group_by}{self.GROUPINGS_SEP}"
2138
2139        return f"{group_by}{groupings}"
def having_sql(self, expression: sqlglot.expressions.Having) -> str:
2141    def having_sql(self, expression: exp.Having) -> str:
2142        this = self.indent(self.sql(expression, "this"))
2143        return f"{self.seg('HAVING')}{self.sep()}{this}"
def connect_sql(self, expression: sqlglot.expressions.Connect) -> str:
2145    def connect_sql(self, expression: exp.Connect) -> str:
2146        start = self.sql(expression, "start")
2147        start = self.seg(f"START WITH {start}") if start else ""
2148        nocycle = " NOCYCLE" if expression.args.get("nocycle") else ""
2149        connect = self.sql(expression, "connect")
2150        connect = self.seg(f"CONNECT BY{nocycle} {connect}")
2151        return start + connect
def prior_sql(self, expression: sqlglot.expressions.Prior) -> str:
2153    def prior_sql(self, expression: exp.Prior) -> str:
2154        return f"PRIOR {self.sql(expression, 'this')}"
def join_sql(self, expression: sqlglot.expressions.Join) -> str:
2156    def join_sql(self, expression: exp.Join) -> str:
2157        if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"):
2158            side = None
2159        else:
2160            side = expression.side
2161
2162        op_sql = " ".join(
2163            op
2164            for op in (
2165                expression.method,
2166                "GLOBAL" if expression.args.get("global") else None,
2167                side,
2168                expression.kind,
2169                expression.hint if self.JOIN_HINTS else None,
2170            )
2171            if op
2172        )
2173        match_cond = self.sql(expression, "match_condition")
2174        match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else ""
2175        on_sql = self.sql(expression, "on")
2176        using = expression.args.get("using")
2177
2178        if not on_sql and using:
2179            on_sql = csv(*(self.sql(column) for column in using))
2180
2181        this = expression.this
2182        this_sql = self.sql(this)
2183
2184        exprs = self.expressions(expression)
2185        if exprs:
2186            this_sql = f"{this_sql},{self.seg(exprs)}"
2187
2188        if on_sql:
2189            on_sql = self.indent(on_sql, skip_first=True)
2190            space = self.seg(" " * self.pad) if self.pretty else " "
2191            if using:
2192                on_sql = f"{space}USING ({on_sql})"
2193            else:
2194                on_sql = f"{space}ON {on_sql}"
2195        elif not op_sql:
2196            if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None:
2197                return f" {this_sql}"
2198
2199            return f", {this_sql}"
2200
2201        if op_sql != "STRAIGHT_JOIN":
2202            op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
2203
2204        return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}"
def lambda_sql( self, expression: sqlglot.expressions.Lambda, arrow_sep: str = '->') -> str:
2206    def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->") -> str:
2207        args = self.expressions(expression, flat=True)
2208        args = f"({args})" if len(args.split(",")) > 1 else args
2209        return f"{args} {arrow_sep} {self.sql(expression, 'this')}"
def lateral_op(self, expression: sqlglot.expressions.Lateral) -> str:
2211    def lateral_op(self, expression: exp.Lateral) -> str:
2212        cross_apply = expression.args.get("cross_apply")
2213
2214        # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/
2215        if cross_apply is True:
2216            op = "INNER JOIN "
2217        elif cross_apply is False:
2218            op = "LEFT JOIN "
2219        else:
2220            op = ""
2221
2222        return f"{op}LATERAL"
def lateral_sql(self, expression: sqlglot.expressions.Lateral) -> str:
2224    def lateral_sql(self, expression: exp.Lateral) -> str:
2225        this = self.sql(expression, "this")
2226
2227        if expression.args.get("view"):
2228            alias = expression.args["alias"]
2229            columns = self.expressions(alias, key="columns", flat=True)
2230            table = f" {alias.name}" if alias.name else ""
2231            columns = f" AS {columns}" if columns else ""
2232            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
2233            return f"{op_sql}{self.sep()}{this}{table}{columns}"
2234
2235        alias = self.sql(expression, "alias")
2236        alias = f" AS {alias}" if alias else ""
2237        return f"{self.lateral_op(expression)} {this}{alias}"
def limit_sql(self, expression: sqlglot.expressions.Limit, top: bool = False) -> str:
2239    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
2240        this = self.sql(expression, "this")
2241
2242        args = [
2243            self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e
2244            for e in (expression.args.get(k) for k in ("offset", "expression"))
2245            if e
2246        ]
2247
2248        args_sql = ", ".join(self.sql(e) for e in args)
2249        args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql
2250        expressions = self.expressions(expression, flat=True)
2251        expressions = f" BY {expressions}" if expressions else ""
2252
2253        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{expressions}"
def offset_sql(self, expression: sqlglot.expressions.Offset) -> str:
2255    def offset_sql(self, expression: exp.Offset) -> str:
2256        this = self.sql(expression, "this")
2257        value = expression.expression
2258        value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value
2259        expressions = self.expressions(expression, flat=True)
2260        expressions = f" BY {expressions}" if expressions else ""
2261        return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"
def setitem_sql(self, expression: sqlglot.expressions.SetItem) -> str:
2263    def setitem_sql(self, expression: exp.SetItem) -> str:
2264        kind = self.sql(expression, "kind")
2265        kind = f"{kind} " if kind else ""
2266        this = self.sql(expression, "this")
2267        expressions = self.expressions(expression)
2268        collate = self.sql(expression, "collate")
2269        collate = f" COLLATE {collate}" if collate else ""
2270        global_ = "GLOBAL " if expression.args.get("global") else ""
2271        return f"{global_}{kind}{this}{expressions}{collate}"
def set_sql(self, expression: sqlglot.expressions.Set) -> str:
2273    def set_sql(self, expression: exp.Set) -> str:
2274        expressions = (
2275            f" {self.expressions(expression, flat=True)}" if expression.expressions else ""
2276        )
2277        tag = " TAG" if expression.args.get("tag") else ""
2278        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"
def pragma_sql(self, expression: sqlglot.expressions.Pragma) -> str:
2280    def pragma_sql(self, expression: exp.Pragma) -> str:
2281        return f"PRAGMA {self.sql(expression, 'this')}"
def lock_sql(self, expression: sqlglot.expressions.Lock) -> str:
2283    def lock_sql(self, expression: exp.Lock) -> str:
2284        if not self.LOCKING_READS_SUPPORTED:
2285            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
2286            return ""
2287
2288        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
2289        expressions = self.expressions(expression, flat=True)
2290        expressions = f" OF {expressions}" if expressions else ""
2291        wait = expression.args.get("wait")
2292
2293        if wait is not None:
2294            if isinstance(wait, exp.Literal):
2295                wait = f" WAIT {self.sql(wait)}"
2296            else:
2297                wait = " NOWAIT" if wait else " SKIP LOCKED"
2298
2299        return f"{lock_type}{expressions}{wait or ''}"
def literal_sql(self, expression: sqlglot.expressions.Literal) -> str:
2301    def literal_sql(self, expression: exp.Literal) -> str:
2302        text = expression.this or ""
2303        if expression.is_string:
2304            text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}"
2305        return text
def escape_str(self, text: str, escape_backslash: bool = True) -> str:
2307    def escape_str(self, text: str, escape_backslash: bool = True) -> str:
2308        if self.dialect.ESCAPED_SEQUENCES:
2309            to_escaped = self.dialect.ESCAPED_SEQUENCES
2310            text = "".join(
2311                to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text
2312            )
2313
2314        return self._replace_line_breaks(text).replace(
2315            self.dialect.QUOTE_END, self._escaped_quote_end
2316        )
def loaddata_sql(self, expression: sqlglot.expressions.LoadData) -> str:
2318    def loaddata_sql(self, expression: exp.LoadData) -> str:
2319        local = " LOCAL" if expression.args.get("local") else ""
2320        inpath = f" INPATH {self.sql(expression, 'inpath')}"
2321        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
2322        this = f" INTO TABLE {self.sql(expression, 'this')}"
2323        partition = self.sql(expression, "partition")
2324        partition = f" {partition}" if partition else ""
2325        input_format = self.sql(expression, "input_format")
2326        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
2327        serde = self.sql(expression, "serde")
2328        serde = f" SERDE {serde}" if serde else ""
2329        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"
def null_sql(self, *_) -> str:
2331    def null_sql(self, *_) -> str:
2332        return "NULL"
def boolean_sql(self, expression: sqlglot.expressions.Boolean) -> str:
2334    def boolean_sql(self, expression: exp.Boolean) -> str:
2335        return "TRUE" if expression.this else "FALSE"
def order_sql(self, expression: sqlglot.expressions.Order, flat: bool = False) -> str:
2337    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
2338        this = self.sql(expression, "this")
2339        this = f"{this} " if this else this
2340        siblings = "SIBLINGS " if expression.args.get("siblings") else ""
2341        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:
2343    def withfill_sql(self, expression: exp.WithFill) -> str:
2344        from_sql = self.sql(expression, "from")
2345        from_sql = f" FROM {from_sql}" if from_sql else ""
2346        to_sql = self.sql(expression, "to")
2347        to_sql = f" TO {to_sql}" if to_sql else ""
2348        step_sql = self.sql(expression, "step")
2349        step_sql = f" STEP {step_sql}" if step_sql else ""
2350        interpolated_values = [
2351            f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}"
2352            if isinstance(e, exp.Alias)
2353            else self.sql(e, "this")
2354            for e in expression.args.get("interpolate") or []
2355        ]
2356        interpolate = (
2357            f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else ""
2358        )
2359        return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}"
def cluster_sql(self, expression: sqlglot.expressions.Cluster) -> str:
2361    def cluster_sql(self, expression: exp.Cluster) -> str:
2362        return self.op_expressions("CLUSTER BY", expression)
def distribute_sql(self, expression: sqlglot.expressions.Distribute) -> str:
2364    def distribute_sql(self, expression: exp.Distribute) -> str:
2365        return self.op_expressions("DISTRIBUTE BY", expression)
def sort_sql(self, expression: sqlglot.expressions.Sort) -> str:
2367    def sort_sql(self, expression: exp.Sort) -> str:
2368        return self.op_expressions("SORT BY", expression)
def ordered_sql(self, expression: sqlglot.expressions.Ordered) -> str:
2370    def ordered_sql(self, expression: exp.Ordered) -> str:
2371        desc = expression.args.get("desc")
2372        asc = not desc
2373
2374        nulls_first = expression.args.get("nulls_first")
2375        nulls_last = not nulls_first
2376        nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large"
2377        nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small"
2378        nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last"
2379
2380        this = self.sql(expression, "this")
2381
2382        sort_order = " DESC" if desc else (" ASC" if desc is False else "")
2383        nulls_sort_change = ""
2384        if nulls_first and (
2385            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
2386        ):
2387            nulls_sort_change = " NULLS FIRST"
2388        elif (
2389            nulls_last
2390            and ((asc and nulls_are_small) or (desc and nulls_are_large))
2391            and not nulls_are_last
2392        ):
2393            nulls_sort_change = " NULLS LAST"
2394
2395        # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it
2396        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
2397            window = expression.find_ancestor(exp.Window, exp.Select)
2398            if isinstance(window, exp.Window) and window.args.get("spec"):
2399                self.unsupported(
2400                    f"'{nulls_sort_change.strip()}' translation not supported in window functions"
2401                )
2402                nulls_sort_change = ""
2403            elif (
2404                self.NULL_ORDERING_SUPPORTED is False
2405                and (isinstance(expression.find_ancestor(exp.AggFunc, exp.Select), exp.AggFunc))
2406                and (
2407                    (asc and nulls_sort_change == " NULLS LAST")
2408                    or (desc and nulls_sort_change == " NULLS FIRST")
2409                )
2410            ):
2411                self.unsupported(
2412                    f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order"
2413                )
2414                nulls_sort_change = ""
2415            elif self.NULL_ORDERING_SUPPORTED is None:
2416                if expression.this.is_int:
2417                    self.unsupported(
2418                        f"'{nulls_sort_change.strip()}' translation not supported with positional ordering"
2419                    )
2420                elif not isinstance(expression.this, exp.Rand):
2421                    null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else ""
2422                    this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}"
2423                nulls_sort_change = ""
2424
2425        with_fill = self.sql(expression, "with_fill")
2426        with_fill = f" {with_fill}" if with_fill else ""
2427
2428        return f"{this}{sort_order}{nulls_sort_change}{with_fill}"
def matchrecognizemeasure_sql(self, expression: sqlglot.expressions.MatchRecognizeMeasure) -> str:
2430    def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str:
2431        window_frame = self.sql(expression, "window_frame")
2432        window_frame = f"{window_frame} " if window_frame else ""
2433
2434        this = self.sql(expression, "this")
2435
2436        return f"{window_frame}{this}"
def matchrecognize_sql(self, expression: sqlglot.expressions.MatchRecognize) -> str:
2438    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
2439        partition = self.partition_by_sql(expression)
2440        order = self.sql(expression, "order")
2441        measures = self.expressions(expression, key="measures")
2442        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
2443        rows = self.sql(expression, "rows")
2444        rows = self.seg(rows) if rows else ""
2445        after = self.sql(expression, "after")
2446        after = self.seg(after) if after else ""
2447        pattern = self.sql(expression, "pattern")
2448        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
2449        definition_sqls = [
2450            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
2451            for definition in expression.args.get("define", [])
2452        ]
2453        definitions = self.expressions(sqls=definition_sqls)
2454        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
2455        body = "".join(
2456            (
2457                partition,
2458                order,
2459                measures,
2460                rows,
2461                after,
2462                pattern,
2463                define,
2464            )
2465        )
2466        alias = self.sql(expression, "alias")
2467        alias = f" {alias}" if alias else ""
2468        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"
def query_modifiers(self, expression: sqlglot.expressions.Expression, *sqls: str) -> str:
2470    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
2471        limit = expression.args.get("limit")
2472
2473        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
2474            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
2475        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
2476            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
2477
2478        return csv(
2479            *sqls,
2480            *[self.sql(join) for join in expression.args.get("joins") or []],
2481            self.sql(expression, "connect"),
2482            self.sql(expression, "match"),
2483            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
2484            self.sql(expression, "prewhere"),
2485            self.sql(expression, "where"),
2486            self.sql(expression, "group"),
2487            self.sql(expression, "having"),
2488            *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()],
2489            self.sql(expression, "order"),
2490            *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit),
2491            *self.after_limit_modifiers(expression),
2492            self.options_modifier(expression),
2493            sep="",
2494        )
def options_modifier(self, expression: sqlglot.expressions.Expression) -> str:
2496    def options_modifier(self, expression: exp.Expression) -> str:
2497        options = self.expressions(expression, key="options")
2498        return f" {options}" if options else ""
def queryoption_sql(self, expression: sqlglot.expressions.QueryOption) -> str:
2500    def queryoption_sql(self, expression: exp.QueryOption) -> str:
2501        return ""
def offset_limit_modifiers( self, expression: sqlglot.expressions.Expression, fetch: bool, limit: Union[sqlglot.expressions.Fetch, sqlglot.expressions.Limit, NoneType]) -> List[str]:
2503    def offset_limit_modifiers(
2504        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
2505    ) -> t.List[str]:
2506        return [
2507            self.sql(expression, "offset") if fetch else self.sql(limit),
2508            self.sql(limit) if fetch else self.sql(expression, "offset"),
2509        ]
def after_limit_modifiers(self, expression: sqlglot.expressions.Expression) -> List[str]:
2511    def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]:
2512        locks = self.expressions(expression, key="locks", sep=" ")
2513        locks = f" {locks}" if locks else ""
2514        return [locks, self.sql(expression, "sample")]
def select_sql(self, expression: sqlglot.expressions.Select) -> str:
2516    def select_sql(self, expression: exp.Select) -> str:
2517        into = expression.args.get("into")
2518        if not self.SUPPORTS_SELECT_INTO and into:
2519            into.pop()
2520
2521        hint = self.sql(expression, "hint")
2522        distinct = self.sql(expression, "distinct")
2523        distinct = f" {distinct}" if distinct else ""
2524        kind = self.sql(expression, "kind")
2525
2526        limit = expression.args.get("limit")
2527        if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP:
2528            top = self.limit_sql(limit, top=True)
2529            limit.pop()
2530        else:
2531            top = ""
2532
2533        expressions = self.expressions(expression)
2534
2535        if kind:
2536            if kind in self.SELECT_KINDS:
2537                kind = f" AS {kind}"
2538            else:
2539                if kind == "STRUCT":
2540                    expressions = self.expressions(
2541                        sqls=[
2542                            self.sql(
2543                                exp.Struct(
2544                                    expressions=[
2545                                        exp.PropertyEQ(this=e.args.get("alias"), expression=e.this)
2546                                        if isinstance(e, exp.Alias)
2547                                        else e
2548                                        for e in expression.expressions
2549                                    ]
2550                                )
2551                            )
2552                        ]
2553                    )
2554                kind = ""
2555
2556        operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ")
2557        operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else ""
2558
2559        # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata
2560        # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first.
2561        top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}"
2562        expressions = f"{self.sep()}{expressions}" if expressions else expressions
2563        sql = self.query_modifiers(
2564            expression,
2565            f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}",
2566            self.sql(expression, "into", comment=False),
2567            self.sql(expression, "from", comment=False),
2568        )
2569
2570        # If both the CTE and SELECT clauses have comments, generate the latter earlier
2571        if expression.args.get("with"):
2572            sql = self.maybe_comment(sql, expression)
2573            expression.pop_comments()
2574
2575        sql = self.prepend_ctes(expression, sql)
2576
2577        if not self.SUPPORTS_SELECT_INTO and into:
2578            if into.args.get("temporary"):
2579                table_kind = " TEMPORARY"
2580            elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"):
2581                table_kind = " UNLOGGED"
2582            else:
2583                table_kind = ""
2584            sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}"
2585
2586        return sql
def schema_sql(self, expression: sqlglot.expressions.Schema) -> str:
2588    def schema_sql(self, expression: exp.Schema) -> str:
2589        this = self.sql(expression, "this")
2590        sql = self.schema_columns_sql(expression)
2591        return f"{this} {sql}" if this and sql else this or sql
def schema_columns_sql(self, expression: sqlglot.expressions.Schema) -> str:
2593    def schema_columns_sql(self, expression: exp.Schema) -> str:
2594        if expression.expressions:
2595            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
2596        return ""
def star_sql(self, expression: sqlglot.expressions.Star) -> str:
2598    def star_sql(self, expression: exp.Star) -> str:
2599        except_ = self.expressions(expression, key="except", flat=True)
2600        except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else ""
2601        replace = self.expressions(expression, key="replace", flat=True)
2602        replace = f"{self.seg('REPLACE')} ({replace})" if replace else ""
2603        rename = self.expressions(expression, key="rename", flat=True)
2604        rename = f"{self.seg('RENAME')} ({rename})" if rename else ""
2605        return f"*{except_}{replace}{rename}"
def parameter_sql(self, expression: sqlglot.expressions.Parameter) -> str:
2607    def parameter_sql(self, expression: exp.Parameter) -> str:
2608        this = self.sql(expression, "this")
2609        return f"{self.PARAMETER_TOKEN}{this}"
def sessionparameter_sql(self, expression: sqlglot.expressions.SessionParameter) -> str:
2611    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
2612        this = self.sql(expression, "this")
2613        kind = expression.text("kind")
2614        if kind:
2615            kind = f"{kind}."
2616        return f"@@{kind}{this}"
def placeholder_sql(self, expression: sqlglot.expressions.Placeholder) -> str:
2618    def placeholder_sql(self, expression: exp.Placeholder) -> str:
2619        return f"{self.NAMED_PLACEHOLDER_TOKEN}{expression.name}" if expression.this else "?"
def subquery_sql(self, expression: sqlglot.expressions.Subquery, sep: str = ' AS ') -> str:
2621    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
2622        alias = self.sql(expression, "alias")
2623        alias = f"{sep}{alias}" if alias else ""
2624        sample = self.sql(expression, "sample")
2625        if self.dialect.ALIAS_POST_TABLESAMPLE and sample:
2626            alias = f"{sample}{alias}"
2627
2628            # Set to None so it's not generated again by self.query_modifiers()
2629            expression.set("sample", None)
2630
2631        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
2632        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
2633        return self.prepend_ctes(expression, sql)
def qualify_sql(self, expression: sqlglot.expressions.Qualify) -> str:
2635    def qualify_sql(self, expression: exp.Qualify) -> str:
2636        this = self.indent(self.sql(expression, "this"))
2637        return f"{self.seg('QUALIFY')}{self.sep()}{this}"
def unnest_sql(self, expression: sqlglot.expressions.Unnest) -> str:
2639    def unnest_sql(self, expression: exp.Unnest) -> str:
2640        args = self.expressions(expression, flat=True)
2641
2642        alias = expression.args.get("alias")
2643        offset = expression.args.get("offset")
2644
2645        if self.UNNEST_WITH_ORDINALITY:
2646            if alias and isinstance(offset, exp.Expression):
2647                alias.append("columns", offset)
2648
2649        if alias and self.dialect.UNNEST_COLUMN_ONLY:
2650            columns = alias.columns
2651            alias = self.sql(columns[0]) if columns else ""
2652        else:
2653            alias = self.sql(alias)
2654
2655        alias = f" AS {alias}" if alias else alias
2656        if self.UNNEST_WITH_ORDINALITY:
2657            suffix = f" WITH ORDINALITY{alias}" if offset else alias
2658        else:
2659            if isinstance(offset, exp.Expression):
2660                suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}"
2661            elif offset:
2662                suffix = f"{alias} WITH OFFSET"
2663            else:
2664                suffix = alias
2665
2666        return f"UNNEST({args}){suffix}"
def prewhere_sql(self, expression: sqlglot.expressions.PreWhere) -> str:
2668    def prewhere_sql(self, expression: exp.PreWhere) -> str:
2669        return ""
def where_sql(self, expression: sqlglot.expressions.Where) -> str:
2671    def where_sql(self, expression: exp.Where) -> str:
2672        this = self.indent(self.sql(expression, "this"))
2673        return f"{self.seg('WHERE')}{self.sep()}{this}"
def window_sql(self, expression: sqlglot.expressions.Window) -> str:
2675    def window_sql(self, expression: exp.Window) -> str:
2676        this = self.sql(expression, "this")
2677        partition = self.partition_by_sql(expression)
2678        order = expression.args.get("order")
2679        order = self.order_sql(order, flat=True) if order else ""
2680        spec = self.sql(expression, "spec")
2681        alias = self.sql(expression, "alias")
2682        over = self.sql(expression, "over") or "OVER"
2683
2684        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
2685
2686        first = expression.args.get("first")
2687        if first is None:
2688            first = ""
2689        else:
2690            first = "FIRST" if first else "LAST"
2691
2692        if not partition and not order and not spec and alias:
2693            return f"{this} {alias}"
2694
2695        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
2696        return f"{this} ({args})"
def partition_by_sql( self, expression: sqlglot.expressions.Window | sqlglot.expressions.MatchRecognize) -> str:
2698    def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str:
2699        partition = self.expressions(expression, key="partition_by", flat=True)
2700        return f"PARTITION BY {partition}" if partition else ""
def windowspec_sql(self, expression: sqlglot.expressions.WindowSpec) -> str:
2702    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
2703        kind = self.sql(expression, "kind")
2704        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
2705        end = (
2706            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
2707            or "CURRENT ROW"
2708        )
2709        return f"{kind} BETWEEN {start} AND {end}"
def withingroup_sql(self, expression: sqlglot.expressions.WithinGroup) -> str:
2711    def withingroup_sql(self, expression: exp.WithinGroup) -> str:
2712        this = self.sql(expression, "this")
2713        expression_sql = self.sql(expression, "expression")[1:]  # order has a leading space
2714        return f"{this} WITHIN GROUP ({expression_sql})"
def between_sql(self, expression: sqlglot.expressions.Between) -> str:
2716    def between_sql(self, expression: exp.Between) -> str:
2717        this = self.sql(expression, "this")
2718        low = self.sql(expression, "low")
2719        high = self.sql(expression, "high")
2720        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]:
2722    def bracket_offset_expressions(
2723        self, expression: exp.Bracket, index_offset: t.Optional[int] = None
2724    ) -> t.List[exp.Expression]:
2725        return apply_index_offset(
2726            expression.this,
2727            expression.expressions,
2728            (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0),
2729        )
def bracket_sql(self, expression: sqlglot.expressions.Bracket) -> str:
2731    def bracket_sql(self, expression: exp.Bracket) -> str:
2732        expressions = self.bracket_offset_expressions(expression)
2733        expressions_sql = ", ".join(self.sql(e) for e in expressions)
2734        return f"{self.sql(expression, 'this')}[{expressions_sql}]"
def all_sql(self, expression: sqlglot.expressions.All) -> str:
2736    def all_sql(self, expression: exp.All) -> str:
2737        return f"ALL {self.wrap(expression)}"
def any_sql(self, expression: sqlglot.expressions.Any) -> str:
2739    def any_sql(self, expression: exp.Any) -> str:
2740        this = self.sql(expression, "this")
2741        if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)):
2742            if isinstance(expression.this, exp.UNWRAPPED_QUERIES):
2743                this = self.wrap(this)
2744            return f"ANY{this}"
2745        return f"ANY {this}"
def exists_sql(self, expression: sqlglot.expressions.Exists) -> str:
2747    def exists_sql(self, expression: exp.Exists) -> str:
2748        return f"EXISTS{self.wrap(expression)}"
def case_sql(self, expression: sqlglot.expressions.Case) -> str:
2750    def case_sql(self, expression: exp.Case) -> str:
2751        this = self.sql(expression, "this")
2752        statements = [f"CASE {this}" if this else "CASE"]
2753
2754        for e in expression.args["ifs"]:
2755            statements.append(f"WHEN {self.sql(e, 'this')}")
2756            statements.append(f"THEN {self.sql(e, 'true')}")
2757
2758        default = self.sql(expression, "default")
2759
2760        if default:
2761            statements.append(f"ELSE {default}")
2762
2763        statements.append("END")
2764
2765        if self.pretty and self.too_wide(statements):
2766            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
2767
2768        return " ".join(statements)
def constraint_sql(self, expression: sqlglot.expressions.Constraint) -> str:
2770    def constraint_sql(self, expression: exp.Constraint) -> str:
2771        this = self.sql(expression, "this")
2772        expressions = self.expressions(expression, flat=True)
2773        return f"CONSTRAINT {this} {expressions}"
def nextvaluefor_sql(self, expression: sqlglot.expressions.NextValueFor) -> str:
2775    def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str:
2776        order = expression.args.get("order")
2777        order = f" OVER ({self.order_sql(order, flat=True)})" if order else ""
2778        return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}"
def extract_sql(self, expression: sqlglot.expressions.Extract) -> str:
2780    def extract_sql(self, expression: exp.Extract) -> str:
2781        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
2782        expression_sql = self.sql(expression, "expression")
2783        return f"EXTRACT({this} FROM {expression_sql})"
def trim_sql(self, expression: sqlglot.expressions.Trim) -> str:
2785    def trim_sql(self, expression: exp.Trim) -> str:
2786        trim_type = self.sql(expression, "position")
2787
2788        if trim_type == "LEADING":
2789            func_name = "LTRIM"
2790        elif trim_type == "TRAILING":
2791            func_name = "RTRIM"
2792        else:
2793            func_name = "TRIM"
2794
2795        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]:
2797    def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]:
2798        args = expression.expressions
2799        if isinstance(expression, exp.ConcatWs):
2800            args = args[1:]  # Skip the delimiter
2801
2802        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
2803            args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args]
2804
2805        if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"):
2806            args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args]
2807
2808        return args
def concat_sql(self, expression: sqlglot.expressions.Concat) -> str:
2810    def concat_sql(self, expression: exp.Concat) -> str:
2811        expressions = self.convert_concat_args(expression)
2812
2813        # Some dialects don't allow a single-argument CONCAT call
2814        if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1:
2815            return self.sql(expressions[0])
2816
2817        return self.func("CONCAT", *expressions)
def concatws_sql(self, expression: sqlglot.expressions.ConcatWs) -> str:
2819    def concatws_sql(self, expression: exp.ConcatWs) -> str:
2820        return self.func(
2821            "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression)
2822        )
def check_sql(self, expression: sqlglot.expressions.Check) -> str:
2824    def check_sql(self, expression: exp.Check) -> str:
2825        this = self.sql(expression, key="this")
2826        return f"CHECK ({this})"
def foreignkey_sql(self, expression: sqlglot.expressions.ForeignKey) -> str:
2828    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
2829        expressions = self.expressions(expression, flat=True)
2830        reference = self.sql(expression, "reference")
2831        reference = f" {reference}" if reference else ""
2832        delete = self.sql(expression, "delete")
2833        delete = f" ON DELETE {delete}" if delete else ""
2834        update = self.sql(expression, "update")
2835        update = f" ON UPDATE {update}" if update else ""
2836        return f"FOREIGN KEY ({expressions}){reference}{delete}{update}"
def primarykey_sql(self, expression: sqlglot.expressions.ForeignKey) -> str:
2838    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
2839        expressions = self.expressions(expression, flat=True)
2840        options = self.expressions(expression, key="options", flat=True, sep=" ")
2841        options = f" {options}" if options else ""
2842        return f"PRIMARY KEY ({expressions}){options}"
def if_sql(self, expression: sqlglot.expressions.If) -> str:
2844    def if_sql(self, expression: exp.If) -> str:
2845        return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false")))
def matchagainst_sql(self, expression: sqlglot.expressions.MatchAgainst) -> str:
2847    def matchagainst_sql(self, expression: exp.MatchAgainst) -> str:
2848        modifier = expression.args.get("modifier")
2849        modifier = f" {modifier}" if modifier else ""
2850        return f"{self.func('MATCH', *expression.expressions)} AGAINST({self.sql(expression, 'this')}{modifier})"
def jsonkeyvalue_sql(self, expression: sqlglot.expressions.JSONKeyValue) -> str:
2852    def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str:
2853        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:
2855    def jsonpath_sql(self, expression: exp.JSONPath) -> str:
2856        path = self.expressions(expression, sep="", flat=True).lstrip(".")
2857
2858        if expression.args.get("escape"):
2859            path = self.escape_str(path)
2860
2861        if self.QUOTE_JSON_PATH:
2862            path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"
2863
2864        return path
def json_path_part(self, expression: int | str | sqlglot.expressions.JSONPathPart) -> str:
2866    def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str:
2867        if isinstance(expression, exp.JSONPathPart):
2868            transform = self.TRANSFORMS.get(expression.__class__)
2869            if not callable(transform):
2870                self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}")
2871                return ""
2872
2873            return transform(self, expression)
2874
2875        if isinstance(expression, int):
2876            return str(expression)
2877
2878        if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE:
2879            escaped = expression.replace("'", "\\'")
2880            escaped = f"\\'{expression}\\'"
2881        else:
2882            escaped = expression.replace('"', '\\"')
2883            escaped = f'"{escaped}"'
2884
2885        return escaped
def formatjson_sql(self, expression: sqlglot.expressions.FormatJson) -> str:
2887    def formatjson_sql(self, expression: exp.FormatJson) -> str:
2888        return f"{self.sql(expression, 'this')} FORMAT JSON"
def jsonobject_sql( self, expression: sqlglot.expressions.JSONObject | sqlglot.expressions.JSONObjectAgg) -> str:
2890    def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str:
2891        null_handling = expression.args.get("null_handling")
2892        null_handling = f" {null_handling}" if null_handling else ""
2893
2894        unique_keys = expression.args.get("unique_keys")
2895        if unique_keys is not None:
2896            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
2897        else:
2898            unique_keys = ""
2899
2900        return_type = self.sql(expression, "return_type")
2901        return_type = f" RETURNING {return_type}" if return_type else ""
2902        encoding = self.sql(expression, "encoding")
2903        encoding = f" ENCODING {encoding}" if encoding else ""
2904
2905        return self.func(
2906            "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG",
2907            *expression.expressions,
2908            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
2909        )
def jsonobjectagg_sql(self, expression: sqlglot.expressions.JSONObjectAgg) -> str:
2911    def jsonobjectagg_sql(self, expression: exp.JSONObjectAgg) -> str:
2912        return self.jsonobject_sql(expression)
def jsonarray_sql(self, expression: sqlglot.expressions.JSONArray) -> str:
2914    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
2915        null_handling = expression.args.get("null_handling")
2916        null_handling = f" {null_handling}" if null_handling else ""
2917        return_type = self.sql(expression, "return_type")
2918        return_type = f" RETURNING {return_type}" if return_type else ""
2919        strict = " STRICT" if expression.args.get("strict") else ""
2920        return self.func(
2921            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
2922        )
def jsonarrayagg_sql(self, expression: sqlglot.expressions.JSONArrayAgg) -> str:
2924    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
2925        this = self.sql(expression, "this")
2926        order = self.sql(expression, "order")
2927        null_handling = expression.args.get("null_handling")
2928        null_handling = f" {null_handling}" if null_handling else ""
2929        return_type = self.sql(expression, "return_type")
2930        return_type = f" RETURNING {return_type}" if return_type else ""
2931        strict = " STRICT" if expression.args.get("strict") else ""
2932        return self.func(
2933            "JSON_ARRAYAGG",
2934            this,
2935            suffix=f"{order}{null_handling}{return_type}{strict})",
2936        )
def jsoncolumndef_sql(self, expression: sqlglot.expressions.JSONColumnDef) -> str:
2938    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
2939        path = self.sql(expression, "path")
2940        path = f" PATH {path}" if path else ""
2941        nested_schema = self.sql(expression, "nested_schema")
2942
2943        if nested_schema:
2944            return f"NESTED{path} {nested_schema}"
2945
2946        this = self.sql(expression, "this")
2947        kind = self.sql(expression, "kind")
2948        kind = f" {kind}" if kind else ""
2949        return f"{this}{kind}{path}"
def jsonschema_sql(self, expression: sqlglot.expressions.JSONSchema) -> str:
2951    def jsonschema_sql(self, expression: exp.JSONSchema) -> str:
2952        return self.func("COLUMNS", *expression.expressions)
def jsontable_sql(self, expression: sqlglot.expressions.JSONTable) -> str:
2954    def jsontable_sql(self, expression: exp.JSONTable) -> str:
2955        this = self.sql(expression, "this")
2956        path = self.sql(expression, "path")
2957        path = f", {path}" if path else ""
2958        error_handling = expression.args.get("error_handling")
2959        error_handling = f" {error_handling}" if error_handling else ""
2960        empty_handling = expression.args.get("empty_handling")
2961        empty_handling = f" {empty_handling}" if empty_handling else ""
2962        schema = self.sql(expression, "schema")
2963        return self.func(
2964            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
2965        )
def openjsoncolumndef_sql(self, expression: sqlglot.expressions.OpenJSONColumnDef) -> str:
2967    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
2968        this = self.sql(expression, "this")
2969        kind = self.sql(expression, "kind")
2970        path = self.sql(expression, "path")
2971        path = f" {path}" if path else ""
2972        as_json = " AS JSON" if expression.args.get("as_json") else ""
2973        return f"{this} {kind}{path}{as_json}"
def openjson_sql(self, expression: sqlglot.expressions.OpenJSON) -> str:
2975    def openjson_sql(self, expression: exp.OpenJSON) -> str:
2976        this = self.sql(expression, "this")
2977        path = self.sql(expression, "path")
2978        path = f", {path}" if path else ""
2979        expressions = self.expressions(expression)
2980        with_ = (
2981            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
2982            if expressions
2983            else ""
2984        )
2985        return f"OPENJSON({this}{path}){with_}"
def in_sql(self, expression: sqlglot.expressions.In) -> str:
2987    def in_sql(self, expression: exp.In) -> str:
2988        query = expression.args.get("query")
2989        unnest = expression.args.get("unnest")
2990        field = expression.args.get("field")
2991        is_global = " GLOBAL" if expression.args.get("is_global") else ""
2992
2993        if query:
2994            in_sql = self.sql(query)
2995        elif unnest:
2996            in_sql = self.in_unnest_op(unnest)
2997        elif field:
2998            in_sql = self.sql(field)
2999        else:
3000            in_sql = f"({self.expressions(expression, flat=True)})"
3001
3002        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"
def in_unnest_op(self, unnest: sqlglot.expressions.Unnest) -> str:
3004    def in_unnest_op(self, unnest: exp.Unnest) -> str:
3005        return f"(SELECT {self.sql(unnest)})"
def interval_sql(self, expression: sqlglot.expressions.Interval) -> str:
3007    def interval_sql(self, expression: exp.Interval) -> str:
3008        unit = self.sql(expression, "unit")
3009        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
3010            unit = self.TIME_PART_SINGULARS.get(unit, unit)
3011        unit = f" {unit}" if unit else ""
3012
3013        if self.SINGLE_STRING_INTERVAL:
3014            this = expression.this.name if expression.this else ""
3015            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
3016
3017        this = self.sql(expression, "this")
3018        if this:
3019            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
3020            this = f" {this}" if unwrapped else f" ({this})"
3021
3022        return f"INTERVAL{this}{unit}"
def return_sql(self, expression: sqlglot.expressions.Return) -> str:
3024    def return_sql(self, expression: exp.Return) -> str:
3025        return f"RETURN {self.sql(expression, 'this')}"
def reference_sql(self, expression: sqlglot.expressions.Reference) -> str:
3027    def reference_sql(self, expression: exp.Reference) -> str:
3028        this = self.sql(expression, "this")
3029        expressions = self.expressions(expression, flat=True)
3030        expressions = f"({expressions})" if expressions else ""
3031        options = self.expressions(expression, key="options", flat=True, sep=" ")
3032        options = f" {options}" if options else ""
3033        return f"REFERENCES {this}{expressions}{options}"
def anonymous_sql(self, expression: sqlglot.expressions.Anonymous) -> str:
3035    def anonymous_sql(self, expression: exp.Anonymous) -> str:
3036        # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive
3037        parent = expression.parent
3038        is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression
3039        return self.func(
3040            self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified
3041        )
def paren_sql(self, expression: sqlglot.expressions.Paren) -> str:
3043    def paren_sql(self, expression: exp.Paren) -> str:
3044        sql = self.seg(self.indent(self.sql(expression, "this")), sep="")
3045        return f"({sql}{self.seg(')', sep='')}"
def neg_sql(self, expression: sqlglot.expressions.Neg) -> str:
3047    def neg_sql(self, expression: exp.Neg) -> str:
3048        # This makes sure we don't convert "- - 5" to "--5", which is a comment
3049        this_sql = self.sql(expression, "this")
3050        sep = " " if this_sql[0] == "-" else ""
3051        return f"-{sep}{this_sql}"
def not_sql(self, expression: sqlglot.expressions.Not) -> str:
3053    def not_sql(self, expression: exp.Not) -> str:
3054        return f"NOT {self.sql(expression, 'this')}"
def alias_sql(self, expression: sqlglot.expressions.Alias) -> str:
3056    def alias_sql(self, expression: exp.Alias) -> str:
3057        alias = self.sql(expression, "alias")
3058        alias = f" AS {alias}" if alias else ""
3059        return f"{self.sql(expression, 'this')}{alias}"
def pivotalias_sql(self, expression: sqlglot.expressions.PivotAlias) -> str:
3061    def pivotalias_sql(self, expression: exp.PivotAlias) -> str:
3062        alias = expression.args["alias"]
3063
3064        identifier_alias = isinstance(alias, exp.Identifier)
3065        literal_alias = isinstance(alias, exp.Literal)
3066
3067        if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
3068            alias.replace(exp.Literal.string(alias.output_name))
3069        elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
3070            alias.replace(exp.to_identifier(alias.output_name))
3071
3072        return self.alias_sql(expression)
def aliases_sql(self, expression: sqlglot.expressions.Aliases) -> str:
3074    def aliases_sql(self, expression: exp.Aliases) -> str:
3075        return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})"
def atindex_sql(self, expression: sqlglot.expressions.AtTimeZone) -> str:
3077    def atindex_sql(self, expression: exp.AtTimeZone) -> str:
3078        this = self.sql(expression, "this")
3079        index = self.sql(expression, "expression")
3080        return f"{this} AT {index}"
def attimezone_sql(self, expression: sqlglot.expressions.AtTimeZone) -> str:
3082    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
3083        this = self.sql(expression, "this")
3084        zone = self.sql(expression, "zone")
3085        return f"{this} AT TIME ZONE {zone}"
def fromtimezone_sql(self, expression: sqlglot.expressions.FromTimeZone) -> str:
3087    def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str:
3088        this = self.sql(expression, "this")
3089        zone = self.sql(expression, "zone")
3090        return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'"
def add_sql(self, expression: sqlglot.expressions.Add) -> str:
3092    def add_sql(self, expression: exp.Add) -> str:
3093        return self.binary(expression, "+")
def and_sql( self, expression: sqlglot.expressions.And, stack: Optional[List[str | sqlglot.expressions.Expression]] = None) -> str:
3095    def and_sql(
3096        self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None
3097    ) -> str:
3098        return self.connector_sql(expression, "AND", stack)
def or_sql( self, expression: sqlglot.expressions.Or, stack: Optional[List[str | sqlglot.expressions.Expression]] = None) -> str:
3100    def or_sql(
3101        self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None
3102    ) -> str:
3103        return self.connector_sql(expression, "OR", stack)
def xor_sql( self, expression: sqlglot.expressions.Xor, stack: Optional[List[str | sqlglot.expressions.Expression]] = None) -> str:
3105    def xor_sql(
3106        self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None
3107    ) -> str:
3108        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:
3110    def connector_sql(
3111        self,
3112        expression: exp.Connector,
3113        op: str,
3114        stack: t.Optional[t.List[str | exp.Expression]] = None,
3115    ) -> str:
3116        if stack is not None:
3117            if expression.expressions:
3118                stack.append(self.expressions(expression, sep=f" {op} "))
3119            else:
3120                stack.append(expression.right)
3121                if expression.comments and self.comments:
3122                    for comment in expression.comments:
3123                        if comment:
3124                            op += f" /*{self.pad_comment(comment)}*/"
3125                stack.extend((op, expression.left))
3126            return op
3127
3128        stack = [expression]
3129        sqls: t.List[str] = []
3130        ops = set()
3131
3132        while stack:
3133            node = stack.pop()
3134            if isinstance(node, exp.Connector):
3135                ops.add(getattr(self, f"{node.key}_sql")(node, stack))
3136            else:
3137                sql = self.sql(node)
3138                if sqls and sqls[-1] in ops:
3139                    sqls[-1] += f" {sql}"
3140                else:
3141                    sqls.append(sql)
3142
3143        sep = "\n" if self.pretty and self.too_wide(sqls) else " "
3144        return sep.join(sqls)
def bitwiseand_sql(self, expression: sqlglot.expressions.BitwiseAnd) -> str:
3146    def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str:
3147        return self.binary(expression, "&")
def bitwiseleftshift_sql(self, expression: sqlglot.expressions.BitwiseLeftShift) -> str:
3149    def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str:
3150        return self.binary(expression, "<<")
def bitwisenot_sql(self, expression: sqlglot.expressions.BitwiseNot) -> str:
3152    def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str:
3153        return f"~{self.sql(expression, 'this')}"
def bitwiseor_sql(self, expression: sqlglot.expressions.BitwiseOr) -> str:
3155    def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str:
3156        return self.binary(expression, "|")
def bitwiserightshift_sql(self, expression: sqlglot.expressions.BitwiseRightShift) -> str:
3158    def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str:
3159        return self.binary(expression, ">>")
def bitwisexor_sql(self, expression: sqlglot.expressions.BitwiseXor) -> str:
3161    def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str:
3162        return self.binary(expression, "^")
def cast_sql( self, expression: sqlglot.expressions.Cast, safe_prefix: Optional[str] = None) -> str:
3164    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
3165        format_sql = self.sql(expression, "format")
3166        format_sql = f" FORMAT {format_sql}" if format_sql else ""
3167        to_sql = self.sql(expression, "to")
3168        to_sql = f" {to_sql}" if to_sql else ""
3169        action = self.sql(expression, "action")
3170        action = f" {action}" if action else ""
3171        return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{format_sql}{action})"
def currentdate_sql(self, expression: sqlglot.expressions.CurrentDate) -> str:
3173    def currentdate_sql(self, expression: exp.CurrentDate) -> str:
3174        zone = self.sql(expression, "this")
3175        return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE"
def collate_sql(self, expression: sqlglot.expressions.Collate) -> str:
3177    def collate_sql(self, expression: exp.Collate) -> str:
3178        if self.COLLATE_IS_FUNC:
3179            return self.function_fallback_sql(expression)
3180        return self.binary(expression, "COLLATE")
def command_sql(self, expression: sqlglot.expressions.Command) -> str:
3182    def command_sql(self, expression: exp.Command) -> str:
3183        return f"{self.sql(expression, 'this')} {expression.text('expression').strip()}"
def comment_sql(self, expression: sqlglot.expressions.Comment) -> str:
3185    def comment_sql(self, expression: exp.Comment) -> str:
3186        this = self.sql(expression, "this")
3187        kind = expression.args["kind"]
3188        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
3189        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
3190        expression_sql = self.sql(expression, "expression")
3191        return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"
def mergetreettlaction_sql(self, expression: sqlglot.expressions.MergeTreeTTLAction) -> str:
3193    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
3194        this = self.sql(expression, "this")
3195        delete = " DELETE" if expression.args.get("delete") else ""
3196        recompress = self.sql(expression, "recompress")
3197        recompress = f" RECOMPRESS {recompress}" if recompress else ""
3198        to_disk = self.sql(expression, "to_disk")
3199        to_disk = f" TO DISK {to_disk}" if to_disk else ""
3200        to_volume = self.sql(expression, "to_volume")
3201        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
3202        return f"{this}{delete}{recompress}{to_disk}{to_volume}"
def mergetreettl_sql(self, expression: sqlglot.expressions.MergeTreeTTL) -> str:
3204    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
3205        where = self.sql(expression, "where")
3206        group = self.sql(expression, "group")
3207        aggregates = self.expressions(expression, key="aggregates")
3208        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
3209
3210        if not (where or group or aggregates) and len(expression.expressions) == 1:
3211            return f"TTL {self.expressions(expression, flat=True)}"
3212
3213        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"
def transaction_sql(self, expression: sqlglot.expressions.Transaction) -> str:
3215    def transaction_sql(self, expression: exp.Transaction) -> str:
3216        return "BEGIN"
def commit_sql(self, expression: sqlglot.expressions.Commit) -> str:
3218    def commit_sql(self, expression: exp.Commit) -> str:
3219        chain = expression.args.get("chain")
3220        if chain is not None:
3221            chain = " AND CHAIN" if chain else " AND NO CHAIN"
3222
3223        return f"COMMIT{chain or ''}"
def rollback_sql(self, expression: sqlglot.expressions.Rollback) -> str:
3225    def rollback_sql(self, expression: exp.Rollback) -> str:
3226        savepoint = expression.args.get("savepoint")
3227        savepoint = f" TO {savepoint}" if savepoint else ""
3228        return f"ROLLBACK{savepoint}"
def altercolumn_sql(self, expression: sqlglot.expressions.AlterColumn) -> str:
3230    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
3231        this = self.sql(expression, "this")
3232
3233        dtype = self.sql(expression, "dtype")
3234        if dtype:
3235            collate = self.sql(expression, "collate")
3236            collate = f" COLLATE {collate}" if collate else ""
3237            using = self.sql(expression, "using")
3238            using = f" USING {using}" if using else ""
3239            return f"ALTER COLUMN {this} SET DATA TYPE {dtype}{collate}{using}"
3240
3241        default = self.sql(expression, "default")
3242        if default:
3243            return f"ALTER COLUMN {this} SET DEFAULT {default}"
3244
3245        comment = self.sql(expression, "comment")
3246        if comment:
3247            return f"ALTER COLUMN {this} COMMENT {comment}"
3248
3249        allow_null = expression.args.get("allow_null")
3250        drop = expression.args.get("drop")
3251
3252        if not drop and not allow_null:
3253            self.unsupported("Unsupported ALTER COLUMN syntax")
3254
3255        if allow_null is not None:
3256            keyword = "DROP" if drop else "SET"
3257            return f"ALTER COLUMN {this} {keyword} NOT NULL"
3258
3259        return f"ALTER COLUMN {this} DROP DEFAULT"
def alterdiststyle_sql(self, expression: sqlglot.expressions.AlterDistStyle) -> str:
3261    def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str:
3262        this = self.sql(expression, "this")
3263        if not isinstance(expression.this, exp.Var):
3264            this = f"KEY DISTKEY {this}"
3265        return f"ALTER DISTSTYLE {this}"
def altersortkey_sql(self, expression: sqlglot.expressions.AlterSortKey) -> str:
3267    def altersortkey_sql(self, expression: exp.AlterSortKey) -> str:
3268        compound = " COMPOUND" if expression.args.get("compound") else ""
3269        this = self.sql(expression, "this")
3270        expressions = self.expressions(expression, flat=True)
3271        expressions = f"({expressions})" if expressions else ""
3272        return f"ALTER{compound} SORTKEY {this or expressions}"
def alterrename_sql(self, expression: sqlglot.expressions.AlterRename) -> str:
3274    def alterrename_sql(self, expression: exp.AlterRename) -> str:
3275        if not self.RENAME_TABLE_WITH_DB:
3276            # Remove db from tables
3277            expression = expression.transform(
3278                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
3279            ).assert_is(exp.AlterRename)
3280        this = self.sql(expression, "this")
3281        return f"RENAME TO {this}"
def renamecolumn_sql(self, expression: sqlglot.expressions.RenameColumn) -> str:
3283    def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
3284        exists = " IF EXISTS" if expression.args.get("exists") else ""
3285        old_column = self.sql(expression, "this")
3286        new_column = self.sql(expression, "to")
3287        return f"RENAME COLUMN{exists} {old_column} TO {new_column}"
def alterset_sql(self, expression: sqlglot.expressions.AlterSet) -> str:
3289    def alterset_sql(self, expression: exp.AlterSet) -> str:
3290        exprs = self.expressions(expression, flat=True)
3291        return f"SET {exprs}"
def alter_sql(self, expression: sqlglot.expressions.Alter) -> str:
3293    def alter_sql(self, expression: exp.Alter) -> str:
3294        actions = expression.args["actions"]
3295
3296        if isinstance(actions[0], exp.ColumnDef):
3297            actions = self.add_column_sql(expression)
3298        elif isinstance(actions[0], exp.Schema):
3299            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
3300        elif isinstance(actions[0], exp.Delete):
3301            actions = self.expressions(expression, key="actions", flat=True)
3302        elif isinstance(actions[0], exp.Query):
3303            actions = "AS " + self.expressions(expression, key="actions")
3304        else:
3305            actions = self.expressions(expression, key="actions", flat=True)
3306
3307        exists = " IF EXISTS" if expression.args.get("exists") else ""
3308        on_cluster = self.sql(expression, "cluster")
3309        on_cluster = f" {on_cluster}" if on_cluster else ""
3310        only = " ONLY" if expression.args.get("only") else ""
3311        options = self.expressions(expression, key="options")
3312        options = f", {options}" if options else ""
3313        kind = self.sql(expression, "kind")
3314        not_valid = " NOT VALID" if expression.args.get("not_valid") else ""
3315
3316        return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions}{not_valid}{options}"
def add_column_sql(self, expression: sqlglot.expressions.Alter) -> str:
3318    def add_column_sql(self, expression: exp.Alter) -> str:
3319        if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD:
3320            return self.expressions(
3321                expression,
3322                key="actions",
3323                prefix="ADD COLUMN ",
3324                skip_first=True,
3325            )
3326        return f"ADD {self.expressions(expression, key='actions', flat=True)}"
def droppartition_sql(self, expression: sqlglot.expressions.DropPartition) -> str:
3328    def droppartition_sql(self, expression: exp.DropPartition) -> str:
3329        expressions = self.expressions(expression)
3330        exists = " IF EXISTS " if expression.args.get("exists") else " "
3331        return f"DROP{exists}{expressions}"
def addconstraint_sql(self, expression: sqlglot.expressions.AddConstraint) -> str:
3333    def addconstraint_sql(self, expression: exp.AddConstraint) -> str:
3334        return f"ADD {self.expressions(expression)}"
def distinct_sql(self, expression: sqlglot.expressions.Distinct) -> str:
3336    def distinct_sql(self, expression: exp.Distinct) -> str:
3337        this = self.expressions(expression, flat=True)
3338
3339        if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1:
3340            case = exp.case()
3341            for arg in expression.expressions:
3342                case = case.when(arg.is_(exp.null()), exp.null())
3343            this = self.sql(case.else_(f"({this})"))
3344
3345        this = f" {this}" if this else ""
3346
3347        on = self.sql(expression, "on")
3348        on = f" ON {on}" if on else ""
3349        return f"DISTINCT{this}{on}"
def ignorenulls_sql(self, expression: sqlglot.expressions.IgnoreNulls) -> str:
3351    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
3352        return self._embed_ignore_nulls(expression, "IGNORE NULLS")
def respectnulls_sql(self, expression: sqlglot.expressions.RespectNulls) -> str:
3354    def respectnulls_sql(self, expression: exp.RespectNulls) -> str:
3355        return self._embed_ignore_nulls(expression, "RESPECT NULLS")
def havingmax_sql(self, expression: sqlglot.expressions.HavingMax) -> str:
3357    def havingmax_sql(self, expression: exp.HavingMax) -> str:
3358        this_sql = self.sql(expression, "this")
3359        expression_sql = self.sql(expression, "expression")
3360        kind = "MAX" if expression.args.get("max") else "MIN"
3361        return f"{this_sql} HAVING {kind} {expression_sql}"
def intdiv_sql(self, expression: sqlglot.expressions.IntDiv) -> str:
3363    def intdiv_sql(self, expression: exp.IntDiv) -> str:
3364        return self.sql(
3365            exp.Cast(
3366                this=exp.Div(this=expression.this, expression=expression.expression),
3367                to=exp.DataType(this=exp.DataType.Type.INT),
3368            )
3369        )
def dpipe_sql(self, expression: sqlglot.expressions.DPipe) -> str:
3371    def dpipe_sql(self, expression: exp.DPipe) -> str:
3372        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
3373            return self.func(
3374                "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten())
3375            )
3376        return self.binary(expression, "||")
def div_sql(self, expression: sqlglot.expressions.Div) -> str:
3378    def div_sql(self, expression: exp.Div) -> str:
3379        l, r = expression.left, expression.right
3380
3381        if not self.dialect.SAFE_DIVISION and expression.args.get("safe"):
3382            r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0)))
3383
3384        if self.dialect.TYPED_DIVISION and not expression.args.get("typed"):
3385            if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES):
3386                l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE))
3387
3388        elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"):
3389            if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES):
3390                return self.sql(
3391                    exp.cast(
3392                        l / r,
3393                        to=exp.DataType.Type.BIGINT,
3394                    )
3395                )
3396
3397        return self.binary(expression, "/")
def overlaps_sql(self, expression: sqlglot.expressions.Overlaps) -> str:
3399    def overlaps_sql(self, expression: exp.Overlaps) -> str:
3400        return self.binary(expression, "OVERLAPS")
def distance_sql(self, expression: sqlglot.expressions.Distance) -> str:
3402    def distance_sql(self, expression: exp.Distance) -> str:
3403        return self.binary(expression, "<->")
def dot_sql(self, expression: sqlglot.expressions.Dot) -> str:
3405    def dot_sql(self, expression: exp.Dot) -> str:
3406        return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}"
def eq_sql(self, expression: sqlglot.expressions.EQ) -> str:
3408    def eq_sql(self, expression: exp.EQ) -> str:
3409        return self.binary(expression, "=")
def propertyeq_sql(self, expression: sqlglot.expressions.PropertyEQ) -> str:
3411    def propertyeq_sql(self, expression: exp.PropertyEQ) -> str:
3412        return self.binary(expression, ":=")
def escape_sql(self, expression: sqlglot.expressions.Escape) -> str:
3414    def escape_sql(self, expression: exp.Escape) -> str:
3415        return self.binary(expression, "ESCAPE")
def glob_sql(self, expression: sqlglot.expressions.Glob) -> str:
3417    def glob_sql(self, expression: exp.Glob) -> str:
3418        return self.binary(expression, "GLOB")
def gt_sql(self, expression: sqlglot.expressions.GT) -> str:
3420    def gt_sql(self, expression: exp.GT) -> str:
3421        return self.binary(expression, ">")
def gte_sql(self, expression: sqlglot.expressions.GTE) -> str:
3423    def gte_sql(self, expression: exp.GTE) -> str:
3424        return self.binary(expression, ">=")
def ilike_sql(self, expression: sqlglot.expressions.ILike) -> str:
3426    def ilike_sql(self, expression: exp.ILike) -> str:
3427        return self.binary(expression, "ILIKE")
def ilikeany_sql(self, expression: sqlglot.expressions.ILikeAny) -> str:
3429    def ilikeany_sql(self, expression: exp.ILikeAny) -> str:
3430        return self.binary(expression, "ILIKE ANY")
def is_sql(self, expression: sqlglot.expressions.Is) -> str:
3432    def is_sql(self, expression: exp.Is) -> str:
3433        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
3434            return self.sql(
3435                expression.this if expression.expression.this else exp.not_(expression.this)
3436            )
3437        return self.binary(expression, "IS")
def like_sql(self, expression: sqlglot.expressions.Like) -> str:
3439    def like_sql(self, expression: exp.Like) -> str:
3440        return self.binary(expression, "LIKE")
def likeany_sql(self, expression: sqlglot.expressions.LikeAny) -> str:
3442    def likeany_sql(self, expression: exp.LikeAny) -> str:
3443        return self.binary(expression, "LIKE ANY")
def similarto_sql(self, expression: sqlglot.expressions.SimilarTo) -> str:
3445    def similarto_sql(self, expression: exp.SimilarTo) -> str:
3446        return self.binary(expression, "SIMILAR TO")
def lt_sql(self, expression: sqlglot.expressions.LT) -> str:
3448    def lt_sql(self, expression: exp.LT) -> str:
3449        return self.binary(expression, "<")
def lte_sql(self, expression: sqlglot.expressions.LTE) -> str:
3451    def lte_sql(self, expression: exp.LTE) -> str:
3452        return self.binary(expression, "<=")
def mod_sql(self, expression: sqlglot.expressions.Mod) -> str:
3454    def mod_sql(self, expression: exp.Mod) -> str:
3455        return self.binary(expression, "%")
def mul_sql(self, expression: sqlglot.expressions.Mul) -> str:
3457    def mul_sql(self, expression: exp.Mul) -> str:
3458        return self.binary(expression, "*")
def neq_sql(self, expression: sqlglot.expressions.NEQ) -> str:
3460    def neq_sql(self, expression: exp.NEQ) -> str:
3461        return self.binary(expression, "<>")
def nullsafeeq_sql(self, expression: sqlglot.expressions.NullSafeEQ) -> str:
3463    def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str:
3464        return self.binary(expression, "IS NOT DISTINCT FROM")
def nullsafeneq_sql(self, expression: sqlglot.expressions.NullSafeNEQ) -> str:
3466    def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str:
3467        return self.binary(expression, "IS DISTINCT FROM")
def slice_sql(self, expression: sqlglot.expressions.Slice) -> str:
3469    def slice_sql(self, expression: exp.Slice) -> str:
3470        return self.binary(expression, ":")
def sub_sql(self, expression: sqlglot.expressions.Sub) -> str:
3472    def sub_sql(self, expression: exp.Sub) -> str:
3473        return self.binary(expression, "-")
def trycast_sql(self, expression: sqlglot.expressions.TryCast) -> str:
3475    def trycast_sql(self, expression: exp.TryCast) -> str:
3476        return self.cast_sql(expression, safe_prefix="TRY_")
def try_sql(self, expression: sqlglot.expressions.Try) -> str:
3478    def try_sql(self, expression: exp.Try) -> str:
3479        if not self.TRY_SUPPORTED:
3480            self.unsupported("Unsupported TRY function")
3481            return self.sql(expression, "this")
3482
3483        return self.func("TRY", expression.this)
def log_sql(self, expression: sqlglot.expressions.Log) -> str:
3485    def log_sql(self, expression: exp.Log) -> str:
3486        this = expression.this
3487        expr = expression.expression
3488
3489        if self.dialect.LOG_BASE_FIRST is False:
3490            this, expr = expr, this
3491        elif self.dialect.LOG_BASE_FIRST is None and expr:
3492            if this.name in ("2", "10"):
3493                return self.func(f"LOG{this.name}", expr)
3494
3495            self.unsupported(f"Unsupported logarithm with base {self.sql(this)}")
3496
3497        return self.func("LOG", this, expr)
def use_sql(self, expression: sqlglot.expressions.Use) -> str:
3499    def use_sql(self, expression: exp.Use) -> str:
3500        kind = self.sql(expression, "kind")
3501        kind = f" {kind}" if kind else ""
3502        this = self.sql(expression, "this")
3503        this = f" {this}" if this else ""
3504        return f"USE{kind}{this}"
def binary(self, expression: sqlglot.expressions.Binary, op: str) -> str:
3506    def binary(self, expression: exp.Binary, op: str) -> str:
3507        sqls: t.List[str] = []
3508        stack: t.List[t.Union[str, exp.Expression]] = [expression]
3509        binary_type = type(expression)
3510
3511        while stack:
3512            node = stack.pop()
3513
3514            if type(node) is binary_type:
3515                op_func = node.args.get("operator")
3516                if op_func:
3517                    op = f"OPERATOR({self.sql(op_func)})"
3518
3519                stack.append(node.right)
3520                stack.append(f" {self.maybe_comment(op, comments=node.comments)} ")
3521                stack.append(node.left)
3522            else:
3523                sqls.append(self.sql(node))
3524
3525        return "".join(sqls)
def function_fallback_sql(self, expression: sqlglot.expressions.Func) -> str:
3527    def function_fallback_sql(self, expression: exp.Func) -> str:
3528        args = []
3529
3530        for key in expression.arg_types:
3531            arg_value = expression.args.get(key)
3532
3533            if isinstance(arg_value, list):
3534                for value in arg_value:
3535                    args.append(value)
3536            elif arg_value is not None:
3537                args.append(arg_value)
3538
3539        if self.dialect.PRESERVE_ORIGINAL_NAMES:
3540            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
3541        else:
3542            name = expression.sql_name()
3543
3544        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:
3546    def func(
3547        self,
3548        name: str,
3549        *args: t.Optional[exp.Expression | str],
3550        prefix: str = "(",
3551        suffix: str = ")",
3552        normalize: bool = True,
3553    ) -> str:
3554        name = self.normalize_func(name) if normalize else name
3555        return f"{name}{prefix}{self.format_args(*args)}{suffix}"
def format_args( self, *args: Union[str, sqlglot.expressions.Expression, NoneType], sep: str = ', ') -> str:
3557    def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str:
3558        arg_sqls = tuple(
3559            self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool)
3560        )
3561        if self.pretty and self.too_wide(arg_sqls):
3562            return self.indent(
3563                "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True
3564            )
3565        return sep.join(arg_sqls)
def too_wide(self, args: Iterable) -> bool:
3567    def too_wide(self, args: t.Iterable) -> bool:
3568        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]:
3570    def format_time(
3571        self,
3572        expression: exp.Expression,
3573        inverse_time_mapping: t.Optional[t.Dict[str, str]] = None,
3574        inverse_time_trie: t.Optional[t.Dict] = None,
3575    ) -> t.Optional[str]:
3576        return format_time(
3577            self.sql(expression, "format"),
3578            inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING,
3579            inverse_time_trie or self.dialect.INVERSE_TIME_TRIE,
3580        )
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:
3582    def expressions(
3583        self,
3584        expression: t.Optional[exp.Expression] = None,
3585        key: t.Optional[str] = None,
3586        sqls: t.Optional[t.Collection[str | exp.Expression]] = None,
3587        flat: bool = False,
3588        indent: bool = True,
3589        skip_first: bool = False,
3590        skip_last: bool = False,
3591        sep: str = ", ",
3592        prefix: str = "",
3593        dynamic: bool = False,
3594        new_line: bool = False,
3595    ) -> str:
3596        expressions = expression.args.get(key or "expressions") if expression else sqls
3597
3598        if not expressions:
3599            return ""
3600
3601        if flat:
3602            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
3603
3604        num_sqls = len(expressions)
3605        result_sqls = []
3606
3607        for i, e in enumerate(expressions):
3608            sql = self.sql(e, comment=False)
3609            if not sql:
3610                continue
3611
3612            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
3613
3614            if self.pretty:
3615                if self.leading_comma:
3616                    result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}")
3617                else:
3618                    result_sqls.append(
3619                        f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}"
3620                    )
3621            else:
3622                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
3623
3624        if self.pretty and (not dynamic or self.too_wide(result_sqls)):
3625            if new_line:
3626                result_sqls.insert(0, "")
3627                result_sqls.append("")
3628            result_sql = "\n".join(s.rstrip() for s in result_sqls)
3629        else:
3630            result_sql = "".join(result_sqls)
3631
3632        return (
3633            self.indent(result_sql, skip_first=skip_first, skip_last=skip_last)
3634            if indent
3635            else result_sql
3636        )
def op_expressions( self, op: str, expression: sqlglot.expressions.Expression, flat: bool = False) -> str:
3638    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
3639        flat = flat or isinstance(expression.parent, exp.Properties)
3640        expressions_sql = self.expressions(expression, flat=flat)
3641        if flat:
3642            return f"{op} {expressions_sql}"
3643        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"
def naked_property(self, expression: sqlglot.expressions.Property) -> str:
3645    def naked_property(self, expression: exp.Property) -> str:
3646        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
3647        if not property_name:
3648            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
3649        return f"{property_name} {self.sql(expression, 'this')}"
def tag_sql(self, expression: sqlglot.expressions.Tag) -> str:
3651    def tag_sql(self, expression: exp.Tag) -> str:
3652        return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}"
def token_sql(self, token_type: sqlglot.tokens.TokenType) -> str:
3654    def token_sql(self, token_type: TokenType) -> str:
3655        return self.TOKEN_MAPPING.get(token_type, token_type.name)
def userdefinedfunction_sql(self, expression: sqlglot.expressions.UserDefinedFunction) -> str:
3657    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
3658        this = self.sql(expression, "this")
3659        expressions = self.no_identify(self.expressions, expression)
3660        expressions = (
3661            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
3662        )
3663        return f"{this}{expressions}" if expressions.strip() != "" else this
def joinhint_sql(self, expression: sqlglot.expressions.JoinHint) -> str:
3665    def joinhint_sql(self, expression: exp.JoinHint) -> str:
3666        this = self.sql(expression, "this")
3667        expressions = self.expressions(expression, flat=True)
3668        return f"{this}({expressions})"
def kwarg_sql(self, expression: sqlglot.expressions.Kwarg) -> str:
3670    def kwarg_sql(self, expression: exp.Kwarg) -> str:
3671        return self.binary(expression, "=>")
def when_sql(self, expression: sqlglot.expressions.When) -> str:
3673    def when_sql(self, expression: exp.When) -> str:
3674        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
3675        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
3676        condition = self.sql(expression, "condition")
3677        condition = f" AND {condition}" if condition else ""
3678
3679        then_expression = expression.args.get("then")
3680        if isinstance(then_expression, exp.Insert):
3681            this = self.sql(then_expression, "this")
3682            this = f"INSERT {this}" if this else "INSERT"
3683            then = self.sql(then_expression, "expression")
3684            then = f"{this} VALUES {then}" if then else this
3685        elif isinstance(then_expression, exp.Update):
3686            if isinstance(then_expression.args.get("expressions"), exp.Star):
3687                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
3688            else:
3689                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
3690        else:
3691            then = self.sql(then_expression)
3692        return f"WHEN {matched}{source}{condition} THEN {then}"
def merge_sql(self, expression: sqlglot.expressions.Merge) -> str:
3694    def merge_sql(self, expression: exp.Merge) -> str:
3695        table = expression.this
3696        table_alias = ""
3697
3698        hints = table.args.get("hints")
3699        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
3700            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
3701            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
3702
3703        this = self.sql(table)
3704        using = f"USING {self.sql(expression, 'using')}"
3705        on = f"ON {self.sql(expression, 'on')}"
3706        expressions = self.expressions(expression, sep=" ", indent=False)
3707        returning = self.sql(expression, "returning")
3708        if returning:
3709            expressions = f"{expressions}{returning}"
3710
3711        sep = self.sep()
3712
3713        return self.prepend_ctes(
3714            expression,
3715            f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{expressions}",
3716        )
@unsupported_args('format')
def tochar_sql(self, expression: sqlglot.expressions.ToChar) -> str:
3718    @unsupported_args("format")
3719    def tochar_sql(self, expression: exp.ToChar) -> str:
3720        return self.sql(exp.cast(expression.this, exp.DataType.Type.TEXT))
def tonumber_sql(self, expression: sqlglot.expressions.ToNumber) -> str:
3722    def tonumber_sql(self, expression: exp.ToNumber) -> str:
3723        if not self.SUPPORTS_TO_NUMBER:
3724            self.unsupported("Unsupported TO_NUMBER function")
3725            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
3726
3727        fmt = expression.args.get("format")
3728        if not fmt:
3729            self.unsupported("Conversion format is required for TO_NUMBER")
3730            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
3731
3732        return self.func("TO_NUMBER", expression.this, fmt)
def dictproperty_sql(self, expression: sqlglot.expressions.DictProperty) -> str:
3734    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
3735        this = self.sql(expression, "this")
3736        kind = self.sql(expression, "kind")
3737        settings_sql = self.expressions(expression, key="settings", sep=" ")
3738        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
3739        return f"{this}({kind}{args})"
def dictrange_sql(self, expression: sqlglot.expressions.DictRange) -> str:
3741    def dictrange_sql(self, expression: exp.DictRange) -> str:
3742        this = self.sql(expression, "this")
3743        max = self.sql(expression, "max")
3744        min = self.sql(expression, "min")
3745        return f"{this}(MIN {min} MAX {max})"
def dictsubproperty_sql(self, expression: sqlglot.expressions.DictSubProperty) -> str:
3747    def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str:
3748        return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}"
def duplicatekeyproperty_sql(self, expression: sqlglot.expressions.DuplicateKeyProperty) -> str:
3750    def duplicatekeyproperty_sql(self, expression: exp.DuplicateKeyProperty) -> str:
3751        return f"DUPLICATE KEY ({self.expressions(expression, flat=True)})"
def distributedbyproperty_sql(self, expression: sqlglot.expressions.DistributedByProperty) -> str:
3754    def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str:
3755        expressions = self.expressions(expression, flat=True)
3756        expressions = f" {self.wrap(expressions)}" if expressions else ""
3757        buckets = self.sql(expression, "buckets")
3758        kind = self.sql(expression, "kind")
3759        buckets = f" BUCKETS {buckets}" if buckets else ""
3760        order = self.sql(expression, "order")
3761        return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}"
def oncluster_sql(self, expression: sqlglot.expressions.OnCluster) -> str:
3763    def oncluster_sql(self, expression: exp.OnCluster) -> str:
3764        return ""
def clusteredbyproperty_sql(self, expression: sqlglot.expressions.ClusteredByProperty) -> str:
3766    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
3767        expressions = self.expressions(expression, key="expressions", flat=True)
3768        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
3769        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
3770        buckets = self.sql(expression, "buckets")
3771        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"
def anyvalue_sql(self, expression: sqlglot.expressions.AnyValue) -> str:
3773    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
3774        this = self.sql(expression, "this")
3775        having = self.sql(expression, "having")
3776
3777        if having:
3778            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
3779
3780        return self.func("ANY_VALUE", this)
def querytransform_sql(self, expression: sqlglot.expressions.QueryTransform) -> str:
3782    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
3783        transform = self.func("TRANSFORM", *expression.expressions)
3784        row_format_before = self.sql(expression, "row_format_before")
3785        row_format_before = f" {row_format_before}" if row_format_before else ""
3786        record_writer = self.sql(expression, "record_writer")
3787        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
3788        using = f" USING {self.sql(expression, 'command_script')}"
3789        schema = self.sql(expression, "schema")
3790        schema = f" AS {schema}" if schema else ""
3791        row_format_after = self.sql(expression, "row_format_after")
3792        row_format_after = f" {row_format_after}" if row_format_after else ""
3793        record_reader = self.sql(expression, "record_reader")
3794        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
3795        return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}"
def indexconstraintoption_sql(self, expression: sqlglot.expressions.IndexConstraintOption) -> str:
3797    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
3798        key_block_size = self.sql(expression, "key_block_size")
3799        if key_block_size:
3800            return f"KEY_BLOCK_SIZE = {key_block_size}"
3801
3802        using = self.sql(expression, "using")
3803        if using:
3804            return f"USING {using}"
3805
3806        parser = self.sql(expression, "parser")
3807        if parser:
3808            return f"WITH PARSER {parser}"
3809
3810        comment = self.sql(expression, "comment")
3811        if comment:
3812            return f"COMMENT {comment}"
3813
3814        visible = expression.args.get("visible")
3815        if visible is not None:
3816            return "VISIBLE" if visible else "INVISIBLE"
3817
3818        engine_attr = self.sql(expression, "engine_attr")
3819        if engine_attr:
3820            return f"ENGINE_ATTRIBUTE = {engine_attr}"
3821
3822        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
3823        if secondary_engine_attr:
3824            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
3825
3826        self.unsupported("Unsupported index constraint option.")
3827        return ""
def checkcolumnconstraint_sql(self, expression: sqlglot.expressions.CheckColumnConstraint) -> str:
3829    def checkcolumnconstraint_sql(self, expression: exp.CheckColumnConstraint) -> str:
3830        enforced = " ENFORCED" if expression.args.get("enforced") else ""
3831        return f"CHECK ({self.sql(expression, 'this')}){enforced}"
def indexcolumnconstraint_sql(self, expression: sqlglot.expressions.IndexColumnConstraint) -> str:
3833    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
3834        kind = self.sql(expression, "kind")
3835        kind = f"{kind} INDEX" if kind else "INDEX"
3836        this = self.sql(expression, "this")
3837        this = f" {this}" if this else ""
3838        index_type = self.sql(expression, "index_type")
3839        index_type = f" USING {index_type}" if index_type else ""
3840        expressions = self.expressions(expression, flat=True)
3841        expressions = f" ({expressions})" if expressions else ""
3842        options = self.expressions(expression, key="options", sep=" ")
3843        options = f" {options}" if options else ""
3844        return f"{kind}{this}{index_type}{expressions}{options}"
def nvl2_sql(self, expression: sqlglot.expressions.Nvl2) -> str:
3846    def nvl2_sql(self, expression: exp.Nvl2) -> str:
3847        if self.NVL2_SUPPORTED:
3848            return self.function_fallback_sql(expression)
3849
3850        case = exp.Case().when(
3851            expression.this.is_(exp.null()).not_(copy=False),
3852            expression.args["true"],
3853            copy=False,
3854        )
3855        else_cond = expression.args.get("false")
3856        if else_cond:
3857            case.else_(else_cond, copy=False)
3858
3859        return self.sql(case)
def comprehension_sql(self, expression: sqlglot.expressions.Comprehension) -> str:
3861    def comprehension_sql(self, expression: exp.Comprehension) -> str:
3862        this = self.sql(expression, "this")
3863        expr = self.sql(expression, "expression")
3864        iterator = self.sql(expression, "iterator")
3865        condition = self.sql(expression, "condition")
3866        condition = f" IF {condition}" if condition else ""
3867        return f"{this} FOR {expr} IN {iterator}{condition}"
def columnprefix_sql(self, expression: sqlglot.expressions.ColumnPrefix) -> str:
3869    def columnprefix_sql(self, expression: exp.ColumnPrefix) -> str:
3870        return f"{self.sql(expression, 'this')}({self.sql(expression, 'expression')})"
def opclass_sql(self, expression: sqlglot.expressions.Opclass) -> str:
3872    def opclass_sql(self, expression: exp.Opclass) -> str:
3873        return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}"
def predict_sql(self, expression: sqlglot.expressions.Predict) -> str:
3875    def predict_sql(self, expression: exp.Predict) -> str:
3876        model = self.sql(expression, "this")
3877        model = f"MODEL {model}"
3878        table = self.sql(expression, "expression")
3879        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
3880        parameters = self.sql(expression, "params_struct")
3881        return self.func("PREDICT", model, table, parameters or None)
def forin_sql(self, expression: sqlglot.expressions.ForIn) -> str:
3883    def forin_sql(self, expression: exp.ForIn) -> str:
3884        this = self.sql(expression, "this")
3885        expression_sql = self.sql(expression, "expression")
3886        return f"FOR {this} DO {expression_sql}"
def refresh_sql(self, expression: sqlglot.expressions.Refresh) -> str:
3888    def refresh_sql(self, expression: exp.Refresh) -> str:
3889        this = self.sql(expression, "this")
3890        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
3891        return f"REFRESH {table}{this}"
def toarray_sql(self, expression: sqlglot.expressions.ToArray) -> str:
3893    def toarray_sql(self, expression: exp.ToArray) -> str:
3894        arg = expression.this
3895        if not arg.type:
3896            from sqlglot.optimizer.annotate_types import annotate_types
3897
3898            arg = annotate_types(arg)
3899
3900        if arg.is_type(exp.DataType.Type.ARRAY):
3901            return self.sql(arg)
3902
3903        cond_for_null = arg.is_(exp.null())
3904        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:
3906    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
3907        this = expression.this
3908        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
3909            return self.sql(this)
3910
3911        return self.sql(exp.cast(this, exp.DataType.Type.TIME))
def tsordstotimestamp_sql(self, expression: sqlglot.expressions.TsOrDsToTimestamp) -> str:
3913    def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str:
3914        this = expression.this
3915        if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP):
3916            return self.sql(this)
3917
3918        return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect))
def tsordstodatetime_sql(self, expression: sqlglot.expressions.TsOrDsToDatetime) -> str:
3920    def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str:
3921        this = expression.this
3922        if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME):
3923            return self.sql(this)
3924
3925        return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect))
def tsordstodate_sql(self, expression: sqlglot.expressions.TsOrDsToDate) -> str:
3927    def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:
3928        this = expression.this
3929        time_format = self.format_time(expression)
3930
3931        if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT):
3932            return self.sql(
3933                exp.cast(
3934                    exp.StrToTime(this=this, format=expression.args["format"]),
3935                    exp.DataType.Type.DATE,
3936                )
3937            )
3938
3939        if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE):
3940            return self.sql(this)
3941
3942        return self.sql(exp.cast(this, exp.DataType.Type.DATE))
def unixdate_sql(self, expression: sqlglot.expressions.UnixDate) -> str:
3944    def unixdate_sql(self, expression: exp.UnixDate) -> str:
3945        return self.sql(
3946            exp.func(
3947                "DATEDIFF",
3948                expression.this,
3949                exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE),
3950                "day",
3951            )
3952        )
def lastday_sql(self, expression: sqlglot.expressions.LastDay) -> str:
3954    def lastday_sql(self, expression: exp.LastDay) -> str:
3955        if self.LAST_DAY_SUPPORTS_DATE_PART:
3956            return self.function_fallback_sql(expression)
3957
3958        unit = expression.text("unit")
3959        if unit and unit != "MONTH":
3960            self.unsupported("Date parts are not supported in LAST_DAY.")
3961
3962        return self.func("LAST_DAY", expression.this)
def dateadd_sql(self, expression: sqlglot.expressions.DateAdd) -> str:
3964    def dateadd_sql(self, expression: exp.DateAdd) -> str:
3965        from sqlglot.dialects.dialect import unit_to_str
3966
3967        return self.func(
3968            "DATE_ADD", expression.this, expression.expression, unit_to_str(expression)
3969        )
def arrayany_sql(self, expression: sqlglot.expressions.ArrayAny) -> str:
3971    def arrayany_sql(self, expression: exp.ArrayAny) -> str:
3972        if self.CAN_IMPLEMENT_ARRAY_ANY:
3973            filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression)
3974            filtered_not_empty = exp.ArraySize(this=filtered).neq(0)
3975            original_is_empty = exp.ArraySize(this=expression.this).eq(0)
3976            return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty)))
3977
3978        from sqlglot.dialects import Dialect
3979
3980        # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect
3981        if self.dialect.__class__ != Dialect:
3982            self.unsupported("ARRAY_ANY is unsupported")
3983
3984        return self.function_fallback_sql(expression)
def struct_sql(self, expression: sqlglot.expressions.Struct) -> str:
3986    def struct_sql(self, expression: exp.Struct) -> str:
3987        expression.set(
3988            "expressions",
3989            [
3990                exp.alias_(e.expression, e.name if e.this.is_string else e.this)
3991                if isinstance(e, exp.PropertyEQ)
3992                else e
3993                for e in expression.expressions
3994            ],
3995        )
3996
3997        return self.function_fallback_sql(expression)
def partitionrange_sql(self, expression: sqlglot.expressions.PartitionRange) -> str:
3999    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
4000        low = self.sql(expression, "this")
4001        high = self.sql(expression, "expression")
4002
4003        return f"{low} TO {high}"
def truncatetable_sql(self, expression: sqlglot.expressions.TruncateTable) -> str:
4005    def truncatetable_sql(self, expression: exp.TruncateTable) -> str:
4006        target = "DATABASE" if expression.args.get("is_database") else "TABLE"
4007        tables = f" {self.expressions(expression)}"
4008
4009        exists = " IF EXISTS" if expression.args.get("exists") else ""
4010
4011        on_cluster = self.sql(expression, "cluster")
4012        on_cluster = f" {on_cluster}" if on_cluster else ""
4013
4014        identity = self.sql(expression, "identity")
4015        identity = f" {identity} IDENTITY" if identity else ""
4016
4017        option = self.sql(expression, "option")
4018        option = f" {option}" if option else ""
4019
4020        partition = self.sql(expression, "partition")
4021        partition = f" {partition}" if partition else ""
4022
4023        return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"
def convert_sql(self, expression: sqlglot.expressions.Convert) -> str:
4027    def convert_sql(self, expression: exp.Convert) -> str:
4028        to = expression.this
4029        value = expression.expression
4030        style = expression.args.get("style")
4031        safe = expression.args.get("safe")
4032        strict = expression.args.get("strict")
4033
4034        if not to or not value:
4035            return ""
4036
4037        # Retrieve length of datatype and override to default if not specified
4038        if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES:
4039            to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
4040
4041        transformed: t.Optional[exp.Expression] = None
4042        cast = exp.Cast if strict else exp.TryCast
4043
4044        # Check whether a conversion with format (T-SQL calls this 'style') is applicable
4045        if isinstance(style, exp.Literal) and style.is_int:
4046            from sqlglot.dialects.tsql import TSQL
4047
4048            style_value = style.name
4049            converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value)
4050            if not converted_style:
4051                self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}")
4052
4053            fmt = exp.Literal.string(converted_style)
4054
4055            if to.this == exp.DataType.Type.DATE:
4056                transformed = exp.StrToDate(this=value, format=fmt)
4057            elif to.this == exp.DataType.Type.DATETIME:
4058                transformed = exp.StrToTime(this=value, format=fmt)
4059            elif to.this in self.PARAMETERIZABLE_TEXT_TYPES:
4060                transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe)
4061            elif to.this == exp.DataType.Type.TEXT:
4062                transformed = exp.TimeToStr(this=value, format=fmt)
4063
4064        if not transformed:
4065            transformed = cast(this=value, to=to, safe=safe)
4066
4067        return self.sql(transformed)
def copyparameter_sql(self, expression: sqlglot.expressions.CopyParameter) -> str:
4127    def copyparameter_sql(self, expression: exp.CopyParameter) -> str:
4128        option = self.sql(expression, "this")
4129
4130        if expression.expressions:
4131            upper = option.upper()
4132
4133            # Snowflake FILE_FORMAT options are separated by whitespace
4134            sep = " " if upper == "FILE_FORMAT" else ", "
4135
4136            # Databricks copy/format options do not set their list of values with EQ
4137            op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = "
4138            values = self.expressions(expression, flat=True, sep=sep)
4139            return f"{option}{op}({values})"
4140
4141        value = self.sql(expression, "expression")
4142
4143        if not value:
4144            return option
4145
4146        op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " "
4147
4148        return f"{option}{op}{value}"
def credentials_sql(self, expression: sqlglot.expressions.Credentials) -> str:
4150    def credentials_sql(self, expression: exp.Credentials) -> str:
4151        cred_expr = expression.args.get("credentials")
4152        if isinstance(cred_expr, exp.Literal):
4153            # Redshift case: CREDENTIALS <string>
4154            credentials = self.sql(expression, "credentials")
4155            credentials = f"CREDENTIALS {credentials}" if credentials else ""
4156        else:
4157            # Snowflake case: CREDENTIALS = (...)
4158            credentials = self.expressions(expression, key="credentials", flat=True, sep=" ")
4159            credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else ""
4160
4161        storage = self.sql(expression, "storage")
4162        storage = f"STORAGE_INTEGRATION = {storage}" if storage else ""
4163
4164        encryption = self.expressions(expression, key="encryption", flat=True, sep=" ")
4165        encryption = f" ENCRYPTION = ({encryption})" if encryption else ""
4166
4167        iam_role = self.sql(expression, "iam_role")
4168        iam_role = f"IAM_ROLE {iam_role}" if iam_role else ""
4169
4170        region = self.sql(expression, "region")
4171        region = f" REGION {region}" if region else ""
4172
4173        return f"{credentials}{storage}{encryption}{iam_role}{region}"
def copy_sql(self, expression: sqlglot.expressions.Copy) -> str:
4175    def copy_sql(self, expression: exp.Copy) -> str:
4176        this = self.sql(expression, "this")
4177        this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}"
4178
4179        credentials = self.sql(expression, "credentials")
4180        credentials = self.seg(credentials) if credentials else ""
4181        kind = self.seg("FROM" if expression.args.get("kind") else "TO")
4182        files = self.expressions(expression, key="files", flat=True)
4183
4184        sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " "
4185        params = self.expressions(
4186            expression,
4187            key="params",
4188            sep=sep,
4189            new_line=True,
4190            skip_last=True,
4191            skip_first=True,
4192            indent=self.COPY_PARAMS_ARE_WRAPPED,
4193        )
4194
4195        if params:
4196            if self.COPY_PARAMS_ARE_WRAPPED:
4197                params = f" WITH ({params})"
4198            elif not self.pretty:
4199                params = f" {params}"
4200
4201        return f"COPY{this}{kind} {files}{credentials}{params}"
def semicolon_sql(self, expression: sqlglot.expressions.Semicolon) -> str:
4203    def semicolon_sql(self, expression: exp.Semicolon) -> str:
4204        return ""
def datadeletionproperty_sql(self, expression: sqlglot.expressions.DataDeletionProperty) -> str:
4206    def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str:
4207        on_sql = "ON" if expression.args.get("on") else "OFF"
4208        filter_col: t.Optional[str] = self.sql(expression, "filter_column")
4209        filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None
4210        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
4211        retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None
4212
4213        if filter_col or retention_period:
4214            on_sql = self.func("ON", filter_col, retention_period)
4215
4216        return f"DATA_DELETION={on_sql}"
def maskingpolicycolumnconstraint_sql( self, expression: sqlglot.expressions.MaskingPolicyColumnConstraint) -> str:
4218    def maskingpolicycolumnconstraint_sql(
4219        self, expression: exp.MaskingPolicyColumnConstraint
4220    ) -> str:
4221        this = self.sql(expression, "this")
4222        expressions = self.expressions(expression, flat=True)
4223        expressions = f" USING ({expressions})" if expressions else ""
4224        return f"MASKING POLICY {this}{expressions}"
def gapfill_sql(self, expression: sqlglot.expressions.GapFill) -> str:
4226    def gapfill_sql(self, expression: exp.GapFill) -> str:
4227        this = self.sql(expression, "this")
4228        this = f"TABLE {this}"
4229        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:
4231    def scope_resolution(self, rhs: str, scope_name: str) -> str:
4232        return self.func("SCOPE_RESOLUTION", scope_name or None, rhs)
def scoperesolution_sql(self, expression: sqlglot.expressions.ScopeResolution) -> str:
4234    def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str:
4235        this = self.sql(expression, "this")
4236        expr = expression.expression
4237
4238        if isinstance(expr, exp.Func):
4239            # T-SQL's CLR functions are case sensitive
4240            expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})"
4241        else:
4242            expr = self.sql(expression, "expression")
4243
4244        return self.scope_resolution(expr, this)
def parsejson_sql(self, expression: sqlglot.expressions.ParseJSON) -> str:
4246    def parsejson_sql(self, expression: exp.ParseJSON) -> str:
4247        if self.PARSE_JSON_NAME is None:
4248            return self.sql(expression.this)
4249
4250        return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression)
def rand_sql(self, expression: sqlglot.expressions.Rand) -> str:
4252    def rand_sql(self, expression: exp.Rand) -> str:
4253        lower = self.sql(expression, "lower")
4254        upper = self.sql(expression, "upper")
4255
4256        if lower and upper:
4257            return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}"
4258        return self.func("RAND", expression.this)
def changes_sql(self, expression: sqlglot.expressions.Changes) -> str:
4260    def changes_sql(self, expression: exp.Changes) -> str:
4261        information = self.sql(expression, "information")
4262        information = f"INFORMATION => {information}"
4263        at_before = self.sql(expression, "at_before")
4264        at_before = f"{self.seg('')}{at_before}" if at_before else ""
4265        end = self.sql(expression, "end")
4266        end = f"{self.seg('')}{end}" if end else ""
4267
4268        return f"CHANGES ({information}){at_before}{end}"
def pad_sql(self, expression: sqlglot.expressions.Pad) -> str:
4270    def pad_sql(self, expression: exp.Pad) -> str:
4271        prefix = "L" if expression.args.get("is_left") else "R"
4272
4273        fill_pattern = self.sql(expression, "fill_pattern") or None
4274        if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED:
4275            fill_pattern = "' '"
4276
4277        return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)
def summarize_sql(self, expression: sqlglot.expressions.Summarize) -> str:
4279    def summarize_sql(self, expression: exp.Summarize) -> str:
4280        table = " TABLE" if expression.args.get("table") else ""
4281        return f"SUMMARIZE{table} {self.sql(expression.this)}"
def explodinggenerateseries_sql(self, expression: sqlglot.expressions.ExplodingGenerateSeries) -> str:
4283    def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str:
4284        generate_series = exp.GenerateSeries(**expression.args)
4285
4286        parent = expression.parent
4287        if isinstance(parent, (exp.Alias, exp.TableAlias)):
4288            parent = parent.parent
4289
4290        if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)):
4291            return self.sql(exp.Unnest(expressions=[generate_series]))
4292
4293        if isinstance(parent, exp.Select):
4294            self.unsupported("GenerateSeries projection unnesting is not supported.")
4295
4296        return self.sql(generate_series)
def arrayconcat_sql( self, expression: sqlglot.expressions.ArrayConcat, name: str = 'ARRAY_CONCAT') -> str:
4298    def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str:
4299        exprs = expression.expressions
4300        if not self.ARRAY_CONCAT_IS_VAR_LEN:
4301            rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs)
4302        else:
4303            rhs = self.expressions(expression)
4304
4305        return self.func(name, expression.this, rhs or None)
def converttimezone_sql(self, expression: sqlglot.expressions.ConvertTimezone) -> str:
4307    def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str:
4308        if self.SUPPORTS_CONVERT_TIMEZONE:
4309            return self.function_fallback_sql(expression)
4310
4311        source_tz = expression.args.get("source_tz")
4312        target_tz = expression.args.get("target_tz")
4313        timestamp = expression.args.get("timestamp")
4314
4315        if source_tz and timestamp:
4316            timestamp = exp.AtTimeZone(
4317                this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz
4318            )
4319
4320        expr = exp.AtTimeZone(this=timestamp, zone=target_tz)
4321
4322        return self.sql(expr)
def json_sql(self, expression: sqlglot.expressions.JSON) -> str:
4324    def json_sql(self, expression: exp.JSON) -> str:
4325        this = self.sql(expression, "this")
4326        this = f" {this}" if this else ""
4327
4328        _with = expression.args.get("with")
4329
4330        if _with is None:
4331            with_sql = ""
4332        elif not _with:
4333            with_sql = " WITHOUT"
4334        else:
4335            with_sql = " WITH"
4336
4337        unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else ""
4338
4339        return f"JSON{this}{with_sql}{unique_sql}"
def jsonvalue_sql(self, expression: sqlglot.expressions.JSONValue) -> str:
4341    def jsonvalue_sql(self, expression: exp.JSONValue) -> str:
4342        def _generate_on_options(arg: t.Any) -> str:
4343            return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}"
4344
4345        path = self.sql(expression, "path")
4346        returning = self.sql(expression, "returning")
4347        returning = f" RETURNING {returning}" if returning else ""
4348
4349        on_condition = self.sql(expression, "on_condition")
4350        on_condition = f" {on_condition}" if on_condition else ""
4351
4352        return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}")
def conditionalinsert_sql(self, expression: sqlglot.expressions.ConditionalInsert) -> str:
4354    def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str:
4355        else_ = "ELSE " if expression.args.get("else_") else ""
4356        condition = self.sql(expression, "expression")
4357        condition = f"WHEN {condition} THEN " if condition else else_
4358        insert = self.sql(expression, "this")[len("INSERT") :].strip()
4359        return f"{condition}{insert}"
def multitableinserts_sql(self, expression: sqlglot.expressions.MultitableInserts) -> str:
4361    def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str:
4362        kind = self.sql(expression, "kind")
4363        expressions = self.seg(self.expressions(expression, sep=" "))
4364        res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}"
4365        return res
def oncondition_sql(self, expression: sqlglot.expressions.OnCondition) -> str:
4367    def oncondition_sql(self, expression: exp.OnCondition) -> str:
4368        # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR"
4369        empty = expression.args.get("empty")
4370        empty = (
4371            f"DEFAULT {empty} ON EMPTY"
4372            if isinstance(empty, exp.Expression)
4373            else self.sql(expression, "empty")
4374        )
4375
4376        error = expression.args.get("error")
4377        error = (
4378            f"DEFAULT {error} ON ERROR"
4379            if isinstance(error, exp.Expression)
4380            else self.sql(expression, "error")
4381        )
4382
4383        if error and empty:
4384            error = (
4385                f"{empty} {error}"
4386                if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR
4387                else f"{error} {empty}"
4388            )
4389            empty = ""
4390
4391        null = self.sql(expression, "null")
4392
4393        return f"{empty}{error}{null}"
def jsonexists_sql(self, expression: sqlglot.expressions.JSONExists) -> str:
4395    def jsonexists_sql(self, expression: exp.JSONExists) -> str:
4396        this = self.sql(expression, "this")
4397        path = self.sql(expression, "path")
4398
4399        passing = self.expressions(expression, "passing")
4400        passing = f" PASSING {passing}" if passing else ""
4401
4402        on_condition = self.sql(expression, "on_condition")
4403        on_condition = f" {on_condition}" if on_condition else ""
4404
4405        path = f"{path}{passing}{on_condition}"
4406
4407        return self.func("JSON_EXISTS", this, path)
def arrayagg_sql(self, expression: sqlglot.expressions.ArrayAgg) -> str:
4409    def arrayagg_sql(self, expression: exp.ArrayAgg) -> str:
4410        array_agg = self.function_fallback_sql(expression)
4411
4412        # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls
4413        # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB)
4414        if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"):
4415            parent = expression.parent
4416            if isinstance(parent, exp.Filter):
4417                parent_cond = parent.expression.this
4418                parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_()))
4419            else:
4420                this = expression.this
4421                # Do not add the filter if the input is not a column (e.g. literal, struct etc)
4422                if this.find(exp.Column):
4423                    # DISTINCT is already present in the agg function, do not propagate it to FILTER as well
4424                    this_sql = (
4425                        self.expressions(this)
4426                        if isinstance(this, exp.Distinct)
4427                        else self.sql(expression, "this")
4428                    )
4429
4430                    array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)"
4431
4432        return array_agg
def apply_sql(self, expression: sqlglot.expressions.Apply) -> str:
4434    def apply_sql(self, expression: exp.Apply) -> str:
4435        this = self.sql(expression, "this")
4436        expr = self.sql(expression, "expression")
4437
4438        return f"{this} APPLY({expr})"
def grant_sql(self, expression: sqlglot.expressions.Grant) -> str:
4440    def grant_sql(self, expression: exp.Grant) -> str:
4441        privileges_sql = self.expressions(expression, key="privileges", flat=True)
4442
4443        kind = self.sql(expression, "kind")
4444        kind = f" {kind}" if kind else ""
4445
4446        securable = self.sql(expression, "securable")
4447        securable = f" {securable}" if securable else ""
4448
4449        principals = self.expressions(expression, key="principals", flat=True)
4450
4451        grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else ""
4452
4453        return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}"
def grantprivilege_sql(self, expression: sqlglot.expressions.GrantPrivilege):
4455    def grantprivilege_sql(self, expression: exp.GrantPrivilege):
4456        this = self.sql(expression, "this")
4457        columns = self.expressions(expression, flat=True)
4458        columns = f"({columns})" if columns else ""
4459
4460        return f"{this}{columns}"
def grantprincipal_sql(self, expression: sqlglot.expressions.GrantPrincipal):
4462    def grantprincipal_sql(self, expression: exp.GrantPrincipal):
4463        this = self.sql(expression, "this")
4464
4465        kind = self.sql(expression, "kind")
4466        kind = f"{kind} " if kind else ""
4467
4468        return f"{kind}{this}"
def columns_sql(self, expression: sqlglot.expressions.Columns):
4470    def columns_sql(self, expression: exp.Columns):
4471        func = self.function_fallback_sql(expression)
4472        if expression.args.get("unpack"):
4473            func = f"*{func}"
4474
4475        return func
def overlay_sql(self, expression: sqlglot.expressions.Overlay):
4477    def overlay_sql(self, expression: exp.Overlay):
4478        this = self.sql(expression, "this")
4479        expr = self.sql(expression, "expression")
4480        from_sql = self.sql(expression, "from")
4481        for_sql = self.sql(expression, "for")
4482        for_sql = f" FOR {for_sql}" if for_sql else ""
4483
4484        return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})"
@unsupported_args('format')
def todouble_sql(self, expression: sqlglot.expressions.ToDouble) -> str:
4486    @unsupported_args("format")
4487    def todouble_sql(self, expression: exp.ToDouble) -> str:
4488        return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
def string_sql(self, expression: sqlglot.expressions.String) -> str:
4490    def string_sql(self, expression: exp.String) -> str:
4491        this = expression.this
4492        zone = expression.args.get("zone")
4493
4494        if zone:
4495            # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>)
4496            # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC
4497            # set for source_tz to transpile the time conversion before the STRING cast
4498            this = exp.ConvertTimezone(
4499                source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this
4500            )
4501
4502        return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR))
def median_sql(self, expression: sqlglot.expressions.Median):
4504    def median_sql(self, expression: exp.Median):
4505        if not self.SUPPORTS_MEDIAN:
4506            return self.sql(
4507                exp.PercentileCont(this=expression.this, expression=exp.Literal.number(0.5))
4508            )
4509
4510        return self.function_fallback_sql(expression)
def overflowtruncatebehavior_sql(self, expression: sqlglot.expressions.OverflowTruncateBehavior) -> str:
4512    def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str:
4513        filler = self.sql(expression, "this")
4514        filler = f" {filler}" if filler else ""
4515        with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT"
4516        return f"TRUNCATE{filler} {with_count}"
def unixseconds_sql(self, expression: sqlglot.expressions.UnixSeconds) -> str:
4518    def unixseconds_sql(self, expression: exp.UnixSeconds) -> str:
4519        if self.SUPPORTS_UNIX_SECONDS:
4520            return self.function_fallback_sql(expression)
4521
4522        start_ts = exp.cast(
4523            exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ
4524        )
4525
4526        return self.sql(
4527            exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS"))
4528        )
def arraysize_sql(self, expression: sqlglot.expressions.ArraySize) -> str:
4530    def arraysize_sql(self, expression: exp.ArraySize) -> str:
4531        dim = expression.expression
4532
4533        # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension)
4534        if dim and self.ARRAY_SIZE_DIM_REQUIRED is None:
4535            if not (dim.is_int and dim.name == "1"):
4536                self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH")
4537            dim = None
4538
4539        # If dimension is required but not specified, default initialize it
4540        if self.ARRAY_SIZE_DIM_REQUIRED and not dim:
4541            dim = exp.Literal.number(1)
4542
4543        return self.func(self.ARRAY_SIZE_NAME, expression.this, dim)
def attach_sql(self, expression: sqlglot.expressions.Attach) -> str:
4545    def attach_sql(self, expression: exp.Attach) -> str:
4546        this = self.sql(expression, "this")
4547        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
4548        expressions = self.expressions(expression)
4549        expressions = f" ({expressions})" if expressions else ""
4550
4551        return f"ATTACH{exists_sql} {this}{expressions}"
def detach_sql(self, expression: sqlglot.expressions.Detach) -> str:
4553    def detach_sql(self, expression: exp.Detach) -> str:
4554        this = self.sql(expression, "this")
4555        exists_sql = " IF EXISTS" if expression.args.get("exists") else ""
4556
4557        return f"DETACH{exists_sql} {this}"
def attachoption_sql(self, expression: sqlglot.expressions.AttachOption) -> str:
4559    def attachoption_sql(self, expression: exp.AttachOption) -> str:
4560        this = self.sql(expression, "this")
4561        value = self.sql(expression, "expression")
4562        value = f" {value}" if value else ""
4563        return f"{this}{value}"
def featuresattime_sql(self, expression: sqlglot.expressions.FeaturesAtTime) -> str:
4565    def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str:
4566        this_sql = self.sql(expression, "this")
4567        if isinstance(expression.this, exp.Table):
4568            this_sql = f"TABLE {this_sql}"
4569
4570        return self.func(
4571            "FEATURES_AT_TIME",
4572            this_sql,
4573            expression.args.get("time"),
4574            expression.args.get("num_rows"),
4575            expression.args.get("ignore_feature_nulls"),
4576        )
def watermarkcolumnconstraint_sql(self, expression: sqlglot.expressions.WatermarkColumnConstraint) -> str:
4578    def watermarkcolumnconstraint_sql(self, expression: exp.WatermarkColumnConstraint) -> str:
4579        return (
4580            f"WATERMARK FOR {self.sql(expression, 'this')} AS {self.sql(expression, 'expression')}"
4581        )
def encodeproperty_sql(self, expression: sqlglot.expressions.EncodeProperty) -> str:
4583    def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str:
4584        encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE"
4585        encode = f"{encode} {self.sql(expression, 'this')}"
4586
4587        properties = expression.args.get("properties")
4588        if properties:
4589            encode = f"{encode} {self.properties(properties)}"
4590
4591        return encode
def includeproperty_sql(self, expression: sqlglot.expressions.IncludeProperty) -> str:
4593    def includeproperty_sql(self, expression: exp.IncludeProperty) -> str:
4594        this = self.sql(expression, "this")
4595        include = f"INCLUDE {this}"
4596
4597        column_def = self.sql(expression, "column_def")
4598        if column_def:
4599            include = f"{include} {column_def}"
4600
4601        alias = self.sql(expression, "alias")
4602        if alias:
4603            include = f"{include} AS {alias}"
4604
4605        return include