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