Edit on GitHub

# sqlglot.generator

View Source

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

logger = <Logger sqlglot (WARNING)>
ESCAPED_UNICODE_RE = re.compile('\\\\(\\d+)')
UNSUPPORTED_TEMPLATE = "Argument '{}' is not supported for expression '{}' when targeting {}."
def unsupported_args( *args: Union[str, Tuple[str, str]]) -> Callable[[Callable[[~G, ~E], str]], Callable[[~G, ~E], str]]: View Source

    30def unsupported_args(
    31    *args: t.Union[str, t.Tuple[str, str]],
    32) -> t.Callable[[GeneratorMethod], GeneratorMethod]:
    33    """
    34    Decorator that can be used to mark certain args of an `Expression` subclass as unsupported.
    35    It expects a sequence of argument names or pairs of the form (argument_name, diagnostic_msg).
    36    """
    37    diagnostic_by_arg: t.Dict[str, t.Optional[str]] = {}
    38    for arg in args:
    39        if isinstance(arg, str):
    40            diagnostic_by_arg[arg] = None
    41        else:
    42            diagnostic_by_arg[arg[0]] = arg[1]
    43
    44    def decorator(func: GeneratorMethod) -> GeneratorMethod:
    45        @wraps(func)
    46        def _func(generator: G, expression: E) -> str:
    47            expression_name = expression.__class__.__name__
    48            dialect_name = generator.dialect.__class__.__name__
    49
    50            for arg_name, diagnostic in diagnostic_by_arg.items():
    51                if expression.args.get(arg_name):
    52                    diagnostic = diagnostic or UNSUPPORTED_TEMPLATE.format(
    53                        arg_name, expression_name, dialect_name
    54                    )
    55                    generator.unsupported(diagnostic)
    56
    57            return func(generator, expression)
    58
    59        return _func
    60
    61    return decorator

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

class Generator: View Source

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

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

###### Arguments:

- pretty: Whether to format the produced SQL string. Default: False.
- identify: Determines when an identifier should be quoted. Possible values are: False (default): Never quote, except in cases where it's mandatory by the dialect. True or 'always': Always quote. 'safe': Only quote identifiers that are case insensitive.
- normalize: Whether to normalize identifiers to lowercase. Default: False.
- pad: The pad size in a formatted string. For example, this affects the indentation of a projection in a query, relative to its nesting level. Default: 2.
- indent: The indentation size in a formatted string. For example, this affects the indentation of subqueries and filters under a `WHERE` clause. Default: 2.
- normalize_functions: How to normalize function names. Possible values are: "upper" or True (default): Convert names to uppercase. "lower": Convert names to lowercase. False: Disables function name normalization.
- unsupported_level: Determines the generator's behavior when it encounters unsupported expressions. Default ErrorLevel.WARN.
- max_unsupported: Maximum number of unsupported messages to include in a raised UnsupportedError. This is only relevant if unsupported_level is ErrorLevel.RAISE. Default: 3
- leading_comma: Whether the comma is leading or trailing in select expressions. This is only relevant when generating in pretty mode. Default: False
- max_text_width: The max number of characters in a segment before creating new lines in pretty mode. The default is on the smaller end because the length only represents a segment and not the true line length. Default: 80
- comments: Whether to preserve comments in the output SQL code. Default: True

Generator( pretty: Optional[bool] = None, identify: str | bool = False, normalize: bool = False, pad: int = 2, indent: int = 2, normalize_functions: Union[str, bool, NoneType] = None, unsupported_level: sqlglot.errors.ErrorLevel = <ErrorLevel.WARN: 'WARN'>, max_unsupported: int = 3, leading_comma: bool = False, max_text_width: int = 80, comments: bool = True, dialect: Union[str, sqlglot.dialects.Dialect, Type[sqlglot.dialects.Dialect], NoneType] = None) View Source

    695    def __init__(
    696        self,
    697        pretty: t.Optional[bool] = None,
    698        identify: str | bool = False,
    699        normalize: bool = False,
    700        pad: int = 2,
    701        indent: int = 2,
    702        normalize_functions: t.Optional[str | bool] = None,
    703        unsupported_level: ErrorLevel = ErrorLevel.WARN,
    704        max_unsupported: int = 3,
    705        leading_comma: bool = False,
    706        max_text_width: int = 80,
    707        comments: bool = True,
    708        dialect: DialectType = None,
    709    ):
    710        import sqlglot
    711        from sqlglot.dialects import Dialect
    712
    713        self.pretty = pretty if pretty is not None else sqlglot.pretty
    714        self.identify = identify
    715        self.normalize = normalize
    716        self.pad = pad
    717        self._indent = indent
    718        self.unsupported_level = unsupported_level
    719        self.max_unsupported = max_unsupported
    720        self.leading_comma = leading_comma
    721        self.max_text_width = max_text_width
    722        self.comments = comments
    723        self.dialect = Dialect.get_or_raise(dialect)
    724
    725        # This is both a Dialect property and a Generator argument, so we prioritize the latter
    726        self.normalize_functions = (
    727            self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions
    728        )
    729
    730        self.unsupported_messages: t.List[str] = []
    731        self._escaped_quote_end: str = (
    732            self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END
    733        )
    734        self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2
    735
    736        self._next_name = name_sequence("_t")
    737
    738        self._identifier_start = self.dialect.IDENTIFIER_START
    739        self._identifier_end = self.dialect.IDENTIFIER_END
    740
    741        self._quote_json_path_key_using_brackets = True

TRANSFORMS: Dict[Type[sqlglot.expressions.Expression], Callable[..., str]] = {<class 'sqlglot.expressions.JSONPathFilter'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathKey'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathRecursive'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathRoot'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathScript'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSelector'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSlice'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSubscript'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathUnion'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathWildcard'>: <function <lambda>>, <class 'sqlglot.expressions.AllowedValuesProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AnalyzeColumns'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AnalyzeWith'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ArrayContainsAll'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ArrayOverlaps'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AutoRefreshProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.BackupProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CaseSpecificColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Ceil'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CommentColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ConnectByRoot'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ConvertToCharset'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CredentialsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DateFormatColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DefaultColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DynamicProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EmptyProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EncodeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EnviromentProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EphemeralColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExcludeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Except'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExternalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Floor'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Get'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.GlobalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.HeapProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.IcebergProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InheritsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InlineLengthColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Intersect'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.IntervalSpan'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Int64'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LanguageProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LocationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.MaterializedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NonClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NotForReplicationColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnCommitProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnUpdateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Operator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OutputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PartitionedByBucket'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PartitionByTruncate'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PivotAny'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ProjectionPolicyColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Put'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ReturnsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SampleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SecureProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetConfigProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SharingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlReadWriteProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StabilityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Stream'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StreamingTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StrictProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SwapTable'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Tags'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TemporaryProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Union'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UnloggedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UsingTemplateProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UsingData'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Uuid'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VarMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ViewAttributeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithProcedureOptions'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithSchemaBindingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithOperator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ForceProperty'>: <function Generator.<lambda>>}
NULL_ORDERING_SUPPORTED: Optional[bool] = True
IGNORE_NULLS_IN_FUNC = False
LOCKING_READS_SUPPORTED = False
EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = True
WRAP_DERIVED_VALUES = True
CREATE_FUNCTION_RETURN_AS = True
MATCHED_BY_SOURCE = True
SINGLE_STRING_INTERVAL = False
INTERVAL_ALLOWS_PLURAL_FORM = True
LIMIT_FETCH = 'ALL'
LIMIT_ONLY_LITERALS = False
RENAME_TABLE_WITH_DB = True
GROUPINGS_SEP = ','
INDEX_ON = 'ON'
JOIN_HINTS = True
TABLE_HINTS = True
QUERY_HINTS = True
QUERY_HINT_SEP = ', '
IS_BOOL_ALLOWED = True
DUPLICATE_KEY_UPDATE_WITH_SET = True
LIMIT_IS_TOP = False
RETURNING_END = True
EXTRACT_ALLOWS_QUOTES = True
TZ_TO_WITH_TIME_ZONE = False
NVL2_SUPPORTED = True
SELECT_KINDS: Tuple[str, ...] = ('STRUCT', 'VALUE')
VALUES_AS_TABLE = True
ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = True
UNNEST_WITH_ORDINALITY = True
AGGREGATE_FILTER_SUPPORTED = True
SEMI_ANTI_JOIN_WITH_SIDE = True
COMPUTED_COLUMN_WITH_TYPE = True
SUPPORTS_TABLE_COPY = True
TABLESAMPLE_REQUIRES_PARENS = True
TABLESAMPLE_SIZE_IS_ROWS = True
TABLESAMPLE_KEYWORDS = 'TABLESAMPLE'
TABLESAMPLE_WITH_METHOD = True
TABLESAMPLE_SEED_KEYWORD = 'SEED'
COLLATE_IS_FUNC = False
DATA_TYPE_SPECIFIERS_ALLOWED = False
ENSURE_BOOLS = False
CTE_RECURSIVE_KEYWORD_REQUIRED = True
SUPPORTS_SINGLE_ARG_CONCAT = True
LAST_DAY_SUPPORTS_DATE_PART = True
SUPPORTS_TABLE_ALIAS_COLUMNS = True
UNPIVOT_ALIASES_ARE_IDENTIFIERS = True
JSON_KEY_VALUE_PAIR_SEP = ':'
INSERT_OVERWRITE = ' OVERWRITE TABLE'
SUPPORTS_SELECT_INTO = False
SUPPORTS_UNLOGGED_TABLES = False
SUPPORTS_CREATE_TABLE_LIKE = True
LIKE_PROPERTY_INSIDE_SCHEMA = False
MULTI_ARG_DISTINCT = True
JSON_TYPE_REQUIRED_FOR_EXTRACTION = False
JSON_PATH_BRACKETED_KEY_SUPPORTED = True
JSON_PATH_SINGLE_QUOTE_ESCAPE = False
SUPPORTED_JSON_PATH_PARTS = {<class 'sqlglot.expressions.JSONPathFilter'>, <class 'sqlglot.expressions.JSONPathUnion'>, <class 'sqlglot.expressions.JSONPathSubscript'>, <class 'sqlglot.expressions.JSONPathWildcard'>, <class 'sqlglot.expressions.JSONPathSelector'>, <class 'sqlglot.expressions.JSONPathSlice'>, <class 'sqlglot.expressions.JSONPathScript'>, <class 'sqlglot.expressions.JSONPathRoot'>, <class 'sqlglot.expressions.JSONPathRecursive'>, <class 'sqlglot.expressions.JSONPathKey'>}
CAN_IMPLEMENT_ARRAY_ANY = False
SUPPORTS_TO_NUMBER = True
SUPPORTS_WINDOW_EXCLUDE = False
SET_OP_MODIFIERS = True
COPY_PARAMS_ARE_WRAPPED = True
COPY_PARAMS_EQ_REQUIRED = False
COPY_HAS_INTO_KEYWORD = True
TRY_SUPPORTED = True
SUPPORTS_UESCAPE = True
STAR_EXCEPT = 'EXCEPT'
HEX_FUNC = 'HEX'
WITH_PROPERTIES_PREFIX = 'WITH'
QUOTE_JSON_PATH = True
PAD_FILL_PATTERN_IS_REQUIRED = False
SUPPORTS_EXPLODING_PROJECTIONS = True
ARRAY_CONCAT_IS_VAR_LEN = True
SUPPORTS_CONVERT_TIMEZONE = False
SUPPORTS_MEDIAN = True
SUPPORTS_UNIX_SECONDS = False
PARSE_JSON_NAME: Optional[str] = 'PARSE_JSON'
ARRAY_SIZE_NAME: str = 'ARRAY_LENGTH'
ALTER_SET_TYPE = 'SET DATA TYPE'
ARRAY_SIZE_DIM_REQUIRED: Optional[bool] = None
TYPE_MAPPING = {<Type.DATETIME2: 'DATETIME2'>: 'TIMESTAMP', <Type.NCHAR: 'NCHAR'>: 'CHAR', <Type.NVARCHAR: 'NVARCHAR'>: 'VARCHAR', <Type.MEDIUMTEXT: 'MEDIUMTEXT'>: 'TEXT', <Type.LONGTEXT: 'LONGTEXT'>: 'TEXT', <Type.TINYTEXT: 'TINYTEXT'>: 'TEXT', <Type.BLOB: 'BLOB'>: 'VARBINARY', <Type.MEDIUMBLOB: 'MEDIUMBLOB'>: 'BLOB', <Type.LONGBLOB: 'LONGBLOB'>: 'BLOB', <Type.TINYBLOB: 'TINYBLOB'>: 'BLOB', <Type.INET: 'INET'>: 'INET', <Type.ROWVERSION: 'ROWVERSION'>: 'VARBINARY', <Type.SMALLDATETIME: 'SMALLDATETIME'>: 'TIMESTAMP'}
TIME_PART_SINGULARS = {'MICROSECONDS': 'MICROSECOND', 'SECONDS': 'SECOND', 'MINUTES': 'MINUTE', 'HOURS': 'HOUR', 'DAYS': 'DAY', 'WEEKS': 'WEEK', 'MONTHS': 'MONTH', 'QUARTERS': 'QUARTER', 'YEARS': 'YEAR'}
AFTER_HAVING_MODIFIER_TRANSFORMS = {'cluster': <function Generator.<lambda>>, 'distribute': <function Generator.<lambda>>, 'sort': <function Generator.<lambda>>, 'windows': <function Generator.<lambda>>, 'qualify': <function Generator.<lambda>>}
TOKEN_MAPPING: Dict[sqlglot.tokens.TokenType, str] = {}
STRUCT_DELIMITER = ('<', '>')
PARAMETER_TOKEN = '@'
NAMED_PLACEHOLDER_TOKEN = ':'
EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: Set[str] = set()
PROPERTIES_LOCATION = {<class 'sqlglot.expressions.AllowedValuesProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.AlgorithmProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.AutoIncrementProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.AutoRefreshProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.BackupProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.BlockCompressionProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CharacterSetProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ChecksumProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CollateProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Cluster'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ClusteredByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistributedByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DuplicateKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DataBlocksizeProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.DataDeletionProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DefinerProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.DictRange'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DictProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DynamicProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.DistKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistStyleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EmptyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EncodeProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.EngineProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EnviromentProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExternalProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.FallbackProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.FileFormatProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.FreespaceProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.GlobalProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.HeapProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.InheritsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.IcebergProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.IncludeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.InputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.IsolatedLoadingProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.JournalProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.LanguageProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LikeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LocationProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LockProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LockingProperty'>: <Location.POST_ALIAS: 'POST_ALIAS'>, <class 'sqlglot.expressions.LogProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.MaterializedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.MergeBlockRatioProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.OnProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OnCommitProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.Order'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OutputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PartitionedByProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.PartitionedOfProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PrimaryKey'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Property'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ReturnsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatDelimitedProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatSerdeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SampleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SchemaCommentProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SecureProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.SecurityProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SerdeProperties'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Set'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SettingsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SetProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.SetConfigProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SharingProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.SequenceProperties'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.SortKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlReadWriteProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StabilityProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.StorageHandlerProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.StreamingTableProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StrictProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Tags'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.TemporaryProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.ToTableProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TransientProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.TransformModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.MergeTreeTTL'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.UnloggedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.UsingTemplateProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ViewAttributeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.VolatileProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.WithDataProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.WithProcedureOptions'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.WithSchemaBindingProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.WithSystemVersioningProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ForceProperty'>: <Location.POST_CREATE: 'POST_CREATE'>}
RESERVED_KEYWORDS: Set[str] = set()
WITH_SEPARATED_COMMENTS: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Command'>, <class 'sqlglot.expressions.Create'>, <class 'sqlglot.expressions.Describe'>, <class 'sqlglot.expressions.Delete'>, <class 'sqlglot.expressions.Drop'>, <class 'sqlglot.expressions.From'>, <class 'sqlglot.expressions.Insert'>, <class 'sqlglot.expressions.Join'>, <class 'sqlglot.expressions.MultitableInserts'>, <class 'sqlglot.expressions.Select'>, <class 'sqlglot.expressions.SetOperation'>, <class 'sqlglot.expressions.Update'>, <class 'sqlglot.expressions.Where'>, <class 'sqlglot.expressions.With'>)
EXCLUDE_COMMENTS: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Binary'>, <class 'sqlglot.expressions.SetOperation'>)
UNWRAPPED_INTERVAL_VALUES: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Column'>, <class 'sqlglot.expressions.Literal'>, <class 'sqlglot.expressions.Neg'>, <class 'sqlglot.expressions.Paren'>)
PARAMETERIZABLE_TEXT_TYPES = {<Type.VARCHAR: 'VARCHAR'>, <Type.NVARCHAR: 'NVARCHAR'>, <Type.CHAR: 'CHAR'>, <Type.NCHAR: 'NCHAR'>}
EXPRESSIONS_WITHOUT_NESTED_CTES: Set[Type[sqlglot.expressions.Expression]] = set()
SENTINEL_LINE_BREAK = '__SQLGLOT__LB__'
pretty
identify
normalize
pad
unsupported_level
max_unsupported
leading_comma
max_text_width
comments
dialect
normalize_functions
unsupported_messages: List[str]
def generate( self, expression: sqlglot.expressions.Expression, copy: bool = True) -> str: View Source

    743    def generate(self, expression: exp.Expression, copy: bool = True) -> str:
    744        """
    745        Generates the SQL string corresponding to the given syntax tree.
    746
    747        Args:
    748            expression: The syntax tree.
    749            copy: Whether to copy the expression. The generator performs mutations so
    750                it is safer to copy.
    751
    752        Returns:
    753            The SQL string corresponding to `expression`.
    754        """
    755        if copy:
    756            expression = expression.copy()
    757
    758        expression = self.preprocess(expression)
    759
    760        self.unsupported_messages = []
    761        sql = self.sql(expression).strip()
    762
    763        if self.pretty:
    764            sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n")
    765
    766        if self.unsupported_level == ErrorLevel.IGNORE:
    767            return sql
    768
    769        if self.unsupported_level == ErrorLevel.WARN:
    770            for msg in self.unsupported_messages:
    771                logger.warning(msg)
    772        elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages:
    773            raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported))
    774
    775        return sql

Generates the SQL string corresponding to the given syntax tree.

###### Arguments:

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

###### Returns:

> The SQL string corresponding to `expression`.

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

    777    def preprocess(self, expression: exp.Expression) -> exp.Expression:
    778        """Apply generic preprocessing transformations to a given expression."""
    779        expression = self._move_ctes_to_top_level(expression)
    780
    781        if self.ENSURE_BOOLS:
    782            from sqlglot.transforms import ensure_bools
    783
    784            expression = ensure_bools(expression)
    785
    786        return expression

Apply generic preprocessing transformations to a given expression.

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

    799    def unsupported(self, message: str) -> None:
    800        if self.unsupported_level == ErrorLevel.IMMEDIATE:
    801            raise UnsupportedError(message)
    802        self.unsupported_messages.append(message)

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

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

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

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

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

    810    def pad_comment(self, comment: str) -> str:
    811        comment = " " + comment if comment[0].strip() else comment
    812        comment = comment + " " if comment[-1].strip() else comment
    813        return comment

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

    815    def maybe_comment(
    816        self,
    817        sql: str,
    818        expression: t.Optional[exp.Expression] = None,
    819        comments: t.Optional[t.List[str]] = None,
    820        separated: bool = False,
    821    ) -> str:
    822        comments = (
    823            ((expression and expression.comments) if comments is None else comments)  # type: ignore
    824            if self.comments
    825            else None
    826        )
    827
    828        if not comments or isinstance(expression, self.EXCLUDE_COMMENTS):
    829            return sql
    830
    831        comments_sql = " ".join(
    832            f"/*{self.pad_comment(comment)}*/" for comment in comments if comment
    833        )
    834
    835        if not comments_sql:
    836            return sql
    837
    838        comments_sql = self._replace_line_breaks(comments_sql)
    839
    840        if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS):
    841            return (
    842                f"{self.sep()}{comments_sql}{sql}"
    843                if not sql or sql[0].isspace()
    844                else f"{comments_sql}{self.sep()}{sql}"
    845            )
    846
    847        return f"{sql} {comments_sql}"

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

    849    def wrap(self, expression: exp.Expression | str) -> str:
    850        this_sql = (
    851            self.sql(expression)
    852            if isinstance(expression, exp.UNWRAPPED_QUERIES)
    853            else self.sql(expression, "this")
    854        )
    855        if not this_sql:
    856            return "()"
    857
    858        this_sql = self.indent(this_sql, level=1, pad=0)
    859        return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"

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

    861    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
    862        original = self.identify
    863        self.identify = False
    864        result = func(*args, **kwargs)
    865        self.identify = original
    866        return result

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

    868    def normalize_func(self, name: str) -> str:
    869        if self.normalize_functions == "upper" or self.normalize_functions is True:
    870            return name.upper()
    871        if self.normalize_functions == "lower":
    872            return name.lower()
    873        return name

def indent( self, sql: str, level: int = 0, pad: Optional[int] = None, skip_first: bool = False, skip_last: bool = False) -> str: View Source

    875    def indent(
    876        self,
    877        sql: str,
    878        level: int = 0,
    879        pad: t.Optional[int] = None,
    880        skip_first: bool = False,
    881        skip_last: bool = False,
    882    ) -> str:
    883        if not self.pretty or not sql:
    884            return sql
    885
    886        pad = self.pad if pad is None else pad
    887        lines = sql.split("\n")
    888
    889        return "\n".join(
    890            (
    891                line
    892                if (skip_first and i == 0) or (skip_last and i == len(lines) - 1)
    893                else f"{' ' * (level * self._indent + pad)}{line}"
    894            )
    895            for i, line in enumerate(lines)
    896        )

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

    898    def sql(
    899        self,
    900        expression: t.Optional[str | exp.Expression],
    901        key: t.Optional[str] = None,
    902        comment: bool = True,
    903    ) -> str:
    904        if not expression:
    905            return ""
    906
    907        if isinstance(expression, str):
    908            return expression
    909
    910        if key:
    911            value = expression.args.get(key)
    912            if value:
    913                return self.sql(value)
    914            return ""
    915
    916        transform = self.TRANSFORMS.get(expression.__class__)
    917
    918        if callable(transform):
    919            sql = transform(self, expression)
    920        elif isinstance(expression, exp.Expression):
    921            exp_handler_name = f"{expression.key}_sql"
    922
    923            if hasattr(self, exp_handler_name):
    924                sql = getattr(self, exp_handler_name)(expression)
    925            elif isinstance(expression, exp.Func):
    926                sql = self.function_fallback_sql(expression)
    927            elif isinstance(expression, exp.Property):
    928                sql = self.property_sql(expression)
    929            else:
    930                raise ValueError(f"Unsupported expression type {expression.__class__.__name__}")
    931        else:
    932            raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}")
    933
    934        return self.maybe_comment(sql, expression) if self.comments and comment else sql

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

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

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

    941    def cache_sql(self, expression: exp.Cache) -> str:
    942        lazy = " LAZY" if expression.args.get("lazy") else ""
    943        table = self.sql(expression, "this")
    944        options = expression.args.get("options")
    945        options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else ""
    946        sql = self.sql(expression, "expression")
    947        sql = f" AS{self.sep()}{sql}" if sql else ""
    948        sql = f"CACHE{lazy} TABLE {table}{options}{sql}"
    949        return self.prepend_ctes(expression, sql)

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

    951    def characterset_sql(self, expression: exp.CharacterSet) -> str:
    952        if isinstance(expression.parent, exp.Cast):
    953            return f"CHAR CHARACTER SET {self.sql(expression, 'this')}"
    954        default = "DEFAULT " if expression.args.get("default") else ""
    955        return f"{default}CHARACTER SET={self.sql(expression, 'this')}"

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

    957    def column_parts(self, expression: exp.Column) -> str:
    958        return ".".join(
    959            self.sql(part)
    960            for part in (
    961                expression.args.get("catalog"),
    962                expression.args.get("db"),
    963                expression.args.get("table"),
    964                expression.args.get("this"),
    965            )
    966            if part
    967        )

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

    969    def column_sql(self, expression: exp.Column) -> str:
    970        join_mark = " (+)" if expression.args.get("join_mark") else ""
    971
    972        if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS:
    973            join_mark = ""
    974            self.unsupported("Outer join syntax using the (+) operator is not supported.")
    975
    976        return f"{self.column_parts(expression)}{join_mark}"

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

    978    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
    979        this = self.sql(expression, "this")
    980        this = f" {this}" if this else ""
    981        position = self.sql(expression, "position")
    982        return f"{position}{this}"

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

    984    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
    985        column = self.sql(expression, "this")
    986        kind = self.sql(expression, "kind")
    987        constraints = self.expressions(expression, key="constraints", sep=" ", flat=True)
    988        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
    989        kind = f"{sep}{kind}" if kind else ""
    990        constraints = f" {constraints}" if constraints else ""
    991        position = self.sql(expression, "position")
    992        position = f" {position}" if position else ""
    993
    994        if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE:
    995            kind = ""
    996
    997        return f"{exists}{column}{kind}{constraints}{position}"

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

     999    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
    1000        this = self.sql(expression, "this")
    1001        kind_sql = self.sql(expression, "kind").strip()
    1002        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql

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

    1004    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
    1005        this = self.sql(expression, "this")
    1006        if expression.args.get("not_null"):
    1007            persisted = " PERSISTED NOT NULL"
    1008        elif expression.args.get("persisted"):
    1009            persisted = " PERSISTED"
    1010        else:
    1011            persisted = ""
    1012        return f"AS {this}{persisted}"

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

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

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

    1017    def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str:
    1018        if isinstance(expression.this, list):
    1019            this = self.wrap(self.expressions(expression, key="this", flat=True))
    1020        else:
    1021            this = self.sql(expression, "this")
    1022
    1023        return f"COMPRESS {this}"

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

    1025    def generatedasidentitycolumnconstraint_sql(
    1026        self, expression: exp.GeneratedAsIdentityColumnConstraint
    1027    ) -> str:
    1028        this = ""
    1029        if expression.this is not None:
    1030            on_null = " ON NULL" if expression.args.get("on_null") else ""
    1031            this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}"
    1032
    1033        start = expression.args.get("start")
    1034        start = f"START WITH {start}" if start else ""
    1035        increment = expression.args.get("increment")
    1036        increment = f" INCREMENT BY {increment}" if increment else ""
    1037        minvalue = expression.args.get("minvalue")
    1038        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    1039        maxvalue = expression.args.get("maxvalue")
    1040        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    1041        cycle = expression.args.get("cycle")
    1042        cycle_sql = ""
    1043
    1044        if cycle is not None:
    1045            cycle_sql = f"{' NO' if not cycle else ''} CYCLE"
    1046            cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql
    1047
    1048        sequence_opts = ""
    1049        if start or increment or cycle_sql:
    1050            sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}"
    1051            sequence_opts = f" ({sequence_opts.strip()})"
    1052
    1053        expr = self.sql(expression, "expression")
    1054        expr = f"({expr})" if expr else "IDENTITY"
    1055
    1056        return f"GENERATED{this} AS {expr}{sequence_opts}"

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

    1058    def generatedasrowcolumnconstraint_sql(
    1059        self, expression: exp.GeneratedAsRowColumnConstraint
    1060    ) -> str:
    1061        start = "START" if expression.args.get("start") else "END"
    1062        hidden = " HIDDEN" if expression.args.get("hidden") else ""
    1063        return f"GENERATED ALWAYS AS ROW {start}{hidden}"

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

    1065    def periodforsystemtimeconstraint_sql(
    1066        self, expression: exp.PeriodForSystemTimeConstraint
    1067    ) -> str:
    1068        return f"PERIOD FOR SYSTEM_TIME ({self.sql(expression, 'this')}, {self.sql(expression, 'expression')})"

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

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

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

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

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

    1076    def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str:
    1077        desc = expression.args.get("desc")
    1078        if desc is not None:
    1079            return f"PRIMARY KEY{' DESC' if desc else ' ASC'}"
    1080        options = self.expressions(expression, key="options", flat=True, sep=" ")
    1081        options = f" {options}" if options else ""
    1082        return f"PRIMARY KEY{options}"

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

    1084    def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str:
    1085        this = self.sql(expression, "this")
    1086        this = f" {this}" if this else ""
    1087        index_type = expression.args.get("index_type")
    1088        index_type = f" USING {index_type}" if index_type else ""
    1089        on_conflict = self.sql(expression, "on_conflict")
    1090        on_conflict = f" {on_conflict}" if on_conflict else ""
    1091        nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else ""
    1092        options = self.expressions(expression, key="options", flat=True, sep=" ")
    1093        options = f" {options}" if options else ""
    1094        return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}{options}"

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

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

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

    1099    def create_sql(self, expression: exp.Create) -> str:
    1100        kind = self.sql(expression, "kind")
    1101        kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind
    1102        properties = expression.args.get("properties")
    1103        properties_locs = self.locate_properties(properties) if properties else defaultdict()
    1104
    1105        this = self.createable_sql(expression, properties_locs)
    1106
    1107        properties_sql = ""
    1108        if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get(
    1109            exp.Properties.Location.POST_WITH
    1110        ):
    1111            properties_sql = self.sql(
    1112                exp.Properties(
    1113                    expressions=[
    1114                        *properties_locs[exp.Properties.Location.POST_SCHEMA],
    1115                        *properties_locs[exp.Properties.Location.POST_WITH],
    1116                    ]
    1117                )
    1118            )
    1119
    1120            if properties_locs.get(exp.Properties.Location.POST_SCHEMA):
    1121                properties_sql = self.sep() + properties_sql
    1122            elif not self.pretty:
    1123                # Standalone POST_WITH properties need a leading whitespace in non-pretty mode
    1124                properties_sql = f" {properties_sql}"
    1125
    1126        begin = " BEGIN" if expression.args.get("begin") else ""
    1127        end = " END" if expression.args.get("end") else ""
    1128
    1129        expression_sql = self.sql(expression, "expression")
    1130        if expression_sql:
    1131            expression_sql = f"{begin}{self.sep()}{expression_sql}{end}"
    1132
    1133            if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return):
    1134                postalias_props_sql = ""
    1135                if properties_locs.get(exp.Properties.Location.POST_ALIAS):
    1136                    postalias_props_sql = self.properties(
    1137                        exp.Properties(
    1138                            expressions=properties_locs[exp.Properties.Location.POST_ALIAS]
    1139                        ),
    1140                        wrapped=False,
    1141                    )
    1142                postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else ""
    1143                expression_sql = f" AS{postalias_props_sql}{expression_sql}"
    1144
    1145        postindex_props_sql = ""
    1146        if properties_locs.get(exp.Properties.Location.POST_INDEX):
    1147            postindex_props_sql = self.properties(
    1148                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]),
    1149                wrapped=False,
    1150                prefix=" ",
    1151            )
    1152
    1153        indexes = self.expressions(expression, key="indexes", indent=False, sep=" ")
    1154        indexes = f" {indexes}" if indexes else ""
    1155        index_sql = indexes + postindex_props_sql
    1156
    1157        replace = " OR REPLACE" if expression.args.get("replace") else ""
    1158        refresh = " OR REFRESH" if expression.args.get("refresh") else ""
    1159        unique = " UNIQUE" if expression.args.get("unique") else ""
    1160
    1161        clustered = expression.args.get("clustered")
    1162        if clustered is None:
    1163            clustered_sql = ""
    1164        elif clustered:
    1165            clustered_sql = " CLUSTERED COLUMNSTORE"
    1166        else:
    1167            clustered_sql = " NONCLUSTERED COLUMNSTORE"
    1168
    1169        postcreate_props_sql = ""
    1170        if properties_locs.get(exp.Properties.Location.POST_CREATE):
    1171            postcreate_props_sql = self.properties(
    1172                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]),
    1173                sep=" ",
    1174                prefix=" ",
    1175                wrapped=False,
    1176            )
    1177
    1178        modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql))
    1179
    1180        postexpression_props_sql = ""
    1181        if properties_locs.get(exp.Properties.Location.POST_EXPRESSION):
    1182            postexpression_props_sql = self.properties(
    1183                exp.Properties(
    1184                    expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION]
    1185                ),
    1186                sep=" ",
    1187                prefix=" ",
    1188                wrapped=False,
    1189            )
    1190
    1191        concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else ""
    1192        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
    1193        no_schema_binding = (
    1194            " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else ""
    1195        )
    1196
    1197        clone = self.sql(expression, "clone")
    1198        clone = f" {clone}" if clone else ""
    1199
    1200        if kind in self.EXPRESSION_PRECEDES_PROPERTIES_CREATABLES:
    1201            properties_expression = f"{expression_sql}{properties_sql}"
    1202        else:
    1203            properties_expression = f"{properties_sql}{expression_sql}"
    1204
    1205        expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_expression}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}"
    1206        return self.prepend_ctes(expression, expression_sql)

def sequenceproperties_sql(self, expression: sqlglot.expressions.SequenceProperties) -> str: View Source

    1208    def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str:
    1209        start = self.sql(expression, "start")
    1210        start = f"START WITH {start}" if start else ""
    1211        increment = self.sql(expression, "increment")
    1212        increment = f" INCREMENT BY {increment}" if increment else ""
    1213        minvalue = self.sql(expression, "minvalue")
    1214        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    1215        maxvalue = self.sql(expression, "maxvalue")
    1216        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    1217        owned = self.sql(expression, "owned")
    1218        owned = f" OWNED BY {owned}" if owned else ""
    1219
    1220        cache = expression.args.get("cache")
    1221        if cache is None:
    1222            cache_str = ""
    1223        elif cache is True:
    1224            cache_str = " CACHE"
    1225        else:
    1226            cache_str = f" CACHE {cache}"
    1227
    1228        options = self.expressions(expression, key="options", flat=True, sep=" ")
    1229        options = f" {options}" if options else ""
    1230
    1231        return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip()

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

    1233    def clone_sql(self, expression: exp.Clone) -> str:
    1234        this = self.sql(expression, "this")
    1235        shallow = "SHALLOW " if expression.args.get("shallow") else ""
    1236        keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE"
    1237        return f"{shallow}{keyword} {this}"

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

    1239    def describe_sql(self, expression: exp.Describe) -> str:
    1240        style = expression.args.get("style")
    1241        style = f" {style}" if style else ""
    1242        partition = self.sql(expression, "partition")
    1243        partition = f" {partition}" if partition else ""
    1244        format = self.sql(expression, "format")
    1245        format = f" {format}" if format else ""
    1246
    1247        return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}"

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

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

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

    1253    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
    1254        with_ = self.sql(expression, "with")
    1255        if with_:
    1256            sql = f"{with_}{self.sep()}{sql}"
    1257        return sql

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

    1259    def with_sql(self, expression: exp.With) -> str:
    1260        sql = self.expressions(expression, flat=True)
    1261        recursive = (
    1262            "RECURSIVE "
    1263            if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive")
    1264            else ""
    1265        )
    1266        search = self.sql(expression, "search")
    1267        search = f" {search}" if search else ""
    1268
    1269        return f"WITH {recursive}{sql}{search}"

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

    1271    def cte_sql(self, expression: exp.CTE) -> str:
    1272        alias = expression.args.get("alias")
    1273        if alias:
    1274            alias.add_comments(expression.pop_comments())
    1275
    1276        alias_sql = self.sql(expression, "alias")
    1277
    1278        materialized = expression.args.get("materialized")
    1279        if materialized is False:
    1280            materialized = "NOT MATERIALIZED "
    1281        elif materialized:
    1282            materialized = "MATERIALIZED "
    1283
    1284        return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}"

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

    1286    def tablealias_sql(self, expression: exp.TableAlias) -> str:
    1287        alias = self.sql(expression, "this")
    1288        columns = self.expressions(expression, key="columns", flat=True)
    1289        columns = f"({columns})" if columns else ""
    1290
    1291        if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS:
    1292            columns = ""
    1293            self.unsupported("Named columns are not supported in table alias.")
    1294
    1295        if not alias and not self.dialect.UNNEST_COLUMN_ONLY:
    1296            alias = self._next_name()
    1297
    1298        return f"{alias}{columns}"

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

    1300    def bitstring_sql(self, expression: exp.BitString) -> str:
    1301        this = self.sql(expression, "this")
    1302        if self.dialect.BIT_START:
    1303            return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}"
    1304        return f"{int(this, 2)}"

def hexstring_sql( self, expression: sqlglot.expressions.HexString, binary_function_repr: Optional[str] = None) -> str: View Source

    1306    def hexstring_sql(
    1307        self, expression: exp.HexString, binary_function_repr: t.Optional[str] = None
    1308    ) -> str:
    1309        this = self.sql(expression, "this")
    1310        is_integer_type = expression.args.get("is_integer")
    1311
    1312        if (is_integer_type and not self.dialect.HEX_STRING_IS_INTEGER_TYPE) or (
    1313            not self.dialect.HEX_START and not binary_function_repr
    1314        ):
    1315            # Integer representation will be returned if:
    1316            # - The read dialect treats the hex value as integer literal but not the write
    1317            # - The transpilation is not supported (write dialect hasn't set HEX_START or the param flag)
    1318            return f"{int(this, 16)}"
    1319
    1320        if not is_integer_type:
    1321            # Read dialect treats the hex value as BINARY/BLOB
    1322            if binary_function_repr:
    1323                # The write dialect supports the transpilation to its equivalent BINARY/BLOB
    1324                return self.func(binary_function_repr, exp.Literal.string(this))
    1325            if self.dialect.HEX_STRING_IS_INTEGER_TYPE:
    1326                # The write dialect does not support the transpilation, it'll treat the hex value as INTEGER
    1327                self.unsupported("Unsupported transpilation from BINARY/BLOB hex string")
    1328
    1329        return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"

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

    1331    def bytestring_sql(self, expression: exp.ByteString) -> str:
    1332        this = self.sql(expression, "this")
    1333        if self.dialect.BYTE_START:
    1334            return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}"
    1335        return this

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

    1337    def unicodestring_sql(self, expression: exp.UnicodeString) -> str:
    1338        this = self.sql(expression, "this")
    1339        escape = expression.args.get("escape")
    1340
    1341        if self.dialect.UNICODE_START:
    1342            escape_substitute = r"\\\1"
    1343            left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END
    1344        else:
    1345            escape_substitute = r"\\u\1"
    1346            left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END
    1347
    1348        if escape:
    1349            escape_pattern = re.compile(rf"{escape.name}(\d+)")
    1350            escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else ""
    1351        else:
    1352            escape_pattern = ESCAPED_UNICODE_RE
    1353            escape_sql = ""
    1354
    1355        if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE):
    1356            this = escape_pattern.sub(escape_substitute, this)
    1357
    1358        return f"{left_quote}{this}{right_quote}{escape_sql}"

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

    1360    def rawstring_sql(self, expression: exp.RawString) -> str:
    1361        string = expression.this
    1362        if "\\" in self.dialect.tokenizer_class.STRING_ESCAPES:
    1363            string = string.replace("\\", "\\\\")
    1364
    1365        string = self.escape_str(string, escape_backslash=False)
    1366        return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}"

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

    1368    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
    1369        this = self.sql(expression, "this")
    1370        specifier = self.sql(expression, "expression")
    1371        specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else ""
    1372        return f"{this}{specifier}"

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

    1374    def datatype_sql(self, expression: exp.DataType) -> str:
    1375        nested = ""
    1376        values = ""
    1377        interior = self.expressions(expression, flat=True)
    1378
    1379        type_value = expression.this
    1380        if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"):
    1381            type_sql = self.sql(expression, "kind")
    1382        else:
    1383            type_sql = (
    1384                self.TYPE_MAPPING.get(type_value, type_value.value)
    1385                if isinstance(type_value, exp.DataType.Type)
    1386                else type_value
    1387            )
    1388
    1389        if interior:
    1390            if expression.args.get("nested"):
    1391                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
    1392                if expression.args.get("values") is not None:
    1393                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
    1394                    values = self.expressions(expression, key="values", flat=True)
    1395                    values = f"{delimiters[0]}{values}{delimiters[1]}"
    1396            elif type_value == exp.DataType.Type.INTERVAL:
    1397                nested = f" {interior}"
    1398            else:
    1399                nested = f"({interior})"
    1400
    1401        type_sql = f"{type_sql}{nested}{values}"
    1402        if self.TZ_TO_WITH_TIME_ZONE and type_value in (
    1403            exp.DataType.Type.TIMETZ,
    1404            exp.DataType.Type.TIMESTAMPTZ,
    1405        ):
    1406            type_sql = f"{type_sql} WITH TIME ZONE"
    1407
    1408        return type_sql

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

    1410    def directory_sql(self, expression: exp.Directory) -> str:
    1411        local = "LOCAL " if expression.args.get("local") else ""
    1412        row_format = self.sql(expression, "row_format")
    1413        row_format = f" {row_format}" if row_format else ""
    1414        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"

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

    1416    def delete_sql(self, expression: exp.Delete) -> str:
    1417        this = self.sql(expression, "this")
    1418        this = f" FROM {this}" if this else ""
    1419        using = self.sql(expression, "using")
    1420        using = f" USING {using}" if using else ""
    1421        cluster = self.sql(expression, "cluster")
    1422        cluster = f" {cluster}" if cluster else ""
    1423        where = self.sql(expression, "where")
    1424        returning = self.sql(expression, "returning")
    1425        limit = self.sql(expression, "limit")
    1426        tables = self.expressions(expression, key="tables")
    1427        tables = f" {tables}" if tables else ""
    1428        if self.RETURNING_END:
    1429            expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}"
    1430        else:
    1431            expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}"
    1432        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")

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

    1434    def drop_sql(self, expression: exp.Drop) -> str:
    1435        this = self.sql(expression, "this")
    1436        expressions = self.expressions(expression, flat=True)
    1437        expressions = f" ({expressions})" if expressions else ""
    1438        kind = expression.args["kind"]
    1439        kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind
    1440        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    1441        concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else ""
    1442        on_cluster = self.sql(expression, "cluster")
    1443        on_cluster = f" {on_cluster}" if on_cluster else ""
    1444        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    1445        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    1446        cascade = " CASCADE" if expression.args.get("cascade") else ""
    1447        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
    1448        purge = " PURGE" if expression.args.get("purge") else ""
    1449        return f"DROP{temporary}{materialized} {kind}{concurrently_sql}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}"

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

    1451    def set_operation(self, expression: exp.SetOperation) -> str:
    1452        op_type = type(expression)
    1453        op_name = op_type.key.upper()
    1454
    1455        distinct = expression.args.get("distinct")
    1456        if (
    1457            distinct is False
    1458            and op_type in (exp.Except, exp.Intersect)
    1459            and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE
    1460        ):
    1461            self.unsupported(f"{op_name} ALL is not supported")
    1462
    1463        default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type]
    1464
    1465        if distinct is None:
    1466            distinct = default_distinct
    1467            if distinct is None:
    1468                self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified")
    1469
    1470        if distinct is default_distinct:
    1471            distinct_or_all = ""
    1472        else:
    1473            distinct_or_all = " DISTINCT" if distinct else " ALL"
    1474
    1475        side_kind = " ".join(filter(None, [expression.side, expression.kind]))
    1476        side_kind = f"{side_kind} " if side_kind else ""
    1477
    1478        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1479        on = self.expressions(expression, key="on", flat=True)
    1480        on = f" ON ({on})" if on else ""
    1481
    1482        return f"{side_kind}{op_name}{distinct_or_all}{by_name}{on}"

def set_operations(self, expression: sqlglot.expressions.SetOperation) -> str: View Source

    1484    def set_operations(self, expression: exp.SetOperation) -> str:
    1485        if not self.SET_OP_MODIFIERS:
    1486            limit = expression.args.get("limit")
    1487            order = expression.args.get("order")
    1488
    1489            if limit or order:
    1490                select = self._move_ctes_to_top_level(
    1491                    exp.subquery(expression, "_l_0", copy=False).select("*", copy=False)
    1492                )
    1493
    1494                if limit:
    1495                    select = select.limit(limit.pop(), copy=False)
    1496                if order:
    1497                    select = select.order_by(order.pop(), copy=False)
    1498                return self.sql(select)
    1499
    1500        sqls: t.List[str] = []
    1501        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    1502
    1503        while stack:
    1504            node = stack.pop()
    1505
    1506            if isinstance(node, exp.SetOperation):
    1507                stack.append(node.expression)
    1508                stack.append(
    1509                    self.maybe_comment(
    1510                        self.set_operation(node), comments=node.comments, separated=True
    1511                    )
    1512                )
    1513                stack.append(node.this)
    1514            else:
    1515                sqls.append(self.sql(node))
    1516
    1517        this = self.sep().join(sqls)
    1518        this = self.query_modifiers(expression, this)
    1519        return self.prepend_ctes(expression, this)

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

    1521    def fetch_sql(self, expression: exp.Fetch) -> str:
    1522        direction = expression.args.get("direction")
    1523        direction = f" {direction}" if direction else ""
    1524        count = self.sql(expression, "count")
    1525        count = f" {count}" if count else ""
    1526        limit_options = self.sql(expression, "limit_options")
    1527        limit_options = f"{limit_options}" if limit_options else " ROWS ONLY"
    1528        return f"{self.seg('FETCH')}{direction}{count}{limit_options}"

def limitoptions_sql(self, expression: sqlglot.expressions.LimitOptions) -> str: View Source

    1530    def limitoptions_sql(self, expression: exp.LimitOptions) -> str:
    1531        percent = " PERCENT" if expression.args.get("percent") else ""
    1532        rows = " ROWS" if expression.args.get("rows") else ""
    1533        with_ties = " WITH TIES" if expression.args.get("with_ties") else ""
    1534        if not with_ties and rows:
    1535            with_ties = " ONLY"
    1536        return f"{percent}{rows}{with_ties}"

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

    1538    def filter_sql(self, expression: exp.Filter) -> str:
    1539        if self.AGGREGATE_FILTER_SUPPORTED:
    1540            this = self.sql(expression, "this")
    1541            where = self.sql(expression, "expression").strip()
    1542            return f"{this} FILTER({where})"
    1543
    1544        agg = expression.this
    1545        agg_arg = agg.this
    1546        cond = expression.expression.this
    1547        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
    1548        return self.sql(agg)

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

    1550    def hint_sql(self, expression: exp.Hint) -> str:
    1551        if not self.QUERY_HINTS:
    1552            self.unsupported("Hints are not supported")
    1553            return ""
    1554
    1555        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"

def indexparameters_sql(self, expression: sqlglot.expressions.IndexParameters) -> str: View Source

    1557    def indexparameters_sql(self, expression: exp.IndexParameters) -> str:
    1558        using = self.sql(expression, "using")
    1559        using = f" USING {using}" if using else ""
    1560        columns = self.expressions(expression, key="columns", flat=True)
    1561        columns = f"({columns})" if columns else ""
    1562        partition_by = self.expressions(expression, key="partition_by", flat=True)
    1563        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
    1564        where = self.sql(expression, "where")
    1565        include = self.expressions(expression, key="include", flat=True)
    1566        if include:
    1567            include = f" INCLUDE ({include})"
    1568        with_storage = self.expressions(expression, key="with_storage", flat=True)
    1569        with_storage = f" WITH ({with_storage})" if with_storage else ""
    1570        tablespace = self.sql(expression, "tablespace")
    1571        tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else ""
    1572        on = self.sql(expression, "on")
    1573        on = f" ON {on}" if on else ""
    1574
    1575        return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"

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

    1577    def index_sql(self, expression: exp.Index) -> str:
    1578        unique = "UNIQUE " if expression.args.get("unique") else ""
    1579        primary = "PRIMARY " if expression.args.get("primary") else ""
    1580        amp = "AMP " if expression.args.get("amp") else ""
    1581        name = self.sql(expression, "this")
    1582        name = f"{name} " if name else ""
    1583        table = self.sql(expression, "table")
    1584        table = f"{self.INDEX_ON} {table}" if table else ""
    1585
    1586        index = "INDEX " if not table else ""
    1587
    1588        params = self.sql(expression, "params")
    1589        return f"{unique}{primary}{amp}{index}{name}{table}{params}"

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

    1591    def identifier_sql(self, expression: exp.Identifier) -> str:
    1592        text = expression.name
    1593        lower = text.lower()
    1594        text = lower if self.normalize and not expression.quoted else text
    1595        text = text.replace(self._identifier_end, self._escaped_identifier_end)
    1596        if (
    1597            expression.quoted
    1598            or self.dialect.can_identify(text, self.identify)
    1599            or lower in self.RESERVED_KEYWORDS
    1600            or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
    1601        ):
    1602            text = f"{self._identifier_start}{text}{self._identifier_end}"
    1603        return text

def hex_sql(self, expression: sqlglot.expressions.Hex) -> str: View Source

    1605    def hex_sql(self, expression: exp.Hex) -> str:
    1606        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1607        if self.dialect.HEX_LOWERCASE:
    1608            text = self.func("LOWER", text)
    1609
    1610        return text

def lowerhex_sql(self, expression: sqlglot.expressions.LowerHex) -> str: View Source

    1612    def lowerhex_sql(self, expression: exp.LowerHex) -> str:
    1613        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1614        if not self.dialect.HEX_LOWERCASE:
    1615            text = self.func("LOWER", text)
    1616        return text

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

    1618    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    1619        input_format = self.sql(expression, "input_format")
    1620        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    1621        output_format = self.sql(expression, "output_format")
    1622        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    1623        return self.sep().join((input_format, output_format))

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

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

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

    1629    def partition_sql(self, expression: exp.Partition) -> str:
    1630        partition_keyword = "SUBPARTITION" if expression.args.get("subpartition") else "PARTITION"
    1631        return f"{partition_keyword}({self.expressions(expression, flat=True)})"

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

    1633    def properties_sql(self, expression: exp.Properties) -> str:
    1634        root_properties = []
    1635        with_properties = []
    1636
    1637        for p in expression.expressions:
    1638            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1639            if p_loc == exp.Properties.Location.POST_WITH:
    1640                with_properties.append(p)
    1641            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    1642                root_properties.append(p)
    1643
    1644        root_props = self.root_properties(exp.Properties(expressions=root_properties))
    1645        with_props = self.with_properties(exp.Properties(expressions=with_properties))
    1646
    1647        if root_props and with_props and not self.pretty:
    1648            with_props = " " + with_props
    1649
    1650        return root_props + with_props

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

    1652    def root_properties(self, properties: exp.Properties) -> str:
    1653        if properties.expressions:
    1654            return self.expressions(properties, indent=False, sep=" ")
    1655        return ""

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

    1657    def properties(
    1658        self,
    1659        properties: exp.Properties,
    1660        prefix: str = "",
    1661        sep: str = ", ",
    1662        suffix: str = "",
    1663        wrapped: bool = True,
    1664    ) -> str:
    1665        if properties.expressions:
    1666            expressions = self.expressions(properties, sep=sep, indent=False)
    1667            if expressions:
    1668                expressions = self.wrap(expressions) if wrapped else expressions
    1669                return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}"
    1670        return ""

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

    1672    def with_properties(self, properties: exp.Properties) -> str:
    1673        return self.properties(properties, prefix=self.seg(self.WITH_PROPERTIES_PREFIX, sep=""))

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

    1675    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
    1676        properties_locs = defaultdict(list)
    1677        for p in properties.expressions:
    1678            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1679            if p_loc != exp.Properties.Location.UNSUPPORTED:
    1680                properties_locs[p_loc].append(p)
    1681            else:
    1682                self.unsupported(f"Unsupported property {p.key}")
    1683
    1684        return properties_locs

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

    1686    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
    1687        if isinstance(expression.this, exp.Dot):
    1688            return self.sql(expression, "this")
    1689        return f"'{expression.name}'" if string_key else expression.name

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

    1691    def property_sql(self, expression: exp.Property) -> str:
    1692        property_cls = expression.__class__
    1693        if property_cls == exp.Property:
    1694            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
    1695
    1696        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    1697        if not property_name:
    1698            self.unsupported(f"Unsupported property {expression.key}")
    1699
    1700        return f"{property_name}={self.sql(expression, 'this')}"

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

    1702    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
    1703        if self.SUPPORTS_CREATE_TABLE_LIKE:
    1704            options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
    1705            options = f" {options}" if options else ""
    1706
    1707            like = f"LIKE {self.sql(expression, 'this')}{options}"
    1708            if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema):
    1709                like = f"({like})"
    1710
    1711            return like
    1712
    1713        if expression.expressions:
    1714            self.unsupported("Transpilation of LIKE property options is unsupported")
    1715
    1716        select = exp.select("*").from_(expression.this).limit(0)
    1717        return f"AS {self.sql(select)}"

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

    1719    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1720        no = "NO " if expression.args.get("no") else ""
    1721        protection = " PROTECTION" if expression.args.get("protection") else ""
    1722        return f"{no}FALLBACK{protection}"

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

    1724    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1725        no = "NO " if expression.args.get("no") else ""
    1726        local = expression.args.get("local")
    1727        local = f"{local} " if local else ""
    1728        dual = "DUAL " if expression.args.get("dual") else ""
    1729        before = "BEFORE " if expression.args.get("before") else ""
    1730        after = "AFTER " if expression.args.get("after") else ""
    1731        return f"{no}{local}{dual}{before}{after}JOURNAL"

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

    1733    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1734        freespace = self.sql(expression, "this")
    1735        percent = " PERCENT" if expression.args.get("percent") else ""
    1736        return f"FREESPACE={freespace}{percent}"

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

    1738    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1739        if expression.args.get("default"):
    1740            property = "DEFAULT"
    1741        elif expression.args.get("on"):
    1742            property = "ON"
    1743        else:
    1744            property = "OFF"
    1745        return f"CHECKSUM={property}"

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

    1747    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1748        if expression.args.get("no"):
    1749            return "NO MERGEBLOCKRATIO"
    1750        if expression.args.get("default"):
    1751            return "DEFAULT MERGEBLOCKRATIO"
    1752
    1753        percent = " PERCENT" if expression.args.get("percent") else ""
    1754        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"

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

    1756    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1757        default = expression.args.get("default")
    1758        minimum = expression.args.get("minimum")
    1759        maximum = expression.args.get("maximum")
    1760        if default or minimum or maximum:
    1761            if default:
    1762                prop = "DEFAULT"
    1763            elif minimum:
    1764                prop = "MINIMUM"
    1765            else:
    1766                prop = "MAXIMUM"
    1767            return f"{prop} DATABLOCKSIZE"
    1768        units = expression.args.get("units")
    1769        units = f" {units}" if units else ""
    1770        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"

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

    1772    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1773        autotemp = expression.args.get("autotemp")
    1774        always = expression.args.get("always")
    1775        default = expression.args.get("default")
    1776        manual = expression.args.get("manual")
    1777        never = expression.args.get("never")
    1778
    1779        if autotemp is not None:
    1780            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1781        elif always:
    1782            prop = "ALWAYS"
    1783        elif default:
    1784            prop = "DEFAULT"
    1785        elif manual:
    1786            prop = "MANUAL"
    1787        elif never:
    1788            prop = "NEVER"
    1789        return f"BLOCKCOMPRESSION={prop}"

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

    1791    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1792        no = expression.args.get("no")
    1793        no = " NO" if no else ""
    1794        concurrent = expression.args.get("concurrent")
    1795        concurrent = " CONCURRENT" if concurrent else ""
    1796        target = self.sql(expression, "target")
    1797        target = f" {target}" if target else ""
    1798        return f"WITH{no}{concurrent} ISOLATED LOADING{target}"

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

    1800    def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str:
    1801        if isinstance(expression.this, list):
    1802            return f"IN ({self.expressions(expression, key='this', flat=True)})"
    1803        if expression.this:
    1804            modulus = self.sql(expression, "this")
    1805            remainder = self.sql(expression, "expression")
    1806            return f"WITH (MODULUS {modulus}, REMAINDER {remainder})"
    1807
    1808        from_expressions = self.expressions(expression, key="from_expressions", flat=True)
    1809        to_expressions = self.expressions(expression, key="to_expressions", flat=True)
    1810        return f"FROM ({from_expressions}) TO ({to_expressions})"

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

    1812    def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str:
    1813        this = self.sql(expression, "this")
    1814
    1815        for_values_or_default = expression.expression
    1816        if isinstance(for_values_or_default, exp.PartitionBoundSpec):
    1817            for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}"
    1818        else:
    1819            for_values_or_default = " DEFAULT"
    1820
    1821        return f"PARTITION OF {this}{for_values_or_default}"

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

    1823    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1824        kind = expression.args.get("kind")
    1825        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1826        for_or_in = expression.args.get("for_or_in")
    1827        for_or_in = f" {for_or_in}" if for_or_in else ""
    1828        lock_type = expression.args.get("lock_type")
    1829        override = " OVERRIDE" if expression.args.get("override") else ""
    1830        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"

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

    1832    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1833        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1834        statistics = expression.args.get("statistics")
    1835        statistics_sql = ""
    1836        if statistics is not None:
    1837            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1838        return f"{data_sql}{statistics_sql}"

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

    1840    def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str:
    1841        this = self.sql(expression, "this")
    1842        this = f"HISTORY_TABLE={this}" if this else ""
    1843        data_consistency: t.Optional[str] = self.sql(expression, "data_consistency")
    1844        data_consistency = (
    1845            f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None
    1846        )
    1847        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    1848        retention_period = (
    1849            f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None
    1850        )
    1851
    1852        if this:
    1853            on_sql = self.func("ON", this, data_consistency, retention_period)
    1854        else:
    1855            on_sql = "ON" if expression.args.get("on") else "OFF"
    1856
    1857        sql = f"SYSTEM_VERSIONING={on_sql}"
    1858
    1859        return f"WITH({sql})" if expression.args.get("with") else sql

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

    1861    def insert_sql(self, expression: exp.Insert) -> str:
    1862        hint = self.sql(expression, "hint")
    1863        overwrite = expression.args.get("overwrite")
    1864
    1865        if isinstance(expression.this, exp.Directory):
    1866            this = " OVERWRITE" if overwrite else " INTO"
    1867        else:
    1868            this = self.INSERT_OVERWRITE if overwrite else " INTO"
    1869
    1870        stored = self.sql(expression, "stored")
    1871        stored = f" {stored}" if stored else ""
    1872        alternative = expression.args.get("alternative")
    1873        alternative = f" OR {alternative}" if alternative else ""
    1874        ignore = " IGNORE" if expression.args.get("ignore") else ""
    1875        is_function = expression.args.get("is_function")
    1876        if is_function:
    1877            this = f"{this} FUNCTION"
    1878        this = f"{this} {self.sql(expression, 'this')}"
    1879
    1880        exists = " IF EXISTS" if expression.args.get("exists") else ""
    1881        where = self.sql(expression, "where")
    1882        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
    1883        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
    1884        on_conflict = self.sql(expression, "conflict")
    1885        on_conflict = f" {on_conflict}" if on_conflict else ""
    1886        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1887        returning = self.sql(expression, "returning")
    1888
    1889        if self.RETURNING_END:
    1890            expression_sql = f"{expression_sql}{on_conflict}{returning}"
    1891        else:
    1892            expression_sql = f"{returning}{expression_sql}{on_conflict}"
    1893
    1894        partition_by = self.sql(expression, "partition")
    1895        partition_by = f" {partition_by}" if partition_by else ""
    1896        settings = self.sql(expression, "settings")
    1897        settings = f" {settings}" if settings else ""
    1898
    1899        source = self.sql(expression, "source")
    1900        source = f"TABLE {source}" if source else ""
    1901
    1902        sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}"
    1903        return self.prepend_ctes(expression, sql)

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

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

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

    1908    def kill_sql(self, expression: exp.Kill) -> str:
    1909        kind = self.sql(expression, "kind")
    1910        kind = f" {kind}" if kind else ""
    1911        this = self.sql(expression, "this")
    1912        this = f" {this}" if this else ""
    1913        return f"KILL{kind}{this}"

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

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

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

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

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

    1921    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1922        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1923
    1924        constraint = self.sql(expression, "constraint")
    1925        constraint = f" ON CONSTRAINT {constraint}" if constraint else ""
    1926
    1927        conflict_keys = self.expressions(expression, key="conflict_keys", flat=True)
    1928        conflict_keys = f"({conflict_keys}) " if conflict_keys else " "
    1929        action = self.sql(expression, "action")
    1930
    1931        expressions = self.expressions(expression, flat=True)
    1932        if expressions:
    1933            set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
    1934            expressions = f" {set_keyword}{expressions}"
    1935
    1936        where = self.sql(expression, "where")
    1937        return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}"

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

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

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

    1942    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1943        fields = self.sql(expression, "fields")
    1944        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1945        escaped = self.sql(expression, "escaped")
    1946        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1947        items = self.sql(expression, "collection_items")
    1948        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1949        keys = self.sql(expression, "map_keys")
    1950        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1951        lines = self.sql(expression, "lines")
    1952        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1953        null = self.sql(expression, "null")
    1954        null = f" NULL DEFINED AS {null}" if null else ""
    1955        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"

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

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

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

    1960    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1961        this = f"{self.sql(expression, 'this')} INDEX"
    1962        target = self.sql(expression, "target")
    1963        target = f" FOR {target}" if target else ""
    1964        return f"{this}{target} ({self.expressions(expression, flat=True)})"

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

    1966    def historicaldata_sql(self, expression: exp.HistoricalData) -> str:
    1967        this = self.sql(expression, "this")
    1968        kind = self.sql(expression, "kind")
    1969        expr = self.sql(expression, "expression")
    1970        return f"{this} ({kind} => {expr})"

def table_parts(self, expression: sqlglot.expressions.Table) -> str: View Source

    1972    def table_parts(self, expression: exp.Table) -> str:
    1973        return ".".join(
    1974            self.sql(part)
    1975            for part in (
    1976                expression.args.get("catalog"),
    1977                expression.args.get("db"),
    1978                expression.args.get("this"),
    1979            )
    1980            if part is not None
    1981        )

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

    1983    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1984        table = self.table_parts(expression)
    1985        only = "ONLY " if expression.args.get("only") else ""
    1986        partition = self.sql(expression, "partition")
    1987        partition = f" {partition}" if partition else ""
    1988        version = self.sql(expression, "version")
    1989        version = f" {version}" if version else ""
    1990        alias = self.sql(expression, "alias")
    1991        alias = f"{sep}{alias}" if alias else ""
    1992
    1993        sample = self.sql(expression, "sample")
    1994        if self.dialect.ALIAS_POST_TABLESAMPLE:
    1995            sample_pre_alias = sample
    1996            sample_post_alias = ""
    1997        else:
    1998            sample_pre_alias = ""
    1999            sample_post_alias = sample
    2000
    2001        hints = self.expressions(expression, key="hints", sep=" ")
    2002        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
    2003        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    2004        joins = self.indent(
    2005            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
    2006        )
    2007        laterals = self.expressions(expression, key="laterals", sep="")
    2008
    2009        file_format = self.sql(expression, "format")
    2010        if file_format:
    2011            pattern = self.sql(expression, "pattern")
    2012            pattern = f", PATTERN => {pattern}" if pattern else ""
    2013            file_format = f" (FILE_FORMAT => {file_format}{pattern})"
    2014
    2015        ordinality = expression.args.get("ordinality") or ""
    2016        if ordinality:
    2017            ordinality = f" WITH ORDINALITY{alias}"
    2018            alias = ""
    2019
    2020        when = self.sql(expression, "when")
    2021        if when:
    2022            table = f"{table} {when}"
    2023
    2024        changes = self.sql(expression, "changes")
    2025        changes = f" {changes}" if changes else ""
    2026
    2027        rows_from = self.expressions(expression, key="rows_from")
    2028        if rows_from:
    2029            table = f"ROWS FROM {self.wrap(rows_from)}"
    2030
    2031        return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}"

def tablefromrows_sql(self, expression: sqlglot.expressions.TableFromRows) -> str: View Source

    2033    def tablefromrows_sql(self, expression: exp.TableFromRows) -> str:
    2034        table = self.func("TABLE", expression.this)
    2035        alias = self.sql(expression, "alias")
    2036        alias = f" AS {alias}" if alias else ""
    2037        sample = self.sql(expression, "sample")
    2038        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    2039        joins = self.indent(
    2040            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
    2041        )
    2042        return f"{table}{alias}{pivots}{sample}{joins}"

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

    2044    def tablesample_sql(
    2045        self,
    2046        expression: exp.TableSample,
    2047        tablesample_keyword: t.Optional[str] = None,
    2048    ) -> str:
    2049        method = self.sql(expression, "method")
    2050        method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    2051        numerator = self.sql(expression, "bucket_numerator")
    2052        denominator = self.sql(expression, "bucket_denominator")
    2053        field = self.sql(expression, "bucket_field")
    2054        field = f" ON {field}" if field else ""
    2055        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    2056        seed = self.sql(expression, "seed")
    2057        seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else ""
    2058
    2059        size = self.sql(expression, "size")
    2060        if size and self.TABLESAMPLE_SIZE_IS_ROWS:
    2061            size = f"{size} ROWS"
    2062
    2063        percent = self.sql(expression, "percent")
    2064        if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT:
    2065            percent = f"{percent} PERCENT"
    2066
    2067        expr = f"{bucket}{percent}{size}"
    2068        if self.TABLESAMPLE_REQUIRES_PARENS:
    2069            expr = f"({expr})"
    2070
    2071        return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}"

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

    2073    def pivot_sql(self, expression: exp.Pivot) -> str:
    2074        expressions = self.expressions(expression, flat=True)
    2075        direction = "UNPIVOT" if expression.unpivot else "PIVOT"
    2076
    2077        group = self.sql(expression, "group")
    2078
    2079        if expression.this:
    2080            this = self.sql(expression, "this")
    2081            if not expressions:
    2082                return f"UNPIVOT {this}"
    2083
    2084            on = f"{self.seg('ON')} {expressions}"
    2085            into = self.sql(expression, "into")
    2086            into = f"{self.seg('INTO')} {into}" if into else ""
    2087            using = self.expressions(expression, key="using", flat=True)
    2088            using = f"{self.seg('USING')} {using}" if using else ""
    2089            return f"{direction} {this}{on}{into}{using}{group}"
    2090
    2091        alias = self.sql(expression, "alias")
    2092        alias = f" AS {alias}" if alias else ""
    2093
    2094        fields = self.expressions(
    2095            expression,
    2096            "fields",
    2097            sep=" ",
    2098            dynamic=True,
    2099            new_line=True,
    2100            skip_first=True,
    2101            skip_last=True,
    2102        )
    2103
    2104        include_nulls = expression.args.get("include_nulls")
    2105        if include_nulls is not None:
    2106            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
    2107        else:
    2108            nulls = ""
    2109
    2110        default_on_null = self.sql(expression, "default_on_null")
    2111        default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else ""
    2112        return f"{self.seg(direction)}{nulls}({expressions} FOR {fields}{default_on_null}{group}){alias}"

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

    2114    def version_sql(self, expression: exp.Version) -> str:
    2115        this = f"FOR {expression.name}"
    2116        kind = expression.text("kind")
    2117        expr = self.sql(expression, "expression")
    2118        return f"{this} {kind} {expr}"

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

    2120    def tuple_sql(self, expression: exp.Tuple) -> str:
    2121        return f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})"

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

    2123    def update_sql(self, expression: exp.Update) -> str:
    2124        this = self.sql(expression, "this")
    2125        set_sql = self.expressions(expression, flat=True)
    2126        from_sql = self.sql(expression, "from")
    2127        where_sql = self.sql(expression, "where")
    2128        returning = self.sql(expression, "returning")
    2129        order = self.sql(expression, "order")
    2130        limit = self.sql(expression, "limit")
    2131        if self.RETURNING_END:
    2132            expression_sql = f"{from_sql}{where_sql}{returning}"
    2133        else:
    2134            expression_sql = f"{returning}{from_sql}{where_sql}"
    2135        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
    2136        return self.prepend_ctes(expression, sql)

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

    2138    def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str:
    2139        values_as_table = values_as_table and self.VALUES_AS_TABLE
    2140
    2141        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
    2142        if values_as_table or not expression.find_ancestor(exp.From, exp.Join):
    2143            args = self.expressions(expression)
    2144            alias = self.sql(expression, "alias")
    2145            values = f"VALUES{self.seg('')}{args}"
    2146            values = (
    2147                f"({values})"
    2148                if self.WRAP_DERIVED_VALUES
    2149                and (alias or isinstance(expression.parent, (exp.From, exp.Table)))
    2150                else values
    2151            )
    2152            return f"{values} AS {alias}" if alias else values
    2153
    2154        # Converts `VALUES...` expression into a series of select unions.
    2155        alias_node = expression.args.get("alias")
    2156        column_names = alias_node and alias_node.columns
    2157
    2158        selects: t.List[exp.Query] = []
    2159
    2160        for i, tup in enumerate(expression.expressions):
    2161            row = tup.expressions
    2162
    2163            if i == 0 and column_names:
    2164                row = [
    2165                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
    2166                ]
    2167
    2168            selects.append(exp.Select(expressions=row))
    2169
    2170        if self.pretty:
    2171            # This may result in poor performance for large-cardinality `VALUES` tables, due to
    2172            # the deep nesting of the resulting exp.Unions. If this is a problem, either increase
    2173            # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`.
    2174            query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects)
    2175            return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False))
    2176
    2177        alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else ""
    2178        unions = " UNION ALL ".join(self.sql(select) for select in selects)
    2179        return f"({unions}){alias}"

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

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

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

    2184    @unsupported_args("expressions")
    2185    def into_sql(self, expression: exp.Into) -> str:
    2186        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    2187        unlogged = " UNLOGGED" if expression.args.get("unlogged") else ""
    2188        return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"

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

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

def groupingsets_sql(self, expression: sqlglot.expressions.GroupingSets) -> str: View Source

    2193    def groupingsets_sql(self, expression: exp.GroupingSets) -> str:
    2194        grouping_sets = self.expressions(expression, indent=False)
    2195        return f"GROUPING SETS {self.wrap(grouping_sets)}"

def rollup_sql(self, expression: sqlglot.expressions.Rollup) -> str: View Source

    2197    def rollup_sql(self, expression: exp.Rollup) -> str:
    2198        expressions = self.expressions(expression, indent=False)
    2199        return f"ROLLUP {self.wrap(expressions)}" if expressions else "WITH ROLLUP"

def cube_sql(self, expression: sqlglot.expressions.Cube) -> str: View Source

    2201    def cube_sql(self, expression: exp.Cube) -> str:
    2202        expressions = self.expressions(expression, indent=False)
    2203        return f"CUBE {self.wrap(expressions)}" if expressions else "WITH CUBE"

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

    2205    def group_sql(self, expression: exp.Group) -> str:
    2206        group_by_all = expression.args.get("all")
    2207        if group_by_all is True:
    2208            modifier = " ALL"
    2209        elif group_by_all is False:
    2210            modifier = " DISTINCT"
    2211        else:
    2212            modifier = ""
    2213
    2214        group_by = self.op_expressions(f"GROUP BY{modifier}", expression)
    2215
    2216        grouping_sets = self.expressions(expression, key="grouping_sets")
    2217        cube = self.expressions(expression, key="cube")
    2218        rollup = self.expressions(expression, key="rollup")
    2219
    2220        groupings = csv(
    2221            self.seg(grouping_sets) if grouping_sets else "",
    2222            self.seg(cube) if cube else "",
    2223            self.seg(rollup) if rollup else "",
    2224            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    2225            sep=self.GROUPINGS_SEP,
    2226        )
    2227
    2228        if (
    2229            expression.expressions
    2230            and groupings
    2231            and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP")
    2232        ):
    2233            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    2234
    2235        return f"{group_by}{groupings}"

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

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

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

    2241    def connect_sql(self, expression: exp.Connect) -> str:
    2242        start = self.sql(expression, "start")
    2243        start = self.seg(f"START WITH {start}") if start else ""
    2244        nocycle = " NOCYCLE" if expression.args.get("nocycle") else ""
    2245        connect = self.sql(expression, "connect")
    2246        connect = self.seg(f"CONNECT BY{nocycle} {connect}")
    2247        return start + connect

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

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

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

    2252    def join_sql(self, expression: exp.Join) -> str:
    2253        if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"):
    2254            side = None
    2255        else:
    2256            side = expression.side
    2257
    2258        op_sql = " ".join(
    2259            op
    2260            for op in (
    2261                expression.method,
    2262                "GLOBAL" if expression.args.get("global") else None,
    2263                side,
    2264                expression.kind,
    2265                expression.hint if self.JOIN_HINTS else None,
    2266            )
    2267            if op
    2268        )
    2269        match_cond = self.sql(expression, "match_condition")
    2270        match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else ""
    2271        on_sql = self.sql(expression, "on")
    2272        using = expression.args.get("using")
    2273
    2274        if not on_sql and using:
    2275            on_sql = csv(*(self.sql(column) for column in using))
    2276
    2277        this = expression.this
    2278        this_sql = self.sql(this)
    2279
    2280        exprs = self.expressions(expression)
    2281        if exprs:
    2282            this_sql = f"{this_sql},{self.seg(exprs)}"
    2283
    2284        if on_sql:
    2285            on_sql = self.indent(on_sql, skip_first=True)
    2286            space = self.seg(" " * self.pad) if self.pretty else " "
    2287            if using:
    2288                on_sql = f"{space}USING ({on_sql})"
    2289            else:
    2290                on_sql = f"{space}ON {on_sql}"
    2291        elif not op_sql:
    2292            if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None:
    2293                return f" {this_sql}"
    2294
    2295            return f", {this_sql}"
    2296
    2297        if op_sql != "STRAIGHT_JOIN":
    2298            op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    2299
    2300        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    2301        return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}{pivots}"

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

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

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

    2308    def lateral_op(self, expression: exp.Lateral) -> str:
    2309        cross_apply = expression.args.get("cross_apply")
    2310
    2311        # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/
    2312        if cross_apply is True:
    2313            op = "INNER JOIN "
    2314        elif cross_apply is False:
    2315            op = "LEFT JOIN "
    2316        else:
    2317            op = ""
    2318
    2319        return f"{op}LATERAL"

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

    2321    def lateral_sql(self, expression: exp.Lateral) -> str:
    2322        this = self.sql(expression, "this")
    2323
    2324        if expression.args.get("view"):
    2325            alias = expression.args["alias"]
    2326            columns = self.expressions(alias, key="columns", flat=True)
    2327            table = f" {alias.name}" if alias.name else ""
    2328            columns = f" AS {columns}" if columns else ""
    2329            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    2330            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    2331
    2332        alias = self.sql(expression, "alias")
    2333        alias = f" AS {alias}" if alias else ""
    2334
    2335        ordinality = expression.args.get("ordinality") or ""
    2336        if ordinality:
    2337            ordinality = f" WITH ORDINALITY{alias}"
    2338            alias = ""
    2339
    2340        return f"{self.lateral_op(expression)} {this}{alias}{ordinality}"

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

    2342    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    2343        this = self.sql(expression, "this")
    2344
    2345        args = [
    2346            self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e
    2347            for e in (expression.args.get(k) for k in ("offset", "expression"))
    2348            if e
    2349        ]
    2350
    2351        args_sql = ", ".join(self.sql(e) for e in args)
    2352        args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql
    2353        expressions = self.expressions(expression, flat=True)
    2354        limit_options = self.sql(expression, "limit_options")
    2355        expressions = f" BY {expressions}" if expressions else ""
    2356
    2357        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{limit_options}{expressions}"

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

    2359    def offset_sql(self, expression: exp.Offset) -> str:
    2360        this = self.sql(expression, "this")
    2361        value = expression.expression
    2362        value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value
    2363        expressions = self.expressions(expression, flat=True)
    2364        expressions = f" BY {expressions}" if expressions else ""
    2365        return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"

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

    2367    def setitem_sql(self, expression: exp.SetItem) -> str:
    2368        kind = self.sql(expression, "kind")
    2369        kind = f"{kind} " if kind else ""
    2370        this = self.sql(expression, "this")
    2371        expressions = self.expressions(expression)
    2372        collate = self.sql(expression, "collate")
    2373        collate = f" COLLATE {collate}" if collate else ""
    2374        global_ = "GLOBAL " if expression.args.get("global") else ""
    2375        return f"{global_}{kind}{this}{expressions}{collate}"

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

    2377    def set_sql(self, expression: exp.Set) -> str:
    2378        expressions = f" {self.expressions(expression, flat=True)}"
    2379        tag = " TAG" if expression.args.get("tag") else ""
    2380        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"

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

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

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

    2385    def lock_sql(self, expression: exp.Lock) -> str:
    2386        if not self.LOCKING_READS_SUPPORTED:
    2387            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    2388            return ""
    2389
    2390        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    2391        expressions = self.expressions(expression, flat=True)
    2392        expressions = f" OF {expressions}" if expressions else ""
    2393        wait = expression.args.get("wait")
    2394
    2395        if wait is not None:
    2396            if isinstance(wait, exp.Literal):
    2397                wait = f" WAIT {self.sql(wait)}"
    2398            else:
    2399                wait = " NOWAIT" if wait else " SKIP LOCKED"
    2400
    2401        return f"{lock_type}{expressions}{wait or ''}"

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

    2403    def literal_sql(self, expression: exp.Literal) -> str:
    2404        text = expression.this or ""
    2405        if expression.is_string:
    2406            text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}"
    2407        return text

def escape_str(self, text: str, escape_backslash: bool = True) -> str: View Source

    2409    def escape_str(self, text: str, escape_backslash: bool = True) -> str:
    2410        if self.dialect.ESCAPED_SEQUENCES:
    2411            to_escaped = self.dialect.ESCAPED_SEQUENCES
    2412            text = "".join(
    2413                to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text
    2414            )
    2415
    2416        return self._replace_line_breaks(text).replace(
    2417            self.dialect.QUOTE_END, self._escaped_quote_end
    2418        )

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

    2420    def loaddata_sql(self, expression: exp.LoadData) -> str:
    2421        local = " LOCAL" if expression.args.get("local") else ""
    2422        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    2423        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    2424        this = f" INTO TABLE {self.sql(expression, 'this')}"
    2425        partition = self.sql(expression, "partition")
    2426        partition = f" {partition}" if partition else ""
    2427        input_format = self.sql(expression, "input_format")
    2428        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    2429        serde = self.sql(expression, "serde")
    2430        serde = f" SERDE {serde}" if serde else ""
    2431        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"

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

    2433    def null_sql(self, *_) -> str:
    2434        return "NULL"

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

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

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

    2439    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    2440        this = self.sql(expression, "this")
    2441        this = f"{this} " if this else this
    2442        siblings = "SIBLINGS " if expression.args.get("siblings") else ""
    2443        return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat)  # type: ignore

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

    2445    def withfill_sql(self, expression: exp.WithFill) -> str:
    2446        from_sql = self.sql(expression, "from")
    2447        from_sql = f" FROM {from_sql}" if from_sql else ""
    2448        to_sql = self.sql(expression, "to")
    2449        to_sql = f" TO {to_sql}" if to_sql else ""
    2450        step_sql = self.sql(expression, "step")
    2451        step_sql = f" STEP {step_sql}" if step_sql else ""
    2452        interpolated_values = [
    2453            f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}"
    2454            if isinstance(e, exp.Alias)
    2455            else self.sql(e, "this")
    2456            for e in expression.args.get("interpolate") or []
    2457        ]
    2458        interpolate = (
    2459            f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else ""
    2460        )
    2461        return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}"

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

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

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

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

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

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

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

    2472    def ordered_sql(self, expression: exp.Ordered) -> str:
    2473        desc = expression.args.get("desc")
    2474        asc = not desc
    2475
    2476        nulls_first = expression.args.get("nulls_first")
    2477        nulls_last = not nulls_first
    2478        nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large"
    2479        nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small"
    2480        nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last"
    2481
    2482        this = self.sql(expression, "this")
    2483
    2484        sort_order = " DESC" if desc else (" ASC" if desc is False else "")
    2485        nulls_sort_change = ""
    2486        if nulls_first and (
    2487            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
    2488        ):
    2489            nulls_sort_change = " NULLS FIRST"
    2490        elif (
    2491            nulls_last
    2492            and ((asc and nulls_are_small) or (desc and nulls_are_large))
    2493            and not nulls_are_last
    2494        ):
    2495            nulls_sort_change = " NULLS LAST"
    2496
    2497        # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it
    2498        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
    2499            window = expression.find_ancestor(exp.Window, exp.Select)
    2500            if isinstance(window, exp.Window) and window.args.get("spec"):
    2501                self.unsupported(
    2502                    f"'{nulls_sort_change.strip()}' translation not supported in window functions"
    2503                )
    2504                nulls_sort_change = ""
    2505            elif self.NULL_ORDERING_SUPPORTED is False and (
    2506                (asc and nulls_sort_change == " NULLS LAST")
    2507                or (desc and nulls_sort_change == " NULLS FIRST")
    2508            ):
    2509                # BigQuery does not allow these ordering/nulls combinations when used under
    2510                # an aggregation func or under a window containing one
    2511                ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select)
    2512
    2513                if isinstance(ancestor, exp.Window):
    2514                    ancestor = ancestor.this
    2515                if isinstance(ancestor, exp.AggFunc):
    2516                    self.unsupported(
    2517                        f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order"
    2518                    )
    2519                    nulls_sort_change = ""
    2520            elif self.NULL_ORDERING_SUPPORTED is None:
    2521                if expression.this.is_int:
    2522                    self.unsupported(
    2523                        f"'{nulls_sort_change.strip()}' translation not supported with positional ordering"
    2524                    )
    2525                elif not isinstance(expression.this, exp.Rand):
    2526                    null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else ""
    2527                    this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}"
    2528                nulls_sort_change = ""
    2529
    2530        with_fill = self.sql(expression, "with_fill")
    2531        with_fill = f" {with_fill}" if with_fill else ""
    2532
    2533        return f"{this}{sort_order}{nulls_sort_change}{with_fill}"

def matchrecognizemeasure_sql(self, expression: sqlglot.expressions.MatchRecognizeMeasure) -> str: View Source

    2535    def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str:
    2536        window_frame = self.sql(expression, "window_frame")
    2537        window_frame = f"{window_frame} " if window_frame else ""
    2538
    2539        this = self.sql(expression, "this")
    2540
    2541        return f"{window_frame}{this}"

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

    2543    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    2544        partition = self.partition_by_sql(expression)
    2545        order = self.sql(expression, "order")
    2546        measures = self.expressions(expression, key="measures")
    2547        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    2548        rows = self.sql(expression, "rows")
    2549        rows = self.seg(rows) if rows else ""
    2550        after = self.sql(expression, "after")
    2551        after = self.seg(after) if after else ""
    2552        pattern = self.sql(expression, "pattern")
    2553        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    2554        definition_sqls = [
    2555            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    2556            for definition in expression.args.get("define", [])
    2557        ]
    2558        definitions = self.expressions(sqls=definition_sqls)
    2559        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    2560        body = "".join(
    2561            (
    2562                partition,
    2563                order,
    2564                measures,
    2565                rows,
    2566                after,
    2567                pattern,
    2568                define,
    2569            )
    2570        )
    2571        alias = self.sql(expression, "alias")
    2572        alias = f" {alias}" if alias else ""
    2573        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"

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

    2575    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    2576        limit = expression.args.get("limit")
    2577
    2578        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    2579            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
    2580        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    2581            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
    2582
    2583        return csv(
    2584            *sqls,
    2585            *[self.sql(join) for join in expression.args.get("joins") or []],
    2586            self.sql(expression, "match"),
    2587            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    2588            self.sql(expression, "prewhere"),
    2589            self.sql(expression, "where"),
    2590            self.sql(expression, "connect"),
    2591            self.sql(expression, "group"),
    2592            self.sql(expression, "having"),
    2593            *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()],
    2594            self.sql(expression, "order"),
    2595            *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit),
    2596            *self.after_limit_modifiers(expression),
    2597            self.options_modifier(expression),
    2598            sep="",
    2599        )

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

    2601    def options_modifier(self, expression: exp.Expression) -> str:
    2602        options = self.expressions(expression, key="options")
    2603        return f" {options}" if options else ""

def queryoption_sql(self, expression: sqlglot.expressions.QueryOption) -> str: View Source

    2605    def queryoption_sql(self, expression: exp.QueryOption) -> str:
    2606        self.unsupported("Unsupported query option.")
    2607        return ""

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

    2609    def offset_limit_modifiers(
    2610        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    2611    ) -> t.List[str]:
    2612        return [
    2613            self.sql(expression, "offset") if fetch else self.sql(limit),
    2614            self.sql(limit) if fetch else self.sql(expression, "offset"),
    2615        ]

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

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

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

    2622    def select_sql(self, expression: exp.Select) -> str:
    2623        into = expression.args.get("into")
    2624        if not self.SUPPORTS_SELECT_INTO and into:
    2625            into.pop()
    2626
    2627        hint = self.sql(expression, "hint")
    2628        distinct = self.sql(expression, "distinct")
    2629        distinct = f" {distinct}" if distinct else ""
    2630        kind = self.sql(expression, "kind")
    2631
    2632        limit = expression.args.get("limit")
    2633        if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP:
    2634            top = self.limit_sql(limit, top=True)
    2635            limit.pop()
    2636        else:
    2637            top = ""
    2638
    2639        expressions = self.expressions(expression)
    2640
    2641        if kind:
    2642            if kind in self.SELECT_KINDS:
    2643                kind = f" AS {kind}"
    2644            else:
    2645                if kind == "STRUCT":
    2646                    expressions = self.expressions(
    2647                        sqls=[
    2648                            self.sql(
    2649                                exp.Struct(
    2650                                    expressions=[
    2651                                        exp.PropertyEQ(this=e.args.get("alias"), expression=e.this)
    2652                                        if isinstance(e, exp.Alias)
    2653                                        else e
    2654                                        for e in expression.expressions
    2655                                    ]
    2656                                )
    2657                            )
    2658                        ]
    2659                    )
    2660                kind = ""
    2661
    2662        operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ")
    2663        operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else ""
    2664
    2665        # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata
    2666        # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first.
    2667        top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}"
    2668        expressions = f"{self.sep()}{expressions}" if expressions else expressions
    2669        sql = self.query_modifiers(
    2670            expression,
    2671            f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}",
    2672            self.sql(expression, "into", comment=False),
    2673            self.sql(expression, "from", comment=False),
    2674        )
    2675
    2676        # If both the CTE and SELECT clauses have comments, generate the latter earlier
    2677        if expression.args.get("with"):
    2678            sql = self.maybe_comment(sql, expression)
    2679            expression.pop_comments()
    2680
    2681        sql = self.prepend_ctes(expression, sql)
    2682
    2683        if not self.SUPPORTS_SELECT_INTO and into:
    2684            if into.args.get("temporary"):
    2685                table_kind = " TEMPORARY"
    2686            elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"):
    2687                table_kind = " UNLOGGED"
    2688            else:
    2689                table_kind = ""
    2690            sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}"
    2691
    2692        return sql

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

    2694    def schema_sql(self, expression: exp.Schema) -> str:
    2695        this = self.sql(expression, "this")
    2696        sql = self.schema_columns_sql(expression)
    2697        return f"{this} {sql}" if this and sql else this or sql

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

    2699    def schema_columns_sql(self, expression: exp.Schema) -> str:
    2700        if expression.expressions:
    2701            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
    2702        return ""

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

    2704    def star_sql(self, expression: exp.Star) -> str:
    2705        except_ = self.expressions(expression, key="except", flat=True)
    2706        except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else ""
    2707        replace = self.expressions(expression, key="replace", flat=True)
    2708        replace = f"{self.seg('REPLACE')} ({replace})" if replace else ""
    2709        rename = self.expressions(expression, key="rename", flat=True)
    2710        rename = f"{self.seg('RENAME')} ({rename})" if rename else ""
    2711        return f"*{except_}{replace}{rename}"

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

    2713    def parameter_sql(self, expression: exp.Parameter) -> str:
    2714        this = self.sql(expression, "this")
    2715        return f"{self.PARAMETER_TOKEN}{this}"

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

    2717    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    2718        this = self.sql(expression, "this")
    2719        kind = expression.text("kind")
    2720        if kind:
    2721            kind = f"{kind}."
    2722        return f"@@{kind}{this}"

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

    2724    def placeholder_sql(self, expression: exp.Placeholder) -> str:
    2725        return f"{self.NAMED_PLACEHOLDER_TOKEN}{expression.name}" if expression.this else "?"

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

    2727    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    2728        alias = self.sql(expression, "alias")
    2729        alias = f"{sep}{alias}" if alias else ""
    2730        sample = self.sql(expression, "sample")
    2731        if self.dialect.ALIAS_POST_TABLESAMPLE and sample:
    2732            alias = f"{sample}{alias}"
    2733
    2734            # Set to None so it's not generated again by self.query_modifiers()
    2735            expression.set("sample", None)
    2736
    2737        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    2738        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    2739        return self.prepend_ctes(expression, sql)

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

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

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

    2745    def unnest_sql(self, expression: exp.Unnest) -> str:
    2746        args = self.expressions(expression, flat=True)
    2747
    2748        alias = expression.args.get("alias")
    2749        offset = expression.args.get("offset")
    2750
    2751        if self.UNNEST_WITH_ORDINALITY:
    2752            if alias and isinstance(offset, exp.Expression):
    2753                alias.append("columns", offset)
    2754
    2755        if alias and self.dialect.UNNEST_COLUMN_ONLY:
    2756            columns = alias.columns
    2757            alias = self.sql(columns[0]) if columns else ""
    2758        else:
    2759            alias = self.sql(alias)
    2760
    2761        alias = f" AS {alias}" if alias else alias
    2762        if self.UNNEST_WITH_ORDINALITY:
    2763            suffix = f" WITH ORDINALITY{alias}" if offset else alias
    2764        else:
    2765            if isinstance(offset, exp.Expression):
    2766                suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}"
    2767            elif offset:
    2768                suffix = f"{alias} WITH OFFSET"
    2769            else:
    2770                suffix = alias
    2771
    2772        return f"UNNEST({args}){suffix}"

def prewhere_sql(self, expression: sqlglot.expressions.PreWhere) -> str: View Source

    2774    def prewhere_sql(self, expression: exp.PreWhere) -> str:
    2775        return ""

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

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

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

    2781    def window_sql(self, expression: exp.Window) -> str:
    2782        this = self.sql(expression, "this")
    2783        partition = self.partition_by_sql(expression)
    2784        order = expression.args.get("order")
    2785        order = self.order_sql(order, flat=True) if order else ""
    2786        spec = self.sql(expression, "spec")
    2787        alias = self.sql(expression, "alias")
    2788        over = self.sql(expression, "over") or "OVER"
    2789
    2790        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    2791
    2792        first = expression.args.get("first")
    2793        if first is None:
    2794            first = ""
    2795        else:
    2796            first = "FIRST" if first else "LAST"
    2797
    2798        if not partition and not order and not spec and alias:
    2799            return f"{this} {alias}"
    2800
    2801        args = self.format_args(
    2802            *[arg for arg in (alias, first, partition, order, spec) if arg], sep=" "
    2803        )
    2804        return f"{this} ({args})"

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

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

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

    2810    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    2811        kind = self.sql(expression, "kind")
    2812        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    2813        end = (
    2814            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    2815            or "CURRENT ROW"
    2816        )
    2817
    2818        window_spec = f"{kind} BETWEEN {start} AND {end}"
    2819
    2820        exclude = self.sql(expression, "exclude")
    2821        if exclude:
    2822            if self.SUPPORTS_WINDOW_EXCLUDE:
    2823                window_spec += f" EXCLUDE {exclude}"
    2824            else:
    2825                self.unsupported("EXCLUDE clause is not supported in the WINDOW clause")
    2826
    2827        return window_spec

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

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

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

    2834    def between_sql(self, expression: exp.Between) -> str:
    2835        this = self.sql(expression, "this")
    2836        low = self.sql(expression, "low")
    2837        high = self.sql(expression, "high")
    2838        return f"{this} BETWEEN {low} AND {high}"

def bracket_offset_expressions( self, expression: sqlglot.expressions.Bracket, index_offset: Optional[int] = None) -> List[sqlglot.expressions.Expression]: View Source

    2840    def bracket_offset_expressions(
    2841        self, expression: exp.Bracket, index_offset: t.Optional[int] = None
    2842    ) -> t.List[exp.Expression]:
    2843        return apply_index_offset(
    2844            expression.this,
    2845            expression.expressions,
    2846            (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0),
    2847            dialect=self.dialect,
    2848        )

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

    2850    def bracket_sql(self, expression: exp.Bracket) -> str:
    2851        expressions = self.bracket_offset_expressions(expression)
    2852        expressions_sql = ", ".join(self.sql(e) for e in expressions)
    2853        return f"{self.sql(expression, 'this')}[{expressions_sql}]"

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

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

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

    2858    def any_sql(self, expression: exp.Any) -> str:
    2859        this = self.sql(expression, "this")
    2860        if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)):
    2861            if isinstance(expression.this, exp.UNWRAPPED_QUERIES):
    2862                this = self.wrap(this)
    2863            return f"ANY{this}"
    2864        return f"ANY {this}"

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

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

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

    2869    def case_sql(self, expression: exp.Case) -> str:
    2870        this = self.sql(expression, "this")
    2871        statements = [f"CASE {this}" if this else "CASE"]
    2872
    2873        for e in expression.args["ifs"]:
    2874            statements.append(f"WHEN {self.sql(e, 'this')}")
    2875            statements.append(f"THEN {self.sql(e, 'true')}")
    2876
    2877        default = self.sql(expression, "default")
    2878
    2879        if default:
    2880            statements.append(f"ELSE {default}")
    2881
    2882        statements.append("END")
    2883
    2884        if self.pretty and self.too_wide(statements):
    2885            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    2886
    2887        return " ".join(statements)

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

    2889    def constraint_sql(self, expression: exp.Constraint) -> str:
    2890        this = self.sql(expression, "this")
    2891        expressions = self.expressions(expression, flat=True)
    2892        return f"CONSTRAINT {this} {expressions}"

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

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

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

    2899    def extract_sql(self, expression: exp.Extract) -> str:
    2900        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
    2901        expression_sql = self.sql(expression, "expression")
    2902        return f"EXTRACT({this} FROM {expression_sql})"

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

    2904    def trim_sql(self, expression: exp.Trim) -> str:
    2905        trim_type = self.sql(expression, "position")
    2906
    2907        if trim_type == "LEADING":
    2908            func_name = "LTRIM"
    2909        elif trim_type == "TRAILING":
    2910            func_name = "RTRIM"
    2911        else:
    2912            func_name = "TRIM"
    2913
    2914        return self.func(func_name, expression.this, expression.expression)

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

    2916    def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]:
    2917        args = expression.expressions
    2918        if isinstance(expression, exp.ConcatWs):
    2919            args = args[1:]  # Skip the delimiter
    2920
    2921        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    2922            args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args]
    2923
    2924        if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"):
    2925            args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args]
    2926
    2927        return args

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

    2929    def concat_sql(self, expression: exp.Concat) -> str:
    2930        expressions = self.convert_concat_args(expression)
    2931
    2932        # Some dialects don't allow a single-argument CONCAT call
    2933        if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1:
    2934            return self.sql(expressions[0])
    2935
    2936        return self.func("CONCAT", *expressions)

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

    2938    def concatws_sql(self, expression: exp.ConcatWs) -> str:
    2939        return self.func(
    2940            "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression)
    2941        )

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

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

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

    2947    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    2948        expressions = self.expressions(expression, flat=True)
    2949        expressions = f" ({expressions})" if expressions else ""
    2950        reference = self.sql(expression, "reference")
    2951        reference = f" {reference}" if reference else ""
    2952        delete = self.sql(expression, "delete")
    2953        delete = f" ON DELETE {delete}" if delete else ""
    2954        update = self.sql(expression, "update")
    2955        update = f" ON UPDATE {update}" if update else ""
    2956        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2957        options = f" {options}" if options else ""
    2958        return f"FOREIGN KEY{expressions}{reference}{delete}{update}{options}"

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

    2960    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    2961        expressions = self.expressions(expression, flat=True)
    2962        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2963        options = f" {options}" if options else ""
    2964        return f"PRIMARY KEY ({expressions}){options}"

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

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

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

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

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

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

def jsonpath_sql(self, expression: sqlglot.expressions.JSONPath) -> str: View Source

    2977    def jsonpath_sql(self, expression: exp.JSONPath) -> str:
    2978        path = self.expressions(expression, sep="", flat=True).lstrip(".")
    2979
    2980        if expression.args.get("escape"):
    2981            path = self.escape_str(path)
    2982
    2983        if self.QUOTE_JSON_PATH:
    2984            path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"
    2985
    2986        return path

def json_path_part(self, expression: int | str | sqlglot.expressions.JSONPathPart) -> str: View Source

    2988    def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str:
    2989        if isinstance(expression, exp.JSONPathPart):
    2990            transform = self.TRANSFORMS.get(expression.__class__)
    2991            if not callable(transform):
    2992                self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}")
    2993                return ""
    2994
    2995            return transform(self, expression)
    2996
    2997        if isinstance(expression, int):
    2998            return str(expression)
    2999
    3000        if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE:
    3001            escaped = expression.replace("'", "\\'")
    3002            escaped = f"\\'{expression}\\'"
    3003        else:
    3004            escaped = expression.replace('"', '\\"')
    3005            escaped = f'"{escaped}"'
    3006
    3007        return escaped

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

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

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

    3012    def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str:
    3013        null_handling = expression.args.get("null_handling")
    3014        null_handling = f" {null_handling}" if null_handling else ""
    3015
    3016        unique_keys = expression.args.get("unique_keys")
    3017        if unique_keys is not None:
    3018            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    3019        else:
    3020            unique_keys = ""
    3021
    3022        return_type = self.sql(expression, "return_type")
    3023        return_type = f" RETURNING {return_type}" if return_type else ""
    3024        encoding = self.sql(expression, "encoding")
    3025        encoding = f" ENCODING {encoding}" if encoding else ""
    3026
    3027        return self.func(
    3028            "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG",
    3029            *expression.expressions,
    3030            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
    3031        )

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

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

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

    3036    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
    3037        null_handling = expression.args.get("null_handling")
    3038        null_handling = f" {null_handling}" if null_handling else ""
    3039        return_type = self.sql(expression, "return_type")
    3040        return_type = f" RETURNING {return_type}" if return_type else ""
    3041        strict = " STRICT" if expression.args.get("strict") else ""
    3042        return self.func(
    3043            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
    3044        )

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

    3046    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
    3047        this = self.sql(expression, "this")
    3048        order = self.sql(expression, "order")
    3049        null_handling = expression.args.get("null_handling")
    3050        null_handling = f" {null_handling}" if null_handling else ""
    3051        return_type = self.sql(expression, "return_type")
    3052        return_type = f" RETURNING {return_type}" if return_type else ""
    3053        strict = " STRICT" if expression.args.get("strict") else ""
    3054        return self.func(
    3055            "JSON_ARRAYAGG",
    3056            this,
    3057            suffix=f"{order}{null_handling}{return_type}{strict})",
    3058        )

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

    3060    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
    3061        path = self.sql(expression, "path")
    3062        path = f" PATH {path}" if path else ""
    3063        nested_schema = self.sql(expression, "nested_schema")
    3064
    3065        if nested_schema:
    3066            return f"NESTED{path} {nested_schema}"
    3067
    3068        this = self.sql(expression, "this")
    3069        kind = self.sql(expression, "kind")
    3070        kind = f" {kind}" if kind else ""
    3071        return f"{this}{kind}{path}"

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

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

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

    3076    def jsontable_sql(self, expression: exp.JSONTable) -> str:
    3077        this = self.sql(expression, "this")
    3078        path = self.sql(expression, "path")
    3079        path = f", {path}" if path else ""
    3080        error_handling = expression.args.get("error_handling")
    3081        error_handling = f" {error_handling}" if error_handling else ""
    3082        empty_handling = expression.args.get("empty_handling")
    3083        empty_handling = f" {empty_handling}" if empty_handling else ""
    3084        schema = self.sql(expression, "schema")
    3085        return self.func(
    3086            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
    3087        )

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

    3089    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    3090        this = self.sql(expression, "this")
    3091        kind = self.sql(expression, "kind")
    3092        path = self.sql(expression, "path")
    3093        path = f" {path}" if path else ""
    3094        as_json = " AS JSON" if expression.args.get("as_json") else ""
    3095        return f"{this} {kind}{path}{as_json}"

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

    3097    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    3098        this = self.sql(expression, "this")
    3099        path = self.sql(expression, "path")
    3100        path = f", {path}" if path else ""
    3101        expressions = self.expressions(expression)
    3102        with_ = (
    3103            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    3104            if expressions
    3105            else ""
    3106        )
    3107        return f"OPENJSON({this}{path}){with_}"

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

    3109    def in_sql(self, expression: exp.In) -> str:
    3110        query = expression.args.get("query")
    3111        unnest = expression.args.get("unnest")
    3112        field = expression.args.get("field")
    3113        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    3114
    3115        if query:
    3116            in_sql = self.sql(query)
    3117        elif unnest:
    3118            in_sql = self.in_unnest_op(unnest)
    3119        elif field:
    3120            in_sql = self.sql(field)
    3121        else:
    3122            in_sql = f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})"
    3123
    3124        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"

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

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

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

    3129    def interval_sql(self, expression: exp.Interval) -> str:
    3130        unit = self.sql(expression, "unit")
    3131        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    3132            unit = self.TIME_PART_SINGULARS.get(unit, unit)
    3133        unit = f" {unit}" if unit else ""
    3134
    3135        if self.SINGLE_STRING_INTERVAL:
    3136            this = expression.this.name if expression.this else ""
    3137            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    3138
    3139        this = self.sql(expression, "this")
    3140        if this:
    3141            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    3142            this = f" {this}" if unwrapped else f" ({this})"
    3143
    3144        return f"INTERVAL{this}{unit}"

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

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

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

    3149    def reference_sql(self, expression: exp.Reference) -> str:
    3150        this = self.sql(expression, "this")
    3151        expressions = self.expressions(expression, flat=True)
    3152        expressions = f"({expressions})" if expressions else ""
    3153        options = self.expressions(expression, key="options", flat=True, sep=" ")
    3154        options = f" {options}" if options else ""
    3155        return f"REFERENCES {this}{expressions}{options}"

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

    3157    def anonymous_sql(self, expression: exp.Anonymous) -> str:
    3158        # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive
    3159        parent = expression.parent
    3160        is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression
    3161        return self.func(
    3162            self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified
    3163        )

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

    3165    def paren_sql(self, expression: exp.Paren) -> str:
    3166        sql = self.seg(self.indent(self.sql(expression, "this")), sep="")
    3167        return f"({sql}{self.seg(')', sep='')}"

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

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

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

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

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

    3178    def alias_sql(self, expression: exp.Alias) -> str:
    3179        alias = self.sql(expression, "alias")
    3180        alias = f" AS {alias}" if alias else ""
    3181        return f"{self.sql(expression, 'this')}{alias}"

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

    3183    def pivotalias_sql(self, expression: exp.PivotAlias) -> str:
    3184        alias = expression.args["alias"]
    3185
    3186        parent = expression.parent
    3187        pivot = parent and parent.parent
    3188
    3189        if isinstance(pivot, exp.Pivot) and pivot.unpivot:
    3190            identifier_alias = isinstance(alias, exp.Identifier)
    3191            literal_alias = isinstance(alias, exp.Literal)
    3192
    3193            if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    3194                alias.replace(exp.Literal.string(alias.output_name))
    3195            elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    3196                alias.replace(exp.to_identifier(alias.output_name))
    3197
    3198        return self.alias_sql(expression)

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

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

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

    3203    def atindex_sql(self, expression: exp.AtTimeZone) -> str:
    3204        this = self.sql(expression, "this")
    3205        index = self.sql(expression, "expression")
    3206        return f"{this} AT {index}"

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

    3208    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    3209        this = self.sql(expression, "this")
    3210        zone = self.sql(expression, "zone")
    3211        return f"{this} AT TIME ZONE {zone}"

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

    3213    def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str:
    3214        this = self.sql(expression, "this")
    3215        zone = self.sql(expression, "zone")
    3216        return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'"

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

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

def and_sql( self, expression: sqlglot.expressions.And, stack: Optional[List[str | sqlglot.expressions.Expression]] = None) -> str: View Source

    3221    def and_sql(
    3222        self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None
    3223    ) -> str:
    3224        return self.connector_sql(expression, "AND", stack)

def or_sql( self, expression: sqlglot.expressions.Or, stack: Optional[List[str | sqlglot.expressions.Expression]] = None) -> str: View Source

    3226    def or_sql(
    3227        self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None
    3228    ) -> str:
    3229        return self.connector_sql(expression, "OR", stack)

def xor_sql( self, expression: sqlglot.expressions.Xor, stack: Optional[List[str | sqlglot.expressions.Expression]] = None) -> str: View Source

    3231    def xor_sql(
    3232        self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None
    3233    ) -> str:
    3234        return self.connector_sql(expression, "XOR", stack)

def connector_sql( self, expression: sqlglot.expressions.Connector, op: str, stack: Optional[List[str | sqlglot.expressions.Expression]] = None) -> str: View Source

    3236    def connector_sql(
    3237        self,
    3238        expression: exp.Connector,
    3239        op: str,
    3240        stack: t.Optional[t.List[str | exp.Expression]] = None,
    3241    ) -> str:
    3242        if stack is not None:
    3243            if expression.expressions:
    3244                stack.append(self.expressions(expression, sep=f" {op} "))
    3245            else:
    3246                stack.append(expression.right)
    3247                if expression.comments and self.comments:
    3248                    for comment in expression.comments:
    3249                        if comment:
    3250                            op += f" /*{self.pad_comment(comment)}*/"
    3251                stack.extend((op, expression.left))
    3252            return op
    3253
    3254        stack = [expression]
    3255        sqls: t.List[str] = []
    3256        ops = set()
    3257
    3258        while stack:
    3259            node = stack.pop()
    3260            if isinstance(node, exp.Connector):
    3261                ops.add(getattr(self, f"{node.key}_sql")(node, stack))
    3262            else:
    3263                sql = self.sql(node)
    3264                if sqls and sqls[-1] in ops:
    3265                    sqls[-1] += f" {sql}"
    3266                else:
    3267                    sqls.append(sql)
    3268
    3269        sep = "\n" if self.pretty and self.too_wide(sqls) else " "
    3270        return sep.join(sqls)

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

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

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

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

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

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

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

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

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

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

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

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

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

    3290    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    3291        format_sql = self.sql(expression, "format")
    3292        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    3293        to_sql = self.sql(expression, "to")
    3294        to_sql = f" {to_sql}" if to_sql else ""
    3295        action = self.sql(expression, "action")
    3296        action = f" {action}" if action else ""
    3297        default = self.sql(expression, "default")
    3298        default = f" DEFAULT {default} ON CONVERSION ERROR" if default else ""
    3299        return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{default}{format_sql}{action})"

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

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

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

    3305    def collate_sql(self, expression: exp.Collate) -> str:
    3306        if self.COLLATE_IS_FUNC:
    3307            return self.function_fallback_sql(expression)
    3308        return self.binary(expression, "COLLATE")

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

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

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

    3313    def comment_sql(self, expression: exp.Comment) -> str:
    3314        this = self.sql(expression, "this")
    3315        kind = expression.args["kind"]
    3316        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    3317        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    3318        expression_sql = self.sql(expression, "expression")
    3319        return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"

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

    3321    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    3322        this = self.sql(expression, "this")
    3323        delete = " DELETE" if expression.args.get("delete") else ""
    3324        recompress = self.sql(expression, "recompress")
    3325        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    3326        to_disk = self.sql(expression, "to_disk")
    3327        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    3328        to_volume = self.sql(expression, "to_volume")
    3329        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    3330        return f"{this}{delete}{recompress}{to_disk}{to_volume}"

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

    3332    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    3333        where = self.sql(expression, "where")
    3334        group = self.sql(expression, "group")
    3335        aggregates = self.expressions(expression, key="aggregates")
    3336        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    3337
    3338        if not (where or group or aggregates) and len(expression.expressions) == 1:
    3339            return f"TTL {self.expressions(expression, flat=True)}"
    3340
    3341        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"

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

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

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

    3346    def commit_sql(self, expression: exp.Commit) -> str:
    3347        chain = expression.args.get("chain")
    3348        if chain is not None:
    3349            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    3350
    3351        return f"COMMIT{chain or ''}"

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

    3353    def rollback_sql(self, expression: exp.Rollback) -> str:
    3354        savepoint = expression.args.get("savepoint")
    3355        savepoint = f" TO {savepoint}" if savepoint else ""
    3356        return f"ROLLBACK{savepoint}"

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

    3358    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    3359        this = self.sql(expression, "this")
    3360
    3361        dtype = self.sql(expression, "dtype")
    3362        if dtype:
    3363            collate = self.sql(expression, "collate")
    3364            collate = f" COLLATE {collate}" if collate else ""
    3365            using = self.sql(expression, "using")
    3366            using = f" USING {using}" if using else ""
    3367            alter_set_type = self.ALTER_SET_TYPE + " " if self.ALTER_SET_TYPE else ""
    3368            return f"ALTER COLUMN {this} {alter_set_type}{dtype}{collate}{using}"
    3369
    3370        default = self.sql(expression, "default")
    3371        if default:
    3372            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    3373
    3374        comment = self.sql(expression, "comment")
    3375        if comment:
    3376            return f"ALTER COLUMN {this} COMMENT {comment}"
    3377
    3378        visible = expression.args.get("visible")
    3379        if visible:
    3380            return f"ALTER COLUMN {this} SET {visible}"
    3381
    3382        allow_null = expression.args.get("allow_null")
    3383        drop = expression.args.get("drop")
    3384
    3385        if not drop and not allow_null:
    3386            self.unsupported("Unsupported ALTER COLUMN syntax")
    3387
    3388        if allow_null is not None:
    3389            keyword = "DROP" if drop else "SET"
    3390            return f"ALTER COLUMN {this} {keyword} NOT NULL"
    3391
    3392        return f"ALTER COLUMN {this} DROP DEFAULT"

def alterindex_sql(self, expression: sqlglot.expressions.AlterIndex) -> str: View Source

    3394    def alterindex_sql(self, expression: exp.AlterIndex) -> str:
    3395        this = self.sql(expression, "this")
    3396
    3397        visible = expression.args.get("visible")
    3398        visible_sql = "VISIBLE" if visible else "INVISIBLE"
    3399
    3400        return f"ALTER INDEX {this} {visible_sql}"

def alterdiststyle_sql(self, expression: sqlglot.expressions.AlterDistStyle) -> str: View Source

    3402    def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str:
    3403        this = self.sql(expression, "this")
    3404        if not isinstance(expression.this, exp.Var):
    3405            this = f"KEY DISTKEY {this}"
    3406        return f"ALTER DISTSTYLE {this}"

def altersortkey_sql(self, expression: sqlglot.expressions.AlterSortKey) -> str: View Source

    3408    def altersortkey_sql(self, expression: exp.AlterSortKey) -> str:
    3409        compound = " COMPOUND" if expression.args.get("compound") else ""
    3410        this = self.sql(expression, "this")
    3411        expressions = self.expressions(expression, flat=True)
    3412        expressions = f"({expressions})" if expressions else ""
    3413        return f"ALTER{compound} SORTKEY {this or expressions}"

def alterrename_sql(self, expression: sqlglot.expressions.AlterRename) -> str: View Source

    3415    def alterrename_sql(self, expression: exp.AlterRename) -> str:
    3416        if not self.RENAME_TABLE_WITH_DB:
    3417            # Remove db from tables
    3418            expression = expression.transform(
    3419                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    3420            ).assert_is(exp.AlterRename)
    3421        this = self.sql(expression, "this")
    3422        return f"RENAME TO {this}"

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

    3424    def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
    3425        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3426        old_column = self.sql(expression, "this")
    3427        new_column = self.sql(expression, "to")
    3428        return f"RENAME COLUMN{exists} {old_column} TO {new_column}"

def alterset_sql(self, expression: sqlglot.expressions.AlterSet) -> str: View Source

    3430    def alterset_sql(self, expression: exp.AlterSet) -> str:
    3431        exprs = self.expressions(expression, flat=True)
    3432        return f"SET {exprs}"

def alter_sql(self, expression: sqlglot.expressions.Alter) -> str: View Source

    3434    def alter_sql(self, expression: exp.Alter) -> str:
    3435        actions = expression.args["actions"]
    3436
    3437        if isinstance(actions[0], exp.ColumnDef):
    3438            actions = self.add_column_sql(expression)
    3439        elif isinstance(actions[0], exp.Schema):
    3440            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    3441        elif isinstance(actions[0], exp.Delete):
    3442            actions = self.expressions(expression, key="actions", flat=True)
    3443        elif isinstance(actions[0], exp.Query):
    3444            actions = "AS " + self.expressions(expression, key="actions")
    3445        else:
    3446            actions = self.expressions(expression, key="actions", flat=True)
    3447
    3448        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3449        on_cluster = self.sql(expression, "cluster")
    3450        on_cluster = f" {on_cluster}" if on_cluster else ""
    3451        only = " ONLY" if expression.args.get("only") else ""
    3452        options = self.expressions(expression, key="options")
    3453        options = f", {options}" if options else ""
    3454        kind = self.sql(expression, "kind")
    3455        not_valid = " NOT VALID" if expression.args.get("not_valid") else ""
    3456
    3457        return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions}{not_valid}{options}"

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

    3459    def add_column_sql(self, expression: exp.Alter) -> str:
    3460        if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD:
    3461            return self.expressions(
    3462                expression,
    3463                key="actions",
    3464                prefix="ADD COLUMN ",
    3465                skip_first=True,
    3466            )
    3467        return f"ADD {self.expressions(expression, key='actions', flat=True)}"

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

    3469    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    3470        expressions = self.expressions(expression)
    3471        exists = " IF EXISTS " if expression.args.get("exists") else " "
    3472        return f"DROP{exists}{expressions}"

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

    3474    def addconstraint_sql(self, expression: exp.AddConstraint) -> str:
    3475        return f"ADD {self.expressions(expression)}"

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

    3477    def distinct_sql(self, expression: exp.Distinct) -> str:
    3478        this = self.expressions(expression, flat=True)
    3479
    3480        if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1:
    3481            case = exp.case()
    3482            for arg in expression.expressions:
    3483                case = case.when(arg.is_(exp.null()), exp.null())
    3484            this = self.sql(case.else_(f"({this})"))
    3485
    3486        this = f" {this}" if this else ""
    3487
    3488        on = self.sql(expression, "on")
    3489        on = f" ON {on}" if on else ""
    3490        return f"DISTINCT{this}{on}"

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

    3492    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
    3493        return self._embed_ignore_nulls(expression, "IGNORE NULLS")

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

    3495    def respectnulls_sql(self, expression: exp.RespectNulls) -> str:
    3496        return self._embed_ignore_nulls(expression, "RESPECT NULLS")

def havingmax_sql(self, expression: sqlglot.expressions.HavingMax) -> str: View Source

    3498    def havingmax_sql(self, expression: exp.HavingMax) -> str:
    3499        this_sql = self.sql(expression, "this")
    3500        expression_sql = self.sql(expression, "expression")
    3501        kind = "MAX" if expression.args.get("max") else "MIN"
    3502        return f"{this_sql} HAVING {kind} {expression_sql}"

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

    3504    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    3505        return self.sql(
    3506            exp.Cast(
    3507                this=exp.Div(this=expression.this, expression=expression.expression),
    3508                to=exp.DataType(this=exp.DataType.Type.INT),
    3509            )
    3510        )

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

    3512    def dpipe_sql(self, expression: exp.DPipe) -> str:
    3513        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    3514            return self.func(
    3515                "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten())
    3516            )
    3517        return self.binary(expression, "||")

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

    3519    def div_sql(self, expression: exp.Div) -> str:
    3520        l, r = expression.left, expression.right
    3521
    3522        if not self.dialect.SAFE_DIVISION and expression.args.get("safe"):
    3523            r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0)))
    3524
    3525        if self.dialect.TYPED_DIVISION and not expression.args.get("typed"):
    3526            if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES):
    3527                l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE))
    3528
    3529        elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"):
    3530            if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES):
    3531                return self.sql(
    3532                    exp.cast(
    3533                        l / r,
    3534                        to=exp.DataType.Type.BIGINT,
    3535                    )
    3536                )
    3537
    3538        return self.binary(expression, "/")

def safedivide_sql(self, expression: sqlglot.expressions.SafeDivide) -> str: View Source

    3540    def safedivide_sql(self, expression: exp.SafeDivide) -> str:
    3541        n = exp._wrap(expression.this, exp.Binary)
    3542        d = exp._wrap(expression.expression, exp.Binary)
    3543        return self.sql(exp.If(this=d.neq(0), true=n / d, false=exp.Null()))

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3578    def is_sql(self, expression: exp.Is) -> str:
    3579        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    3580            return self.sql(
    3581                expression.this if expression.expression.this else exp.not_(expression.this)
    3582            )
    3583        return self.binary(expression, "IS")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

def jsoncast_sql(self, expression: sqlglot.expressions.JSONCast) -> str: View Source

    3624    def jsoncast_sql(self, expression: exp.JSONCast) -> str:
    3625        return self.cast_sql(expression)

def try_sql(self, expression: sqlglot.expressions.Try) -> str: View Source

    3627    def try_sql(self, expression: exp.Try) -> str:
    3628        if not self.TRY_SUPPORTED:
    3629            self.unsupported("Unsupported TRY function")
    3630            return self.sql(expression, "this")
    3631
    3632        return self.func("TRY", expression.this)

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

    3634    def log_sql(self, expression: exp.Log) -> str:
    3635        this = expression.this
    3636        expr = expression.expression
    3637
    3638        if self.dialect.LOG_BASE_FIRST is False:
    3639            this, expr = expr, this
    3640        elif self.dialect.LOG_BASE_FIRST is None and expr:
    3641            if this.name in ("2", "10"):
    3642                return self.func(f"LOG{this.name}", expr)
    3643
    3644            self.unsupported(f"Unsupported logarithm with base {self.sql(this)}")
    3645
    3646        return self.func("LOG", this, expr)

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

    3648    def use_sql(self, expression: exp.Use) -> str:
    3649        kind = self.sql(expression, "kind")
    3650        kind = f" {kind}" if kind else ""
    3651        this = self.sql(expression, "this") or self.expressions(expression, flat=True)
    3652        this = f" {this}" if this else ""
    3653        return f"USE{kind}{this}"

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

    3655    def binary(self, expression: exp.Binary, op: str) -> str:
    3656        sqls: t.List[str] = []
    3657        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    3658        binary_type = type(expression)
    3659
    3660        while stack:
    3661            node = stack.pop()
    3662
    3663            if type(node) is binary_type:
    3664                op_func = node.args.get("operator")
    3665                if op_func:
    3666                    op = f"OPERATOR({self.sql(op_func)})"
    3667
    3668                stack.append(node.right)
    3669                stack.append(f" {self.maybe_comment(op, comments=node.comments)} ")
    3670                stack.append(node.left)
    3671            else:
    3672                sqls.append(self.sql(node))
    3673
    3674        return "".join(sqls)

def ceil_floor( self, expression: sqlglot.expressions.Ceil | sqlglot.expressions.Floor) -> str: View Source

    3676    def ceil_floor(self, expression: exp.Ceil | exp.Floor) -> str:
    3677        to_clause = self.sql(expression, "to")
    3678        if to_clause:
    3679            return f"{expression.sql_name()}({self.sql(expression, 'this')} TO {to_clause})"
    3680
    3681        return self.function_fallback_sql(expression)

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

    3683    def function_fallback_sql(self, expression: exp.Func) -> str:
    3684        args = []
    3685
    3686        for key in expression.arg_types:
    3687            arg_value = expression.args.get(key)
    3688
    3689            if isinstance(arg_value, list):
    3690                for value in arg_value:
    3691                    args.append(value)
    3692            elif arg_value is not None:
    3693                args.append(arg_value)
    3694
    3695        if self.dialect.PRESERVE_ORIGINAL_NAMES:
    3696            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
    3697        else:
    3698            name = expression.sql_name()
    3699
    3700        return self.func(name, *args)

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

    3702    def func(
    3703        self,
    3704        name: str,
    3705        *args: t.Optional[exp.Expression | str],
    3706        prefix: str = "(",
    3707        suffix: str = ")",
    3708        normalize: bool = True,
    3709    ) -> str:
    3710        name = self.normalize_func(name) if normalize else name
    3711        return f"{name}{prefix}{self.format_args(*args)}{suffix}"

def format_args( self, *args: Union[str, sqlglot.expressions.Expression, NoneType], sep: str = ', ') -> str: View Source

    3713    def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str:
    3714        arg_sqls = tuple(
    3715            self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool)
    3716        )
    3717        if self.pretty and self.too_wide(arg_sqls):
    3718            return self.indent(
    3719                "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True
    3720            )
    3721        return sep.join(arg_sqls)

def too_wide(self, args: Iterable) -> bool: View Source

    3723    def too_wide(self, args: t.Iterable) -> bool:
    3724        return sum(len(arg) for arg in args) > self.max_text_width

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

    3726    def format_time(
    3727        self,
    3728        expression: exp.Expression,
    3729        inverse_time_mapping: t.Optional[t.Dict[str, str]] = None,
    3730        inverse_time_trie: t.Optional[t.Dict] = None,
    3731    ) -> t.Optional[str]:
    3732        return format_time(
    3733            self.sql(expression, "format"),
    3734            inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING,
    3735            inverse_time_trie or self.dialect.INVERSE_TIME_TRIE,
    3736        )

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

    3738    def expressions(
    3739        self,
    3740        expression: t.Optional[exp.Expression] = None,
    3741        key: t.Optional[str] = None,
    3742        sqls: t.Optional[t.Collection[str | exp.Expression]] = None,
    3743        flat: bool = False,
    3744        indent: bool = True,
    3745        skip_first: bool = False,
    3746        skip_last: bool = False,
    3747        sep: str = ", ",
    3748        prefix: str = "",
    3749        dynamic: bool = False,
    3750        new_line: bool = False,
    3751    ) -> str:
    3752        expressions = expression.args.get(key or "expressions") if expression else sqls
    3753
    3754        if not expressions:
    3755            return ""
    3756
    3757        if flat:
    3758            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
    3759
    3760        num_sqls = len(expressions)
    3761        result_sqls = []
    3762
    3763        for i, e in enumerate(expressions):
    3764            sql = self.sql(e, comment=False)
    3765            if not sql:
    3766                continue
    3767
    3768            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    3769
    3770            if self.pretty:
    3771                if self.leading_comma:
    3772                    result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}")
    3773                else:
    3774                    result_sqls.append(
    3775                        f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}"
    3776                    )
    3777            else:
    3778                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    3779
    3780        if self.pretty and (not dynamic or self.too_wide(result_sqls)):
    3781            if new_line:
    3782                result_sqls.insert(0, "")
    3783                result_sqls.append("")
    3784            result_sql = "\n".join(s.rstrip() for s in result_sqls)
    3785        else:
    3786            result_sql = "".join(result_sqls)
    3787
    3788        return (
    3789            self.indent(result_sql, skip_first=skip_first, skip_last=skip_last)
    3790            if indent
    3791            else result_sql
    3792        )

def op_expressions( self, op: str, expression: sqlglot.expressions.Expression, flat: bool = False) -> str: View Source

    3794    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    3795        flat = flat or isinstance(expression.parent, exp.Properties)
    3796        expressions_sql = self.expressions(expression, flat=flat)
    3797        if flat:
    3798            return f"{op} {expressions_sql}"
    3799        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"

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

    3801    def naked_property(self, expression: exp.Property) -> str:
    3802        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    3803        if not property_name:
    3804            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    3805        return f"{property_name} {self.sql(expression, 'this')}"

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

    3807    def tag_sql(self, expression: exp.Tag) -> str:
    3808        return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}"

def token_sql(self, token_type: sqlglot.tokens.TokenType) -> str: View Source

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

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

    3813    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    3814        this = self.sql(expression, "this")
    3815        expressions = self.no_identify(self.expressions, expression)
    3816        expressions = (
    3817            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    3818        )
    3819        return f"{this}{expressions}" if expressions.strip() != "" else this

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

    3821    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    3822        this = self.sql(expression, "this")
    3823        expressions = self.expressions(expression, flat=True)
    3824        return f"{this}({expressions})"

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

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

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

    3829    def when_sql(self, expression: exp.When) -> str:
    3830        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    3831        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    3832        condition = self.sql(expression, "condition")
    3833        condition = f" AND {condition}" if condition else ""
    3834
    3835        then_expression = expression.args.get("then")
    3836        if isinstance(then_expression, exp.Insert):
    3837            this = self.sql(then_expression, "this")
    3838            this = f"INSERT {this}" if this else "INSERT"
    3839            then = self.sql(then_expression, "expression")
    3840            then = f"{this} VALUES {then}" if then else this
    3841        elif isinstance(then_expression, exp.Update):
    3842            if isinstance(then_expression.args.get("expressions"), exp.Star):
    3843                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    3844            else:
    3845                then = f"UPDATE SET{self.sep()}{self.expressions(then_expression)}"
    3846        else:
    3847            then = self.sql(then_expression)
    3848        return f"WHEN {matched}{source}{condition} THEN {then}"

def whens_sql(self, expression: sqlglot.expressions.Whens) -> str: View Source

    3850    def whens_sql(self, expression: exp.Whens) -> str:
    3851        return self.expressions(expression, sep=" ", indent=False)

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

    3853    def merge_sql(self, expression: exp.Merge) -> str:
    3854        table = expression.this
    3855        table_alias = ""
    3856
    3857        hints = table.args.get("hints")
    3858        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
    3859            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
    3860            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
    3861
    3862        this = self.sql(table)
    3863        using = f"USING {self.sql(expression, 'using')}"
    3864        on = f"ON {self.sql(expression, 'on')}"
    3865        whens = self.sql(expression, "whens")
    3866
    3867        returning = self.sql(expression, "returning")
    3868        if returning:
    3869            whens = f"{whens}{returning}"
    3870
    3871        sep = self.sep()
    3872
    3873        return self.prepend_ctes(
    3874            expression,
    3875            f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}",
    3876        )

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

    3878    @unsupported_args("format")
    3879    def tochar_sql(self, expression: exp.ToChar) -> str:
    3880        return self.sql(exp.cast(expression.this, exp.DataType.Type.TEXT))

def tonumber_sql(self, expression: sqlglot.expressions.ToNumber) -> str: View Source

    3882    def tonumber_sql(self, expression: exp.ToNumber) -> str:
    3883        if not self.SUPPORTS_TO_NUMBER:
    3884            self.unsupported("Unsupported TO_NUMBER function")
    3885            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3886
    3887        fmt = expression.args.get("format")
    3888        if not fmt:
    3889            self.unsupported("Conversion format is required for TO_NUMBER")
    3890            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3891
    3892        return self.func("TO_NUMBER", expression.this, fmt)

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

    3894    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    3895        this = self.sql(expression, "this")
    3896        kind = self.sql(expression, "kind")
    3897        settings_sql = self.expressions(expression, key="settings", sep=" ")
    3898        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    3899        return f"{this}({kind}{args})"

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

    3901    def dictrange_sql(self, expression: exp.DictRange) -> str:
    3902        this = self.sql(expression, "this")
    3903        max = self.sql(expression, "max")
    3904        min = self.sql(expression, "min")
    3905        return f"{this}(MIN {min} MAX {max})"

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

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

def duplicatekeyproperty_sql(self, expression: sqlglot.expressions.DuplicateKeyProperty) -> str: View Source

    3910    def duplicatekeyproperty_sql(self, expression: exp.DuplicateKeyProperty) -> str:
    3911        return f"DUPLICATE KEY ({self.expressions(expression, flat=True)})"

def uniquekeyproperty_sql(self, expression: sqlglot.expressions.UniqueKeyProperty) -> str: View Source

    3914    def uniquekeyproperty_sql(self, expression: exp.UniqueKeyProperty) -> str:
    3915        return f"UNIQUE KEY ({self.expressions(expression, flat=True)})"

def distributedbyproperty_sql(self, expression: sqlglot.expressions.DistributedByProperty) -> str: View Source

    3918    def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str:
    3919        expressions = self.expressions(expression, flat=True)
    3920        expressions = f" {self.wrap(expressions)}" if expressions else ""
    3921        buckets = self.sql(expression, "buckets")
    3922        kind = self.sql(expression, "kind")
    3923        buckets = f" BUCKETS {buckets}" if buckets else ""
    3924        order = self.sql(expression, "order")
    3925        return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}"

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

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

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

    3930    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    3931        expressions = self.expressions(expression, key="expressions", flat=True)
    3932        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    3933        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    3934        buckets = self.sql(expression, "buckets")
    3935        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"

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

    3937    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    3938        this = self.sql(expression, "this")
    3939        having = self.sql(expression, "having")
    3940
    3941        if having:
    3942            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    3943
    3944        return self.func("ANY_VALUE", this)

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

    3946    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
    3947        transform = self.func("TRANSFORM", *expression.expressions)
    3948        row_format_before = self.sql(expression, "row_format_before")
    3949        row_format_before = f" {row_format_before}" if row_format_before else ""
    3950        record_writer = self.sql(expression, "record_writer")
    3951        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
    3952        using = f" USING {self.sql(expression, 'command_script')}"
    3953        schema = self.sql(expression, "schema")
    3954        schema = f" AS {schema}" if schema else ""
    3955        row_format_after = self.sql(expression, "row_format_after")
    3956        row_format_after = f" {row_format_after}" if row_format_after else ""
    3957        record_reader = self.sql(expression, "record_reader")
    3958        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
    3959        return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}"

def indexconstraintoption_sql(self, expression: sqlglot.expressions.IndexConstraintOption) -> str: View Source

    3961    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
    3962        key_block_size = self.sql(expression, "key_block_size")
    3963        if key_block_size:
    3964            return f"KEY_BLOCK_SIZE = {key_block_size}"
    3965
    3966        using = self.sql(expression, "using")
    3967        if using:
    3968            return f"USING {using}"
    3969
    3970        parser = self.sql(expression, "parser")
    3971        if parser:
    3972            return f"WITH PARSER {parser}"
    3973
    3974        comment = self.sql(expression, "comment")
    3975        if comment:
    3976            return f"COMMENT {comment}"
    3977
    3978        visible = expression.args.get("visible")
    3979        if visible is not None:
    3980            return "VISIBLE" if visible else "INVISIBLE"
    3981
    3982        engine_attr = self.sql(expression, "engine_attr")
    3983        if engine_attr:
    3984            return f"ENGINE_ATTRIBUTE = {engine_attr}"
    3985
    3986        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
    3987        if secondary_engine_attr:
    3988            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
    3989
    3990        self.unsupported("Unsupported index constraint option.")
    3991        return ""

def checkcolumnconstraint_sql(self, expression: sqlglot.expressions.CheckColumnConstraint) -> str: View Source

    3993    def checkcolumnconstraint_sql(self, expression: exp.CheckColumnConstraint) -> str:
    3994        enforced = " ENFORCED" if expression.args.get("enforced") else ""
    3995        return f"CHECK ({self.sql(expression, 'this')}){enforced}"

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

    3997    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
    3998        kind = self.sql(expression, "kind")
    3999        kind = f"{kind} INDEX" if kind else "INDEX"
    4000        this = self.sql(expression, "this")
    4001        this = f" {this}" if this else ""
    4002        index_type = self.sql(expression, "index_type")
    4003        index_type = f" USING {index_type}" if index_type else ""
    4004        expressions = self.expressions(expression, flat=True)
    4005        expressions = f" ({expressions})" if expressions else ""
    4006        options = self.expressions(expression, key="options", sep=" ")
    4007        options = f" {options}" if options else ""
    4008        return f"{kind}{this}{index_type}{expressions}{options}"

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

    4010    def nvl2_sql(self, expression: exp.Nvl2) -> str:
    4011        if self.NVL2_SUPPORTED:
    4012            return self.function_fallback_sql(expression)
    4013
    4014        case = exp.Case().when(
    4015            expression.this.is_(exp.null()).not_(copy=False),
    4016            expression.args["true"],
    4017            copy=False,
    4018        )
    4019        else_cond = expression.args.get("false")
    4020        if else_cond:
    4021            case.else_(else_cond, copy=False)
    4022
    4023        return self.sql(case)

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

    4025    def comprehension_sql(self, expression: exp.Comprehension) -> str:
    4026        this = self.sql(expression, "this")
    4027        expr = self.sql(expression, "expression")
    4028        iterator = self.sql(expression, "iterator")
    4029        condition = self.sql(expression, "condition")
    4030        condition = f" IF {condition}" if condition else ""
    4031        return f"{this} FOR {expr} IN {iterator}{condition}"

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

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

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

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

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

    4039    def predict_sql(self, expression: exp.Predict) -> str:
    4040        model = self.sql(expression, "this")
    4041        model = f"MODEL {model}"
    4042        table = self.sql(expression, "expression")
    4043        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
    4044        parameters = self.sql(expression, "params_struct")
    4045        return self.func("PREDICT", model, table, parameters or None)

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

    4047    def forin_sql(self, expression: exp.ForIn) -> str:
    4048        this = self.sql(expression, "this")
    4049        expression_sql = self.sql(expression, "expression")
    4050        return f"FOR {this} DO {expression_sql}"

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

    4052    def refresh_sql(self, expression: exp.Refresh) -> str:
    4053        this = self.sql(expression, "this")
    4054        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
    4055        return f"REFRESH {table}{this}"

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

    4057    def toarray_sql(self, expression: exp.ToArray) -> str:
    4058        arg = expression.this
    4059        if not arg.type:
    4060            from sqlglot.optimizer.annotate_types import annotate_types
    4061
    4062            arg = annotate_types(arg, dialect=self.dialect)
    4063
    4064        if arg.is_type(exp.DataType.Type.ARRAY):
    4065            return self.sql(arg)
    4066
    4067        cond_for_null = arg.is_(exp.null())
    4068        return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False)))

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

    4070    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
    4071        this = expression.this
    4072        time_format = self.format_time(expression)
    4073
    4074        if time_format:
    4075            return self.sql(
    4076                exp.cast(
    4077                    exp.StrToTime(this=this, format=expression.args["format"]),
    4078                    exp.DataType.Type.TIME,
    4079                )
    4080            )
    4081
    4082        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
    4083            return self.sql(this)
    4084
    4085        return self.sql(exp.cast(this, exp.DataType.Type.TIME))

def tsordstotimestamp_sql(self, expression: sqlglot.expressions.TsOrDsToTimestamp) -> str: View Source

    4087    def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str:
    4088        this = expression.this
    4089        if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP):
    4090            return self.sql(this)
    4091
    4092        return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect))

def tsordstodatetime_sql(self, expression: sqlglot.expressions.TsOrDsToDatetime) -> str: View Source

    4094    def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str:
    4095        this = expression.this
    4096        if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME):
    4097            return self.sql(this)
    4098
    4099        return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect))

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

    4101    def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:
    4102        this = expression.this
    4103        time_format = self.format_time(expression)
    4104
    4105        if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT):
    4106            return self.sql(
    4107                exp.cast(
    4108                    exp.StrToTime(this=this, format=expression.args["format"]),
    4109                    exp.DataType.Type.DATE,
    4110                )
    4111            )
    4112
    4113        if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE):
    4114            return self.sql(this)
    4115
    4116        return self.sql(exp.cast(this, exp.DataType.Type.DATE))

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

    4118    def unixdate_sql(self, expression: exp.UnixDate) -> str:
    4119        return self.sql(
    4120            exp.func(
    4121                "DATEDIFF",
    4122                expression.this,
    4123                exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE),
    4124                "day",
    4125            )
    4126        )

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

    4128    def lastday_sql(self, expression: exp.LastDay) -> str:
    4129        if self.LAST_DAY_SUPPORTS_DATE_PART:
    4130            return self.function_fallback_sql(expression)
    4131
    4132        unit = expression.text("unit")
    4133        if unit and unit != "MONTH":
    4134            self.unsupported("Date parts are not supported in LAST_DAY.")
    4135
    4136        return self.func("LAST_DAY", expression.this)

def dateadd_sql(self, expression: sqlglot.expressions.DateAdd) -> str: View Source

    4138    def dateadd_sql(self, expression: exp.DateAdd) -> str:
    4139        from sqlglot.dialects.dialect import unit_to_str
    4140
    4141        return self.func(
    4142            "DATE_ADD", expression.this, expression.expression, unit_to_str(expression)
    4143        )

def arrayany_sql(self, expression: sqlglot.expressions.ArrayAny) -> str: View Source

    4145    def arrayany_sql(self, expression: exp.ArrayAny) -> str:
    4146        if self.CAN_IMPLEMENT_ARRAY_ANY:
    4147            filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression)
    4148            filtered_not_empty = exp.ArraySize(this=filtered).neq(0)
    4149            original_is_empty = exp.ArraySize(this=expression.this).eq(0)
    4150            return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty)))
    4151
    4152        from sqlglot.dialects import Dialect
    4153
    4154        # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect
    4155        if self.dialect.__class__ != Dialect:
    4156            self.unsupported("ARRAY_ANY is unsupported")
    4157
    4158        return self.function_fallback_sql(expression)

def struct_sql(self, expression: sqlglot.expressions.Struct) -> str: View Source

    4160    def struct_sql(self, expression: exp.Struct) -> str:
    4161        expression.set(
    4162            "expressions",
    4163            [
    4164                exp.alias_(e.expression, e.name if e.this.is_string else e.this)
    4165                if isinstance(e, exp.PropertyEQ)
    4166                else e
    4167                for e in expression.expressions
    4168            ],
    4169        )
    4170
    4171        return self.function_fallback_sql(expression)

def partitionrange_sql(self, expression: sqlglot.expressions.PartitionRange) -> str: View Source

    4173    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
    4174        low = self.sql(expression, "this")
    4175        high = self.sql(expression, "expression")
    4176
    4177        return f"{low} TO {high}"

def truncatetable_sql(self, expression: sqlglot.expressions.TruncateTable) -> str: View Source

    4179    def truncatetable_sql(self, expression: exp.TruncateTable) -> str:
    4180        target = "DATABASE" if expression.args.get("is_database") else "TABLE"
    4181        tables = f" {self.expressions(expression)}"
    4182
    4183        exists = " IF EXISTS" if expression.args.get("exists") else ""
    4184
    4185        on_cluster = self.sql(expression, "cluster")
    4186        on_cluster = f" {on_cluster}" if on_cluster else ""
    4187
    4188        identity = self.sql(expression, "identity")
    4189        identity = f" {identity} IDENTITY" if identity else ""
    4190
    4191        option = self.sql(expression, "option")
    4192        option = f" {option}" if option else ""
    4193
    4194        partition = self.sql(expression, "partition")
    4195        partition = f" {partition}" if partition else ""
    4196
    4197        return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"

def convert_sql(self, expression: sqlglot.expressions.Convert) -> str: View Source

    4201    def convert_sql(self, expression: exp.Convert) -> str:
    4202        to = expression.this
    4203        value = expression.expression
    4204        style = expression.args.get("style")
    4205        safe = expression.args.get("safe")
    4206        strict = expression.args.get("strict")
    4207
    4208        if not to or not value:
    4209            return ""
    4210
    4211        # Retrieve length of datatype and override to default if not specified
    4212        if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    4213            to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
    4214
    4215        transformed: t.Optional[exp.Expression] = None
    4216        cast = exp.Cast if strict else exp.TryCast
    4217
    4218        # Check whether a conversion with format (T-SQL calls this 'style') is applicable
    4219        if isinstance(style, exp.Literal) and style.is_int:
    4220            from sqlglot.dialects.tsql import TSQL
    4221
    4222            style_value = style.name
    4223            converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value)
    4224            if not converted_style:
    4225                self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}")
    4226
    4227            fmt = exp.Literal.string(converted_style)
    4228
    4229            if to.this == exp.DataType.Type.DATE:
    4230                transformed = exp.StrToDate(this=value, format=fmt)
    4231            elif to.this in (exp.DataType.Type.DATETIME, exp.DataType.Type.DATETIME2):
    4232                transformed = exp.StrToTime(this=value, format=fmt)
    4233            elif to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    4234                transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe)
    4235            elif to.this == exp.DataType.Type.TEXT:
    4236                transformed = exp.TimeToStr(this=value, format=fmt)
    4237
    4238        if not transformed:
    4239            transformed = cast(this=value, to=to, safe=safe)
    4240
    4241        return self.sql(transformed)

def copyparameter_sql(self, expression: sqlglot.expressions.CopyParameter) -> str: View Source

    4302    def copyparameter_sql(self, expression: exp.CopyParameter) -> str:
    4303        option = self.sql(expression, "this")
    4304
    4305        if expression.expressions:
    4306            upper = option.upper()
    4307
    4308            # Snowflake FILE_FORMAT options are separated by whitespace
    4309            sep = " " if upper == "FILE_FORMAT" else ", "
    4310
    4311            # Databricks copy/format options do not set their list of values with EQ
    4312            op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = "
    4313            values = self.expressions(expression, flat=True, sep=sep)
    4314            return f"{option}{op}({values})"
    4315
    4316        value = self.sql(expression, "expression")
    4317
    4318        if not value:
    4319            return option
    4320
    4321        op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " "
    4322
    4323        return f"{option}{op}{value}"

def credentials_sql(self, expression: sqlglot.expressions.Credentials) -> str: View Source

    4325    def credentials_sql(self, expression: exp.Credentials) -> str:
    4326        cred_expr = expression.args.get("credentials")
    4327        if isinstance(cred_expr, exp.Literal):
    4328            # Redshift case: CREDENTIALS <string>
    4329            credentials = self.sql(expression, "credentials")
    4330            credentials = f"CREDENTIALS {credentials}" if credentials else ""
    4331        else:
    4332            # Snowflake case: CREDENTIALS = (...)
    4333            credentials = self.expressions(expression, key="credentials", flat=True, sep=" ")
    4334            credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else ""
    4335
    4336        storage = self.sql(expression, "storage")
    4337        storage = f"STORAGE_INTEGRATION = {storage}" if storage else ""
    4338
    4339        encryption = self.expressions(expression, key="encryption", flat=True, sep=" ")
    4340        encryption = f" ENCRYPTION = ({encryption})" if encryption else ""
    4341
    4342        iam_role = self.sql(expression, "iam_role")
    4343        iam_role = f"IAM_ROLE {iam_role}" if iam_role else ""
    4344
    4345        region = self.sql(expression, "region")
    4346        region = f" REGION {region}" if region else ""
    4347
    4348        return f"{credentials}{storage}{encryption}{iam_role}{region}"

def copy_sql(self, expression: sqlglot.expressions.Copy) -> str: View Source

    4350    def copy_sql(self, expression: exp.Copy) -> str:
    4351        this = self.sql(expression, "this")
    4352        this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}"
    4353
    4354        credentials = self.sql(expression, "credentials")
    4355        credentials = self.seg(credentials) if credentials else ""
    4356        kind = self.seg("FROM" if expression.args.get("kind") else "TO")
    4357        files = self.expressions(expression, key="files", flat=True)
    4358
    4359        sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " "
    4360        params = self.expressions(
    4361            expression,
    4362            key="params",
    4363            sep=sep,
    4364            new_line=True,
    4365            skip_last=True,
    4366            skip_first=True,
    4367            indent=self.COPY_PARAMS_ARE_WRAPPED,
    4368        )
    4369
    4370        if params:
    4371            if self.COPY_PARAMS_ARE_WRAPPED:
    4372                params = f" WITH ({params})"
    4373            elif not self.pretty:
    4374                params = f" {params}"
    4375
    4376        return f"COPY{this}{kind} {files}{credentials}{params}"

def semicolon_sql(self, expression: sqlglot.expressions.Semicolon) -> str: View Source

    4378    def semicolon_sql(self, expression: exp.Semicolon) -> str:
    4379        return ""

def datadeletionproperty_sql(self, expression: sqlglot.expressions.DataDeletionProperty) -> str: View Source

    4381    def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str:
    4382        on_sql = "ON" if expression.args.get("on") else "OFF"
    4383        filter_col: t.Optional[str] = self.sql(expression, "filter_column")
    4384        filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None
    4385        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    4386        retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None
    4387
    4388        if filter_col or retention_period:
    4389            on_sql = self.func("ON", filter_col, retention_period)
    4390
    4391        return f"DATA_DELETION={on_sql}"

def maskingpolicycolumnconstraint_sql( self, expression: sqlglot.expressions.MaskingPolicyColumnConstraint) -> str: View Source

    4393    def maskingpolicycolumnconstraint_sql(
    4394        self, expression: exp.MaskingPolicyColumnConstraint
    4395    ) -> str:
    4396        this = self.sql(expression, "this")
    4397        expressions = self.expressions(expression, flat=True)
    4398        expressions = f" USING ({expressions})" if expressions else ""
    4399        return f"MASKING POLICY {this}{expressions}"

def gapfill_sql(self, expression: sqlglot.expressions.GapFill) -> str: View Source

    4401    def gapfill_sql(self, expression: exp.GapFill) -> str:
    4402        this = self.sql(expression, "this")
    4403        this = f"TABLE {this}"
    4404        return self.func("GAP_FILL", this, *[v for k, v in expression.args.items() if k != "this"])

def scope_resolution(self, rhs: str, scope_name: str) -> str: View Source

    4406    def scope_resolution(self, rhs: str, scope_name: str) -> str:
    4407        return self.func("SCOPE_RESOLUTION", scope_name or None, rhs)

def scoperesolution_sql(self, expression: sqlglot.expressions.ScopeResolution) -> str: View Source

    4409    def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str:
    4410        this = self.sql(expression, "this")
    4411        expr = expression.expression
    4412
    4413        if isinstance(expr, exp.Func):
    4414            # T-SQL's CLR functions are case sensitive
    4415            expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})"
    4416        else:
    4417            expr = self.sql(expression, "expression")
    4418
    4419        return self.scope_resolution(expr, this)

def parsejson_sql(self, expression: sqlglot.expressions.ParseJSON) -> str: View Source

    4421    def parsejson_sql(self, expression: exp.ParseJSON) -> str:
    4422        if self.PARSE_JSON_NAME is None:
    4423            return self.sql(expression.this)
    4424
    4425        return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression)

def rand_sql(self, expression: sqlglot.expressions.Rand) -> str: View Source

    4427    def rand_sql(self, expression: exp.Rand) -> str:
    4428        lower = self.sql(expression, "lower")
    4429        upper = self.sql(expression, "upper")
    4430
    4431        if lower and upper:
    4432            return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}"
    4433        return self.func("RAND", expression.this)

def changes_sql(self, expression: sqlglot.expressions.Changes) -> str: View Source

    4435    def changes_sql(self, expression: exp.Changes) -> str:
    4436        information = self.sql(expression, "information")
    4437        information = f"INFORMATION => {information}"
    4438        at_before = self.sql(expression, "at_before")
    4439        at_before = f"{self.seg('')}{at_before}" if at_before else ""
    4440        end = self.sql(expression, "end")
    4441        end = f"{self.seg('')}{end}" if end else ""
    4442
    4443        return f"CHANGES ({information}){at_before}{end}"

def pad_sql(self, expression: sqlglot.expressions.Pad) -> str: View Source

    4445    def pad_sql(self, expression: exp.Pad) -> str:
    4446        prefix = "L" if expression.args.get("is_left") else "R"
    4447
    4448        fill_pattern = self.sql(expression, "fill_pattern") or None
    4449        if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED:
    4450            fill_pattern = "' '"
    4451
    4452        return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)

def summarize_sql(self, expression: sqlglot.expressions.Summarize) -> str: View Source

    4454    def summarize_sql(self, expression: exp.Summarize) -> str:
    4455        table = " TABLE" if expression.args.get("table") else ""
    4456        return f"SUMMARIZE{table} {self.sql(expression.this)}"

def explodinggenerateseries_sql(self, expression: sqlglot.expressions.ExplodingGenerateSeries) -> str: View Source

    4458    def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str:
    4459        generate_series = exp.GenerateSeries(**expression.args)
    4460
    4461        parent = expression.parent
    4462        if isinstance(parent, (exp.Alias, exp.TableAlias)):
    4463            parent = parent.parent
    4464
    4465        if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)):
    4466            return self.sql(exp.Unnest(expressions=[generate_series]))
    4467
    4468        if isinstance(parent, exp.Select):
    4469            self.unsupported("GenerateSeries projection unnesting is not supported.")
    4470
    4471        return self.sql(generate_series)

def arrayconcat_sql( self, expression: sqlglot.expressions.ArrayConcat, name: str = 'ARRAY_CONCAT') -> str: View Source

    4473    def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str:
    4474        exprs = expression.expressions
    4475        if not self.ARRAY_CONCAT_IS_VAR_LEN:
    4476            rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs)
    4477        else:
    4478            rhs = self.expressions(expression)
    4479
    4480        return self.func(name, expression.this, rhs or None)

def converttimezone_sql(self, expression: sqlglot.expressions.ConvertTimezone) -> str: View Source

    4482    def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str:
    4483        if self.SUPPORTS_CONVERT_TIMEZONE:
    4484            return self.function_fallback_sql(expression)
    4485
    4486        source_tz = expression.args.get("source_tz")
    4487        target_tz = expression.args.get("target_tz")
    4488        timestamp = expression.args.get("timestamp")
    4489
    4490        if source_tz and timestamp:
    4491            timestamp = exp.AtTimeZone(
    4492                this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz
    4493            )
    4494
    4495        expr = exp.AtTimeZone(this=timestamp, zone=target_tz)
    4496
    4497        return self.sql(expr)

def json_sql(self, expression: sqlglot.expressions.JSON) -> str: View Source

    4499    def json_sql(self, expression: exp.JSON) -> str:
    4500        this = self.sql(expression, "this")
    4501        this = f" {this}" if this else ""
    4502
    4503        _with = expression.args.get("with")
    4504
    4505        if _with is None:
    4506            with_sql = ""
    4507        elif not _with:
    4508            with_sql = " WITHOUT"
    4509        else:
    4510            with_sql = " WITH"
    4511
    4512        unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else ""
    4513
    4514        return f"JSON{this}{with_sql}{unique_sql}"

def jsonvalue_sql(self, expression: sqlglot.expressions.JSONValue) -> str: View Source

    4516    def jsonvalue_sql(self, expression: exp.JSONValue) -> str:
    4517        def _generate_on_options(arg: t.Any) -> str:
    4518            return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}"
    4519
    4520        path = self.sql(expression, "path")
    4521        returning = self.sql(expression, "returning")
    4522        returning = f" RETURNING {returning}" if returning else ""
    4523
    4524        on_condition = self.sql(expression, "on_condition")
    4525        on_condition = f" {on_condition}" if on_condition else ""
    4526
    4527        return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}")

def conditionalinsert_sql(self, expression: sqlglot.expressions.ConditionalInsert) -> str: View Source

    4529    def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str:
    4530        else_ = "ELSE " if expression.args.get("else_") else ""
    4531        condition = self.sql(expression, "expression")
    4532        condition = f"WHEN {condition} THEN " if condition else else_
    4533        insert = self.sql(expression, "this")[len("INSERT") :].strip()
    4534        return f"{condition}{insert}"

def multitableinserts_sql(self, expression: sqlglot.expressions.MultitableInserts) -> str: View Source

    4536    def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str:
    4537        kind = self.sql(expression, "kind")
    4538        expressions = self.seg(self.expressions(expression, sep=" "))
    4539        res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}"
    4540        return res

def oncondition_sql(self, expression: sqlglot.expressions.OnCondition) -> str: View Source

    4542    def oncondition_sql(self, expression: exp.OnCondition) -> str:
    4543        # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR"
    4544        empty = expression.args.get("empty")
    4545        empty = (
    4546            f"DEFAULT {empty} ON EMPTY"
    4547            if isinstance(empty, exp.Expression)
    4548            else self.sql(expression, "empty")
    4549        )
    4550
    4551        error = expression.args.get("error")
    4552        error = (
    4553            f"DEFAULT {error} ON ERROR"
    4554            if isinstance(error, exp.Expression)
    4555            else self.sql(expression, "error")
    4556        )
    4557
    4558        if error and empty:
    4559            error = (
    4560                f"{empty} {error}"
    4561                if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR
    4562                else f"{error} {empty}"
    4563            )
    4564            empty = ""
    4565
    4566        null = self.sql(expression, "null")
    4567
    4568        return f"{empty}{error}{null}"

def jsonextractquote_sql(self, expression: sqlglot.expressions.JSONExtractQuote) -> str: View Source

    4570    def jsonextractquote_sql(self, expression: exp.JSONExtractQuote) -> str:
    4571        scalar = " ON SCALAR STRING" if expression.args.get("scalar") else ""
    4572        return f"{self.sql(expression, 'option')} QUOTES{scalar}"

def jsonexists_sql(self, expression: sqlglot.expressions.JSONExists) -> str: View Source

    4574    def jsonexists_sql(self, expression: exp.JSONExists) -> str:
    4575        this = self.sql(expression, "this")
    4576        path = self.sql(expression, "path")
    4577
    4578        passing = self.expressions(expression, "passing")
    4579        passing = f" PASSING {passing}" if passing else ""
    4580
    4581        on_condition = self.sql(expression, "on_condition")
    4582        on_condition = f" {on_condition}" if on_condition else ""
    4583
    4584        path = f"{path}{passing}{on_condition}"
    4585
    4586        return self.func("JSON_EXISTS", this, path)

def arrayagg_sql(self, expression: sqlglot.expressions.ArrayAgg) -> str: View Source

    4588    def arrayagg_sql(self, expression: exp.ArrayAgg) -> str:
    4589        array_agg = self.function_fallback_sql(expression)
    4590
    4591        # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls
    4592        # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB)
    4593        if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"):
    4594            parent = expression.parent
    4595            if isinstance(parent, exp.Filter):
    4596                parent_cond = parent.expression.this
    4597                parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_()))
    4598            else:
    4599                this = expression.this
    4600                # Do not add the filter if the input is not a column (e.g. literal, struct etc)
    4601                if this.find(exp.Column):
    4602                    # DISTINCT is already present in the agg function, do not propagate it to FILTER as well
    4603                    this_sql = (
    4604                        self.expressions(this)
    4605                        if isinstance(this, exp.Distinct)
    4606                        else self.sql(expression, "this")
    4607                    )
    4608
    4609                    array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)"
    4610
    4611        return array_agg

def apply_sql(self, expression: sqlglot.expressions.Apply) -> str: View Source

    4613    def apply_sql(self, expression: exp.Apply) -> str:
    4614        this = self.sql(expression, "this")
    4615        expr = self.sql(expression, "expression")
    4616
    4617        return f"{this} APPLY({expr})"

def grant_sql(self, expression: sqlglot.expressions.Grant) -> str: View Source

    4619    def grant_sql(self, expression: exp.Grant) -> str:
    4620        privileges_sql = self.expressions(expression, key="privileges", flat=True)
    4621
    4622        kind = self.sql(expression, "kind")
    4623        kind = f" {kind}" if kind else ""
    4624
    4625        securable = self.sql(expression, "securable")
    4626        securable = f" {securable}" if securable else ""
    4627
    4628        principals = self.expressions(expression, key="principals", flat=True)
    4629
    4630        grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else ""
    4631
    4632        return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}"

def grantprivilege_sql(self, expression: sqlglot.expressions.GrantPrivilege): View Source

    4634    def grantprivilege_sql(self, expression: exp.GrantPrivilege):
    4635        this = self.sql(expression, "this")
    4636        columns = self.expressions(expression, flat=True)
    4637        columns = f"({columns})" if columns else ""
    4638
    4639        return f"{this}{columns}"

def grantprincipal_sql(self, expression: sqlglot.expressions.GrantPrincipal): View Source

    4641    def grantprincipal_sql(self, expression: exp.GrantPrincipal):
    4642        this = self.sql(expression, "this")
    4643
    4644        kind = self.sql(expression, "kind")
    4645        kind = f"{kind} " if kind else ""
    4646
    4647        return f"{kind}{this}"

def columns_sql(self, expression: sqlglot.expressions.Columns): View Source

    4649    def columns_sql(self, expression: exp.Columns):
    4650        func = self.function_fallback_sql(expression)
    4651        if expression.args.get("unpack"):
    4652            func = f"*{func}"
    4653
    4654        return func

def overlay_sql(self, expression: sqlglot.expressions.Overlay): View Source

    4656    def overlay_sql(self, expression: exp.Overlay):
    4657        this = self.sql(expression, "this")
    4658        expr = self.sql(expression, "expression")
    4659        from_sql = self.sql(expression, "from")
    4660        for_sql = self.sql(expression, "for")
    4661        for_sql = f" FOR {for_sql}" if for_sql else ""
    4662
    4663        return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})"

@unsupported_args('format')
def todouble_sql(self, expression: sqlglot.expressions.ToDouble) -> str: View Source

    4665    @unsupported_args("format")
    4666    def todouble_sql(self, expression: exp.ToDouble) -> str:
    4667        return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))

def string_sql(self, expression: sqlglot.expressions.String) -> str: View Source

    4669    def string_sql(self, expression: exp.String) -> str:
    4670        this = expression.this
    4671        zone = expression.args.get("zone")
    4672
    4673        if zone:
    4674            # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>)
    4675            # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC
    4676            # set for source_tz to transpile the time conversion before the STRING cast
    4677            this = exp.ConvertTimezone(
    4678                source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this
    4679            )
    4680
    4681        return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR))

def median_sql(self, expression: sqlglot.expressions.Median): View Source

    4683    def median_sql(self, expression: exp.Median):
    4684        if not self.SUPPORTS_MEDIAN:
    4685            return self.sql(
    4686                exp.PercentileCont(this=expression.this, expression=exp.Literal.number(0.5))
    4687            )
    4688
    4689        return self.function_fallback_sql(expression)

def overflowtruncatebehavior_sql(self, expression: sqlglot.expressions.OverflowTruncateBehavior) -> str: View Source

    4691    def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str:
    4692        filler = self.sql(expression, "this")
    4693        filler = f" {filler}" if filler else ""
    4694        with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT"
    4695        return f"TRUNCATE{filler} {with_count}"

def unixseconds_sql(self, expression: sqlglot.expressions.UnixSeconds) -> str: View Source

    4697    def unixseconds_sql(self, expression: exp.UnixSeconds) -> str:
    4698        if self.SUPPORTS_UNIX_SECONDS:
    4699            return self.function_fallback_sql(expression)
    4700
    4701        start_ts = exp.cast(
    4702            exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ
    4703        )
    4704
    4705        return self.sql(
    4706            exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS"))
    4707        )

def arraysize_sql(self, expression: sqlglot.expressions.ArraySize) -> str: View Source

    4709    def arraysize_sql(self, expression: exp.ArraySize) -> str:
    4710        dim = expression.expression
    4711
    4712        # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension)
    4713        if dim and self.ARRAY_SIZE_DIM_REQUIRED is None:
    4714            if not (dim.is_int and dim.name == "1"):
    4715                self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH")
    4716            dim = None
    4717
    4718        # If dimension is required but not specified, default initialize it
    4719        if self.ARRAY_SIZE_DIM_REQUIRED and not dim:
    4720            dim = exp.Literal.number(1)
    4721
    4722        return self.func(self.ARRAY_SIZE_NAME, expression.this, dim)

def attach_sql(self, expression: sqlglot.expressions.Attach) -> str: View Source

    4724    def attach_sql(self, expression: exp.Attach) -> str:
    4725        this = self.sql(expression, "this")
    4726        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
    4727        expressions = self.expressions(expression)
    4728        expressions = f" ({expressions})" if expressions else ""
    4729
    4730        return f"ATTACH{exists_sql} {this}{expressions}"

def detach_sql(self, expression: sqlglot.expressions.Detach) -> str: View Source

    4732    def detach_sql(self, expression: exp.Detach) -> str:
    4733        this = self.sql(expression, "this")
    4734        exists_sql = " IF EXISTS" if expression.args.get("exists") else ""
    4735
    4736        return f"DETACH{exists_sql} {this}"

def attachoption_sql(self, expression: sqlglot.expressions.AttachOption) -> str: View Source

    4738    def attachoption_sql(self, expression: exp.AttachOption) -> str:
    4739        this = self.sql(expression, "this")
    4740        value = self.sql(expression, "expression")
    4741        value = f" {value}" if value else ""
    4742        return f"{this}{value}"

def featuresattime_sql(self, expression: sqlglot.expressions.FeaturesAtTime) -> str: View Source

    4744    def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str:
    4745        this_sql = self.sql(expression, "this")
    4746        if isinstance(expression.this, exp.Table):
    4747            this_sql = f"TABLE {this_sql}"
    4748
    4749        return self.func(
    4750            "FEATURES_AT_TIME",
    4751            this_sql,
    4752            expression.args.get("time"),
    4753            expression.args.get("num_rows"),
    4754            expression.args.get("ignore_feature_nulls"),
    4755        )

def watermarkcolumnconstraint_sql(self, expression: sqlglot.expressions.WatermarkColumnConstraint) -> str: View Source

    4757    def watermarkcolumnconstraint_sql(self, expression: exp.WatermarkColumnConstraint) -> str:
    4758        return (
    4759            f"WATERMARK FOR {self.sql(expression, 'this')} AS {self.sql(expression, 'expression')}"
    4760        )

def encodeproperty_sql(self, expression: sqlglot.expressions.EncodeProperty) -> str: View Source

    4762    def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str:
    4763        encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE"
    4764        encode = f"{encode} {self.sql(expression, 'this')}"
    4765
    4766        properties = expression.args.get("properties")
    4767        if properties:
    4768            encode = f"{encode} {self.properties(properties)}"
    4769
    4770        return encode

def includeproperty_sql(self, expression: sqlglot.expressions.IncludeProperty) -> str: View Source

    4772    def includeproperty_sql(self, expression: exp.IncludeProperty) -> str:
    4773        this = self.sql(expression, "this")
    4774        include = f"INCLUDE {this}"
    4775
    4776        column_def = self.sql(expression, "column_def")
    4777        if column_def:
    4778            include = f"{include} {column_def}"
    4779
    4780        alias = self.sql(expression, "alias")
    4781        if alias:
    4782            include = f"{include} AS {alias}"
    4783
    4784        return include

def xmlelement_sql(self, expression: sqlglot.expressions.XMLElement) -> str: View Source

    4786    def xmlelement_sql(self, expression: exp.XMLElement) -> str:
    4787        name = f"NAME {self.sql(expression, 'this')}"
    4788        return self.func("XMLELEMENT", name, *expression.expressions)

def partitionbyrangeproperty_sql(self, expression: sqlglot.expressions.PartitionByRangeProperty) -> str: View Source

    4790    def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str:
    4791        partitions = self.expressions(expression, "partition_expressions")
    4792        create = self.expressions(expression, "create_expressions")
    4793        return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}"

def partitionbyrangepropertydynamic_sql( self, expression: sqlglot.expressions.PartitionByRangePropertyDynamic) -> str: View Source

    4795    def partitionbyrangepropertydynamic_sql(
    4796        self, expression: exp.PartitionByRangePropertyDynamic
    4797    ) -> str:
    4798        start = self.sql(expression, "start")
    4799        end = self.sql(expression, "end")
    4800
    4801        every = expression.args["every"]
    4802        if isinstance(every, exp.Interval) and every.this.is_string:
    4803            every.this.replace(exp.Literal.number(every.name))
    4804
    4805        return f"START {self.wrap(start)} END {self.wrap(end)} EVERY {self.wrap(self.sql(every))}"

def unpivotcolumns_sql(self, expression: sqlglot.expressions.UnpivotColumns) -> str: View Source

    4807    def unpivotcolumns_sql(self, expression: exp.UnpivotColumns) -> str:
    4808        name = self.sql(expression, "this")
    4809        values = self.expressions(expression, flat=True)
    4810
    4811        return f"NAME {name} VALUE {values}"

def analyzesample_sql(self, expression: sqlglot.expressions.AnalyzeSample) -> str: View Source

    4813    def analyzesample_sql(self, expression: exp.AnalyzeSample) -> str:
    4814        kind = self.sql(expression, "kind")
    4815        sample = self.sql(expression, "sample")
    4816        return f"SAMPLE {sample} {kind}"

def analyzestatistics_sql(self, expression: sqlglot.expressions.AnalyzeStatistics) -> str: View Source

    4818    def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str:
    4819        kind = self.sql(expression, "kind")
    4820        option = self.sql(expression, "option")
    4821        option = f" {option}" if option else ""
    4822        this = self.sql(expression, "this")
    4823        this = f" {this}" if this else ""
    4824        columns = self.expressions(expression)
    4825        columns = f" {columns}" if columns else ""
    4826        return f"{kind}{option} STATISTICS{this}{columns}"

def analyzehistogram_sql(self, expression: sqlglot.expressions.AnalyzeHistogram) -> str: View Source

    4828    def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str:
    4829        this = self.sql(expression, "this")
    4830        columns = self.expressions(expression)
    4831        inner_expression = self.sql(expression, "expression")
    4832        inner_expression = f" {inner_expression}" if inner_expression else ""
    4833        update_options = self.sql(expression, "update_options")
    4834        update_options = f" {update_options} UPDATE" if update_options else ""
    4835        return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}"

def analyzedelete_sql(self, expression: sqlglot.expressions.AnalyzeDelete) -> str: View Source

    4837    def analyzedelete_sql(self, expression: exp.AnalyzeDelete) -> str:
    4838        kind = self.sql(expression, "kind")
    4839        kind = f" {kind}" if kind else ""
    4840        return f"DELETE{kind} STATISTICS"

def analyzelistchainedrows_sql(self, expression: sqlglot.expressions.AnalyzeListChainedRows) -> str: View Source

    4842    def analyzelistchainedrows_sql(self, expression: exp.AnalyzeListChainedRows) -> str:
    4843        inner_expression = self.sql(expression, "expression")
    4844        return f"LIST CHAINED ROWS{inner_expression}"

def analyzevalidate_sql(self, expression: sqlglot.expressions.AnalyzeValidate) -> str: View Source

    4846    def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str:
    4847        kind = self.sql(expression, "kind")
    4848        this = self.sql(expression, "this")
    4849        this = f" {this}" if this else ""
    4850        inner_expression = self.sql(expression, "expression")
    4851        return f"VALIDATE {kind}{this}{inner_expression}"

def analyze_sql(self, expression: sqlglot.expressions.Analyze) -> str: View Source

    4853    def analyze_sql(self, expression: exp.Analyze) -> str:
    4854        options = self.expressions(expression, key="options", sep=" ")
    4855        options = f" {options}" if options else ""
    4856        kind = self.sql(expression, "kind")
    4857        kind = f" {kind}" if kind else ""
    4858        this = self.sql(expression, "this")
    4859        this = f" {this}" if this else ""
    4860        mode = self.sql(expression, "mode")
    4861        mode = f" {mode}" if mode else ""
    4862        properties = self.sql(expression, "properties")
    4863        properties = f" {properties}" if properties else ""
    4864        partition = self.sql(expression, "partition")
    4865        partition = f" {partition}" if partition else ""
    4866        inner_expression = self.sql(expression, "expression")
    4867        inner_expression = f" {inner_expression}" if inner_expression else ""
    4868        return f"ANALYZE{options}{kind}{this}{partition}{mode}{inner_expression}{properties}"

def xmltable_sql(self, expression: sqlglot.expressions.XMLTable) -> str: View Source

    4870    def xmltable_sql(self, expression: exp.XMLTable) -> str:
    4871        this = self.sql(expression, "this")
    4872        namespaces = self.expressions(expression, key="namespaces")
    4873        namespaces = f"XMLNAMESPACES({namespaces}), " if namespaces else ""
    4874        passing = self.expressions(expression, key="passing")
    4875        passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else ""
    4876        columns = self.expressions(expression, key="columns")
    4877        columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else ""
    4878        by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else ""
    4879        return f"XMLTABLE({self.sep('')}{self.indent(namespaces + this + passing + by_ref + columns)}{self.seg(')', sep='')}"

def xmlnamespace_sql(self, expression: sqlglot.expressions.XMLNamespace) -> str: View Source

    4881    def xmlnamespace_sql(self, expression: exp.XMLNamespace) -> str:
    4882        this = self.sql(expression, "this")
    4883        return this if isinstance(expression.this, exp.Alias) else f"DEFAULT {this}"

def export_sql(self, expression: sqlglot.expressions.Export) -> str: View Source

    4885    def export_sql(self, expression: exp.Export) -> str:
    4886        this = self.sql(expression, "this")
    4887        connection = self.sql(expression, "connection")
    4888        connection = f"WITH CONNECTION {connection} " if connection else ""
    4889        options = self.sql(expression, "options")
    4890        return f"EXPORT DATA {connection}{options} AS {this}"

def declare_sql(self, expression: sqlglot.expressions.Declare) -> str: View Source

    4892    def declare_sql(self, expression: exp.Declare) -> str:
    4893        return f"DECLARE {self.expressions(expression, flat=True)}"

def declareitem_sql(self, expression: sqlglot.expressions.DeclareItem) -> str: View Source

    4895    def declareitem_sql(self, expression: exp.DeclareItem) -> str:
    4896        variable = self.sql(expression, "this")
    4897        default = self.sql(expression, "default")
    4898        default = f" = {default}" if default else ""
    4899
    4900        kind = self.sql(expression, "kind")
    4901        if isinstance(expression.args.get("kind"), exp.Schema):
    4902            kind = f"TABLE {kind}"
    4903
    4904        return f"{variable} AS {kind}{default}"

def recursivewithsearch_sql(self, expression: sqlglot.expressions.RecursiveWithSearch) -> str: View Source

    4906    def recursivewithsearch_sql(self, expression: exp.RecursiveWithSearch) -> str:
    4907        kind = self.sql(expression, "kind")
    4908        this = self.sql(expression, "this")
    4909        set = self.sql(expression, "expression")
    4910        using = self.sql(expression, "using")
    4911        using = f" USING {using}" if using else ""
    4912
    4913        kind_sql = kind if kind == "CYCLE" else f"SEARCH {kind} FIRST BY"
    4914
    4915        return f"{kind_sql} {this} SET {set}{using}"

def parameterizedagg_sql(self, expression: sqlglot.expressions.ParameterizedAgg) -> str: View Source

    4917    def parameterizedagg_sql(self, expression: exp.ParameterizedAgg) -> str:
    4918        params = self.expressions(expression, key="params", flat=True)
    4919        return self.func(expression.name, *expression.expressions) + f"({params})"

def anonymousaggfunc_sql(self, expression: sqlglot.expressions.AnonymousAggFunc) -> str: View Source

    4921    def anonymousaggfunc_sql(self, expression: exp.AnonymousAggFunc) -> str:
    4922        return self.func(expression.name, *expression.expressions)

def combinedaggfunc_sql(self, expression: sqlglot.expressions.CombinedAggFunc) -> str: View Source

    4924    def combinedaggfunc_sql(self, expression: exp.CombinedAggFunc) -> str:
    4925        return self.anonymousaggfunc_sql(expression)

def combinedparameterizedagg_sql(self, expression: sqlglot.expressions.CombinedParameterizedAgg) -> str: View Source

    4927    def combinedparameterizedagg_sql(self, expression: exp.CombinedParameterizedAgg) -> str:
    4928        return self.parameterizedagg_sql(expression)

def show_sql(self, expression: sqlglot.expressions.Show) -> str: View Source

    4930    def show_sql(self, expression: exp.Show) -> str:
    4931        self.unsupported("Unsupported SHOW statement")
    4932        return ""

def get_put_sql( self, expression: sqlglot.expressions.Put | sqlglot.expressions.Get) -> str: View Source

    4934    def get_put_sql(self, expression: exp.Put | exp.Get) -> str:
    4935        # Snowflake GET/PUT statements:
    4936        #   PUT <file> <internalStage> <properties>
    4937        #   GET <internalStage> <file> <properties>
    4938        props = expression.args.get("properties")
    4939        props_sql = self.properties(props, prefix=" ", sep=" ", wrapped=False) if props else ""
    4940        this = self.sql(expression, "this")
    4941        target = self.sql(expression, "target")
    4942
    4943        if isinstance(expression, exp.Put):
    4944            return f"PUT {this} {target}{props_sql}"
    4945        else:
    4946            return f"GET {target} {this}{props_sql}"

def translatecharacters_sql(self, expression: sqlglot.expressions.TranslateCharacters): View Source

    4948    def translatecharacters_sql(self, expression: exp.TranslateCharacters):
    4949        this = self.sql(expression, "this")
    4950        expr = self.sql(expression, "expression")
    4951        with_error = " WITH ERROR" if expression.args.get("with_error") else ""
    4952        return f"TRANSLATE({this} USING {expr}{with_error})"