sqlglot.generator API documentation

Edit on GitHub

# sqlglot.generator

View Source

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

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

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

###### Arguments:

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

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

    659    def __init__(
    660        self,
    661        pretty: t.Optional[bool] = None,
    662        identify: str | bool = False,
    663        normalize: bool = False,
    664        pad: int = 2,
    665        indent: int = 2,
    666        normalize_functions: t.Optional[str | bool] = None,
    667        unsupported_level: ErrorLevel = ErrorLevel.WARN,
    668        max_unsupported: int = 3,
    669        leading_comma: bool = False,
    670        max_text_width: int = 80,
    671        comments: bool = True,
    672        dialect: DialectType = None,
    673    ):
    674        import sqlglot
    675        from sqlglot.dialects import Dialect
    676
    677        self.pretty = pretty if pretty is not None else sqlglot.pretty
    678        self.identify = identify
    679        self.normalize = normalize
    680        self.pad = pad
    681        self._indent = indent
    682        self.unsupported_level = unsupported_level
    683        self.max_unsupported = max_unsupported
    684        self.leading_comma = leading_comma
    685        self.max_text_width = max_text_width
    686        self.comments = comments
    687        self.dialect = Dialect.get_or_raise(dialect)
    688
    689        # This is both a Dialect property and a Generator argument, so we prioritize the latter
    690        self.normalize_functions = (
    691            self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions
    692        )
    693
    694        self.unsupported_messages: t.List[str] = []
    695        self._escaped_quote_end: str = (
    696            self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END
    697        )
    698        self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2
    699
    700        self._next_name = name_sequence("_t")
    701
    702        self._identifier_start = self.dialect.IDENTIFIER_START
    703        self._identifier_end = self.dialect.IDENTIFIER_END

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

    705    def generate(self, expression: exp.Expression, copy: bool = True) -> str:
    706        """
    707        Generates the SQL string corresponding to the given syntax tree.
    708
    709        Args:
    710            expression: The syntax tree.
    711            copy: Whether to copy the expression. The generator performs mutations so
    712                it is safer to copy.
    713
    714        Returns:
    715            The SQL string corresponding to `expression`.
    716        """
    717        if copy:
    718            expression = expression.copy()
    719
    720        expression = self.preprocess(expression)
    721
    722        self.unsupported_messages = []
    723        sql = self.sql(expression).strip()
    724
    725        if self.pretty:
    726            sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n")
    727
    728        if self.unsupported_level == ErrorLevel.IGNORE:
    729            return sql
    730
    731        if self.unsupported_level == ErrorLevel.WARN:
    732            for msg in self.unsupported_messages:
    733                logger.warning(msg)
    734        elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages:
    735            raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported))
    736
    737        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

    739    def preprocess(self, expression: exp.Expression) -> exp.Expression:
    740        """Apply generic preprocessing transformations to a given expression."""
    741        expression = self._move_ctes_to_top_level(expression)
    742
    743        if self.ENSURE_BOOLS:
    744            from sqlglot.transforms import ensure_bools
    745
    746            expression = ensure_bools(expression)
    747
    748        return expression

Apply generic preprocessing transformations to a given expression.

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

    761    def unsupported(self, message: str) -> None:
    762        if self.unsupported_level == ErrorLevel.IMMEDIATE:
    763            raise UnsupportedError(message)
    764        self.unsupported_messages.append(message)

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

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

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

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

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

    772    def pad_comment(self, comment: str) -> str:
    773        comment = " " + comment if comment[0].strip() else comment
    774        comment = comment + " " if comment[-1].strip() else comment
    775        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

    777    def maybe_comment(
    778        self,
    779        sql: str,
    780        expression: t.Optional[exp.Expression] = None,
    781        comments: t.Optional[t.List[str]] = None,
    782        separated: bool = False,
    783    ) -> str:
    784        comments = (
    785            ((expression and expression.comments) if comments is None else comments)  # type: ignore
    786            if self.comments
    787            else None
    788        )
    789
    790        if not comments or isinstance(expression, self.EXCLUDE_COMMENTS):
    791            return sql
    792
    793        comments_sql = " ".join(
    794            f"/*{self.pad_comment(comment)}*/" for comment in comments if comment
    795        )
    796
    797        if not comments_sql:
    798            return sql
    799
    800        comments_sql = self._replace_line_breaks(comments_sql)
    801
    802        if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS):
    803            return (
    804                f"{self.sep()}{comments_sql}{sql}"
    805                if not sql or sql[0].isspace()
    806                else f"{comments_sql}{self.sep()}{sql}"
    807            )
    808
    809        return f"{sql} {comments_sql}"

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

    811    def wrap(self, expression: exp.Expression | str) -> str:
    812        this_sql = (
    813            self.sql(expression)
    814            if isinstance(expression, exp.UNWRAPPED_QUERIES)
    815            else self.sql(expression, "this")
    816        )
    817        if not this_sql:
    818            return "()"
    819
    820        this_sql = self.indent(this_sql, level=1, pad=0)
    821        return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"

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

    823    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
    824        original = self.identify
    825        self.identify = False
    826        result = func(*args, **kwargs)
    827        self.identify = original
    828        return result

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

    830    def normalize_func(self, name: str) -> str:
    831        if self.normalize_functions == "upper" or self.normalize_functions is True:
    832            return name.upper()
    833        if self.normalize_functions == "lower":
    834            return name.lower()
    835        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

    837    def indent(
    838        self,
    839        sql: str,
    840        level: int = 0,
    841        pad: t.Optional[int] = None,
    842        skip_first: bool = False,
    843        skip_last: bool = False,
    844    ) -> str:
    845        if not self.pretty or not sql:
    846            return sql
    847
    848        pad = self.pad if pad is None else pad
    849        lines = sql.split("\n")
    850
    851        return "\n".join(
    852            (
    853                line
    854                if (skip_first and i == 0) or (skip_last and i == len(lines) - 1)
    855                else f"{' ' * (level * self._indent + pad)}{line}"
    856            )
    857            for i, line in enumerate(lines)
    858        )

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

    860    def sql(
    861        self,
    862        expression: t.Optional[str | exp.Expression],
    863        key: t.Optional[str] = None,
    864        comment: bool = True,
    865    ) -> str:
    866        if not expression:
    867            return ""
    868
    869        if isinstance(expression, str):
    870            return expression
    871
    872        if key:
    873            value = expression.args.get(key)
    874            if value:
    875                return self.sql(value)
    876            return ""
    877
    878        transform = self.TRANSFORMS.get(expression.__class__)
    879
    880        if callable(transform):
    881            sql = transform(self, expression)
    882        elif isinstance(expression, exp.Expression):
    883            exp_handler_name = f"{expression.key}_sql"
    884
    885            if hasattr(self, exp_handler_name):
    886                sql = getattr(self, exp_handler_name)(expression)
    887            elif isinstance(expression, exp.Func):
    888                sql = self.function_fallback_sql(expression)
    889            elif isinstance(expression, exp.Property):
    890                sql = self.property_sql(expression)
    891            else:
    892                raise ValueError(f"Unsupported expression type {expression.__class__.__name__}")
    893        else:
    894            raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}")
    895
    896        return self.maybe_comment(sql, expression) if self.comments and comment else sql

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

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

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

    903    def cache_sql(self, expression: exp.Cache) -> str:
    904        lazy = " LAZY" if expression.args.get("lazy") else ""
    905        table = self.sql(expression, "this")
    906        options = expression.args.get("options")
    907        options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else ""
    908        sql = self.sql(expression, "expression")
    909        sql = f" AS{self.sep()}{sql}" if sql else ""
    910        sql = f"CACHE{lazy} TABLE {table}{options}{sql}"
    911        return self.prepend_ctes(expression, sql)

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

    913    def characterset_sql(self, expression: exp.CharacterSet) -> str:
    914        if isinstance(expression.parent, exp.Cast):
    915            return f"CHAR CHARACTER SET {self.sql(expression, 'this')}"
    916        default = "DEFAULT " if expression.args.get("default") else ""
    917        return f"{default}CHARACTER SET={self.sql(expression, 'this')}"

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

    919    def column_parts(self, expression: exp.Column) -> str:
    920        return ".".join(
    921            self.sql(part)
    922            for part in (
    923                expression.args.get("catalog"),
    924                expression.args.get("db"),
    925                expression.args.get("table"),
    926                expression.args.get("this"),
    927            )
    928            if part
    929        )

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

    931    def column_sql(self, expression: exp.Column) -> str:
    932        join_mark = " (+)" if expression.args.get("join_mark") else ""
    933
    934        if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS:
    935            join_mark = ""
    936            self.unsupported("Outer join syntax using the (+) operator is not supported.")
    937
    938        return f"{self.column_parts(expression)}{join_mark}"

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

    940    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
    941        this = self.sql(expression, "this")
    942        this = f" {this}" if this else ""
    943        position = self.sql(expression, "position")
    944        return f"{position}{this}"

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

    946    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
    947        column = self.sql(expression, "this")
    948        kind = self.sql(expression, "kind")
    949        constraints = self.expressions(expression, key="constraints", sep=" ", flat=True)
    950        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
    951        kind = f"{sep}{kind}" if kind else ""
    952        constraints = f" {constraints}" if constraints else ""
    953        position = self.sql(expression, "position")
    954        position = f" {position}" if position else ""
    955
    956        if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE:
    957            kind = ""
    958
    959        return f"{exists}{column}{kind}{constraints}{position}"

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

    961    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
    962        this = self.sql(expression, "this")
    963        kind_sql = self.sql(expression, "kind").strip()
    964        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql

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

    966    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
    967        this = self.sql(expression, "this")
    968        if expression.args.get("not_null"):
    969            persisted = " PERSISTED NOT NULL"
    970        elif expression.args.get("persisted"):
    971            persisted = " PERSISTED"
    972        else:
    973            persisted = ""
    974        return f"AS {this}{persisted}"

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

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

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

    979    def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str:
    980        if isinstance(expression.this, list):
    981            this = self.wrap(self.expressions(expression, key="this", flat=True))
    982        else:
    983            this = self.sql(expression, "this")
    984
    985        return f"COMPRESS {this}"

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

     987    def generatedasidentitycolumnconstraint_sql(
     988        self, expression: exp.GeneratedAsIdentityColumnConstraint
     989    ) -> str:
     990        this = ""
     991        if expression.this is not None:
     992            on_null = " ON NULL" if expression.args.get("on_null") else ""
     993            this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}"
     994
     995        start = expression.args.get("start")
     996        start = f"START WITH {start}" if start else ""
     997        increment = expression.args.get("increment")
     998        increment = f" INCREMENT BY {increment}" if increment else ""
     999        minvalue = expression.args.get("minvalue")
    1000        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    1001        maxvalue = expression.args.get("maxvalue")
    1002        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    1003        cycle = expression.args.get("cycle")
    1004        cycle_sql = ""
    1005
    1006        if cycle is not None:
    1007            cycle_sql = f"{' NO' if not cycle else ''} CYCLE"
    1008            cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql
    1009
    1010        sequence_opts = ""
    1011        if start or increment or cycle_sql:
    1012            sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}"
    1013            sequence_opts = f" ({sequence_opts.strip()})"
    1014
    1015        expr = self.sql(expression, "expression")
    1016        expr = f"({expr})" if expr else "IDENTITY"
    1017
    1018        return f"GENERATED{this} AS {expr}{sequence_opts}"

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

    1020    def generatedasrowcolumnconstraint_sql(
    1021        self, expression: exp.GeneratedAsRowColumnConstraint
    1022    ) -> str:
    1023        start = "START" if expression.args.get("start") else "END"
    1024        hidden = " HIDDEN" if expression.args.get("hidden") else ""
    1025        return f"GENERATED ALWAYS AS ROW {start}{hidden}"

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

    1027    def periodforsystemtimeconstraint_sql(
    1028        self, expression: exp.PeriodForSystemTimeConstraint
    1029    ) -> str:
    1030        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

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

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

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

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

    1038    def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str:
    1039        desc = expression.args.get("desc")
    1040        if desc is not None:
    1041            return f"PRIMARY KEY{' DESC' if desc else ' ASC'}"
    1042        return "PRIMARY KEY"

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

    1044    def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str:
    1045        this = self.sql(expression, "this")
    1046        this = f" {this}" if this else ""
    1047        index_type = expression.args.get("index_type")
    1048        index_type = f" USING {index_type}" if index_type else ""
    1049        on_conflict = self.sql(expression, "on_conflict")
    1050        on_conflict = f" {on_conflict}" if on_conflict else ""
    1051        nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else ""
    1052        return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}"

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

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

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

    1057    def create_sql(self, expression: exp.Create) -> str:
    1058        kind = self.sql(expression, "kind")
    1059        kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind
    1060        properties = expression.args.get("properties")
    1061        properties_locs = self.locate_properties(properties) if properties else defaultdict()
    1062
    1063        this = self.createable_sql(expression, properties_locs)
    1064
    1065        properties_sql = ""
    1066        if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get(
    1067            exp.Properties.Location.POST_WITH
    1068        ):
    1069            properties_sql = self.sql(
    1070                exp.Properties(
    1071                    expressions=[
    1072                        *properties_locs[exp.Properties.Location.POST_SCHEMA],
    1073                        *properties_locs[exp.Properties.Location.POST_WITH],
    1074                    ]
    1075                )
    1076            )
    1077
    1078            if properties_locs.get(exp.Properties.Location.POST_SCHEMA):
    1079                properties_sql = self.sep() + properties_sql
    1080            elif not self.pretty:
    1081                # Standalone POST_WITH properties need a leading whitespace in non-pretty mode
    1082                properties_sql = f" {properties_sql}"
    1083
    1084        begin = " BEGIN" if expression.args.get("begin") else ""
    1085        end = " END" if expression.args.get("end") else ""
    1086
    1087        expression_sql = self.sql(expression, "expression")
    1088        if expression_sql:
    1089            expression_sql = f"{begin}{self.sep()}{expression_sql}{end}"
    1090
    1091            if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return):
    1092                postalias_props_sql = ""
    1093                if properties_locs.get(exp.Properties.Location.POST_ALIAS):
    1094                    postalias_props_sql = self.properties(
    1095                        exp.Properties(
    1096                            expressions=properties_locs[exp.Properties.Location.POST_ALIAS]
    1097                        ),
    1098                        wrapped=False,
    1099                    )
    1100                postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else ""
    1101                expression_sql = f" AS{postalias_props_sql}{expression_sql}"
    1102
    1103        postindex_props_sql = ""
    1104        if properties_locs.get(exp.Properties.Location.POST_INDEX):
    1105            postindex_props_sql = self.properties(
    1106                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]),
    1107                wrapped=False,
    1108                prefix=" ",
    1109            )
    1110
    1111        indexes = self.expressions(expression, key="indexes", indent=False, sep=" ")
    1112        indexes = f" {indexes}" if indexes else ""
    1113        index_sql = indexes + postindex_props_sql
    1114
    1115        replace = " OR REPLACE" if expression.args.get("replace") else ""
    1116        refresh = " OR REFRESH" if expression.args.get("refresh") else ""
    1117        unique = " UNIQUE" if expression.args.get("unique") else ""
    1118
    1119        clustered = expression.args.get("clustered")
    1120        if clustered is None:
    1121            clustered_sql = ""
    1122        elif clustered:
    1123            clustered_sql = " CLUSTERED COLUMNSTORE"
    1124        else:
    1125            clustered_sql = " NONCLUSTERED COLUMNSTORE"
    1126
    1127        postcreate_props_sql = ""
    1128        if properties_locs.get(exp.Properties.Location.POST_CREATE):
    1129            postcreate_props_sql = self.properties(
    1130                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]),
    1131                sep=" ",
    1132                prefix=" ",
    1133                wrapped=False,
    1134            )
    1135
    1136        modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql))
    1137
    1138        postexpression_props_sql = ""
    1139        if properties_locs.get(exp.Properties.Location.POST_EXPRESSION):
    1140            postexpression_props_sql = self.properties(
    1141                exp.Properties(
    1142                    expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION]
    1143                ),
    1144                sep=" ",
    1145                prefix=" ",
    1146                wrapped=False,
    1147            )
    1148
    1149        concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else ""
    1150        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
    1151        no_schema_binding = (
    1152            " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else ""
    1153        )
    1154
    1155        clone = self.sql(expression, "clone")
    1156        clone = f" {clone}" if clone else ""
    1157
    1158        expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_sql}{expression_sql}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}"
    1159        return self.prepend_ctes(expression, expression_sql)

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

    1161    def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str:
    1162        start = self.sql(expression, "start")
    1163        start = f"START WITH {start}" if start else ""
    1164        increment = self.sql(expression, "increment")
    1165        increment = f" INCREMENT BY {increment}" if increment else ""
    1166        minvalue = self.sql(expression, "minvalue")
    1167        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    1168        maxvalue = self.sql(expression, "maxvalue")
    1169        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    1170        owned = self.sql(expression, "owned")
    1171        owned = f" OWNED BY {owned}" if owned else ""
    1172
    1173        cache = expression.args.get("cache")
    1174        if cache is None:
    1175            cache_str = ""
    1176        elif cache is True:
    1177            cache_str = " CACHE"
    1178        else:
    1179            cache_str = f" CACHE {cache}"
    1180
    1181        options = self.expressions(expression, key="options", flat=True, sep=" ")
    1182        options = f" {options}" if options else ""
    1183
    1184        return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip()

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

    1186    def clone_sql(self, expression: exp.Clone) -> str:
    1187        this = self.sql(expression, "this")
    1188        shallow = "SHALLOW " if expression.args.get("shallow") else ""
    1189        keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE"
    1190        return f"{shallow}{keyword} {this}"

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

    1192    def describe_sql(self, expression: exp.Describe) -> str:
    1193        style = expression.args.get("style")
    1194        style = f" {style}" if style else ""
    1195        partition = self.sql(expression, "partition")
    1196        partition = f" {partition}" if partition else ""
    1197        return f"DESCRIBE{style} {self.sql(expression, 'this')}{partition}"

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

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

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

    1203    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
    1204        with_ = self.sql(expression, "with")
    1205        if with_:
    1206            sql = f"{with_}{self.sep()}{sql}"
    1207        return sql

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

    1209    def with_sql(self, expression: exp.With) -> str:
    1210        sql = self.expressions(expression, flat=True)
    1211        recursive = (
    1212            "RECURSIVE "
    1213            if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive")
    1214            else ""
    1215        )
    1216
    1217        return f"WITH {recursive}{sql}"

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

    1219    def cte_sql(self, expression: exp.CTE) -> str:
    1220        alias = expression.args.get("alias")
    1221        if alias:
    1222            alias.add_comments(expression.pop_comments())
    1223
    1224        alias_sql = self.sql(expression, "alias")
    1225
    1226        materialized = expression.args.get("materialized")
    1227        if materialized is False:
    1228            materialized = "NOT MATERIALIZED "
    1229        elif materialized:
    1230            materialized = "MATERIALIZED "
    1231
    1232        return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}"

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

    1234    def tablealias_sql(self, expression: exp.TableAlias) -> str:
    1235        alias = self.sql(expression, "this")
    1236        columns = self.expressions(expression, key="columns", flat=True)
    1237        columns = f"({columns})" if columns else ""
    1238
    1239        if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS:
    1240            columns = ""
    1241            self.unsupported("Named columns are not supported in table alias.")
    1242
    1243        if not alias and not self.dialect.UNNEST_COLUMN_ONLY:
    1244            alias = self._next_name()
    1245
    1246        return f"{alias}{columns}"

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

    1248    def bitstring_sql(self, expression: exp.BitString) -> str:
    1249        this = self.sql(expression, "this")
    1250        if self.dialect.BIT_START:
    1251            return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}"
    1252        return f"{int(this, 2)}"

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

    1254    def hexstring_sql(self, expression: exp.HexString) -> str:
    1255        this = self.sql(expression, "this")
    1256        if self.dialect.HEX_START:
    1257            return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"
    1258        return f"{int(this, 16)}"

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

    1260    def bytestring_sql(self, expression: exp.ByteString) -> str:
    1261        this = self.sql(expression, "this")
    1262        if self.dialect.BYTE_START:
    1263            return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}"
    1264        return this

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

    1266    def unicodestring_sql(self, expression: exp.UnicodeString) -> str:
    1267        this = self.sql(expression, "this")
    1268        escape = expression.args.get("escape")
    1269
    1270        if self.dialect.UNICODE_START:
    1271            escape_substitute = r"\\\1"
    1272            left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END
    1273        else:
    1274            escape_substitute = r"\\u\1"
    1275            left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END
    1276
    1277        if escape:
    1278            escape_pattern = re.compile(rf"{escape.name}(\d+)")
    1279            escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else ""
    1280        else:
    1281            escape_pattern = ESCAPED_UNICODE_RE
    1282            escape_sql = ""
    1283
    1284        if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE):
    1285            this = escape_pattern.sub(escape_substitute, this)
    1286
    1287        return f"{left_quote}{this}{right_quote}{escape_sql}"

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

    1289    def rawstring_sql(self, expression: exp.RawString) -> str:
    1290        string = self.escape_str(expression.this.replace("\\", "\\\\"), escape_backslash=False)
    1291        return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}"

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

    1293    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
    1294        this = self.sql(expression, "this")
    1295        specifier = self.sql(expression, "expression")
    1296        specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else ""
    1297        return f"{this}{specifier}"

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

    1299    def datatype_sql(self, expression: exp.DataType) -> str:
    1300        nested = ""
    1301        values = ""
    1302        interior = self.expressions(expression, flat=True)
    1303
    1304        type_value = expression.this
    1305        if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"):
    1306            type_sql = self.sql(expression, "kind")
    1307        else:
    1308            type_sql = (
    1309                self.TYPE_MAPPING.get(type_value, type_value.value)
    1310                if isinstance(type_value, exp.DataType.Type)
    1311                else type_value
    1312            )
    1313
    1314        if interior:
    1315            if expression.args.get("nested"):
    1316                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
    1317                if expression.args.get("values") is not None:
    1318                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
    1319                    values = self.expressions(expression, key="values", flat=True)
    1320                    values = f"{delimiters[0]}{values}{delimiters[1]}"
    1321            elif type_value == exp.DataType.Type.INTERVAL:
    1322                nested = f" {interior}"
    1323            else:
    1324                nested = f"({interior})"
    1325
    1326        type_sql = f"{type_sql}{nested}{values}"
    1327        if self.TZ_TO_WITH_TIME_ZONE and type_value in (
    1328            exp.DataType.Type.TIMETZ,
    1329            exp.DataType.Type.TIMESTAMPTZ,
    1330        ):
    1331            type_sql = f"{type_sql} WITH TIME ZONE"
    1332
    1333        return type_sql

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

    1335    def directory_sql(self, expression: exp.Directory) -> str:
    1336        local = "LOCAL " if expression.args.get("local") else ""
    1337        row_format = self.sql(expression, "row_format")
    1338        row_format = f" {row_format}" if row_format else ""
    1339        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"

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

    1341    def delete_sql(self, expression: exp.Delete) -> str:
    1342        this = self.sql(expression, "this")
    1343        this = f" FROM {this}" if this else ""
    1344        using = self.sql(expression, "using")
    1345        using = f" USING {using}" if using else ""
    1346        cluster = self.sql(expression, "cluster")
    1347        cluster = f" {cluster}" if cluster else ""
    1348        where = self.sql(expression, "where")
    1349        returning = self.sql(expression, "returning")
    1350        limit = self.sql(expression, "limit")
    1351        tables = self.expressions(expression, key="tables")
    1352        tables = f" {tables}" if tables else ""
    1353        if self.RETURNING_END:
    1354            expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}"
    1355        else:
    1356            expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}"
    1357        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")

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

    1359    def drop_sql(self, expression: exp.Drop) -> str:
    1360        this = self.sql(expression, "this")
    1361        expressions = self.expressions(expression, flat=True)
    1362        expressions = f" ({expressions})" if expressions else ""
    1363        kind = expression.args["kind"]
    1364        kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind
    1365        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    1366        concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else ""
    1367        on_cluster = self.sql(expression, "cluster")
    1368        on_cluster = f" {on_cluster}" if on_cluster else ""
    1369        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    1370        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    1371        cascade = " CASCADE" if expression.args.get("cascade") else ""
    1372        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
    1373        purge = " PURGE" if expression.args.get("purge") else ""
    1374        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

    1376    def set_operation(self, expression: exp.SetOperation) -> str:
    1377        op_type = type(expression)
    1378        op_name = op_type.key.upper()
    1379
    1380        distinct = expression.args.get("distinct")
    1381        if (
    1382            distinct is False
    1383            and op_type in (exp.Except, exp.Intersect)
    1384            and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE
    1385        ):
    1386            self.unsupported(f"{op_name} ALL is not supported")
    1387
    1388        default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type]
    1389
    1390        if distinct is None:
    1391            distinct = default_distinct
    1392            if distinct is None:
    1393                self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified")
    1394
    1395        if distinct is default_distinct:
    1396            kind = ""
    1397        else:
    1398            kind = " DISTINCT" if distinct else " ALL"
    1399
    1400        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1401        return f"{op_name}{kind}{by_name}"

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

    1403    def set_operations(self, expression: exp.SetOperation) -> str:
    1404        if not self.SET_OP_MODIFIERS:
    1405            limit = expression.args.get("limit")
    1406            order = expression.args.get("order")
    1407
    1408            if limit or order:
    1409                select = self._move_ctes_to_top_level(
    1410                    exp.subquery(expression, "_l_0", copy=False).select("*", copy=False)
    1411                )
    1412
    1413                if limit:
    1414                    select = select.limit(limit.pop(), copy=False)
    1415                if order:
    1416                    select = select.order_by(order.pop(), copy=False)
    1417                return self.sql(select)
    1418
    1419        sqls: t.List[str] = []
    1420        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    1421
    1422        while stack:
    1423            node = stack.pop()
    1424
    1425            if isinstance(node, exp.SetOperation):
    1426                stack.append(node.expression)
    1427                stack.append(
    1428                    self.maybe_comment(
    1429                        self.set_operation(node), comments=node.comments, separated=True
    1430                    )
    1431                )
    1432                stack.append(node.this)
    1433            else:
    1434                sqls.append(self.sql(node))
    1435
    1436        this = self.sep().join(sqls)
    1437        this = self.query_modifiers(expression, this)
    1438        return self.prepend_ctes(expression, this)

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

    1440    def fetch_sql(self, expression: exp.Fetch) -> str:
    1441        direction = expression.args.get("direction")
    1442        direction = f" {direction}" if direction else ""
    1443        count = self.sql(expression, "count")
    1444        count = f" {count}" if count else ""
    1445        if expression.args.get("percent"):
    1446            count = f"{count} PERCENT"
    1447        with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY"
    1448        return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}"

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

    1450    def filter_sql(self, expression: exp.Filter) -> str:
    1451        if self.AGGREGATE_FILTER_SUPPORTED:
    1452            this = self.sql(expression, "this")
    1453            where = self.sql(expression, "expression").strip()
    1454            return f"{this} FILTER({where})"
    1455
    1456        agg = expression.this
    1457        agg_arg = agg.this
    1458        cond = expression.expression.this
    1459        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
    1460        return self.sql(agg)

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

    1462    def hint_sql(self, expression: exp.Hint) -> str:
    1463        if not self.QUERY_HINTS:
    1464            self.unsupported("Hints are not supported")
    1465            return ""
    1466
    1467        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"

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

    1469    def indexparameters_sql(self, expression: exp.IndexParameters) -> str:
    1470        using = self.sql(expression, "using")
    1471        using = f" USING {using}" if using else ""
    1472        columns = self.expressions(expression, key="columns", flat=True)
    1473        columns = f"({columns})" if columns else ""
    1474        partition_by = self.expressions(expression, key="partition_by", flat=True)
    1475        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
    1476        where = self.sql(expression, "where")
    1477        include = self.expressions(expression, key="include", flat=True)
    1478        if include:
    1479            include = f" INCLUDE ({include})"
    1480        with_storage = self.expressions(expression, key="with_storage", flat=True)
    1481        with_storage = f" WITH ({with_storage})" if with_storage else ""
    1482        tablespace = self.sql(expression, "tablespace")
    1483        tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else ""
    1484        on = self.sql(expression, "on")
    1485        on = f" ON {on}" if on else ""
    1486
    1487        return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"

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

    1489    def index_sql(self, expression: exp.Index) -> str:
    1490        unique = "UNIQUE " if expression.args.get("unique") else ""
    1491        primary = "PRIMARY " if expression.args.get("primary") else ""
    1492        amp = "AMP " if expression.args.get("amp") else ""
    1493        name = self.sql(expression, "this")
    1494        name = f"{name} " if name else ""
    1495        table = self.sql(expression, "table")
    1496        table = f"{self.INDEX_ON} {table}" if table else ""
    1497
    1498        index = "INDEX " if not table else ""
    1499
    1500        params = self.sql(expression, "params")
    1501        return f"{unique}{primary}{amp}{index}{name}{table}{params}"

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

    1503    def identifier_sql(self, expression: exp.Identifier) -> str:
    1504        text = expression.name
    1505        lower = text.lower()
    1506        text = lower if self.normalize and not expression.quoted else text
    1507        text = text.replace(self._identifier_end, self._escaped_identifier_end)
    1508        if (
    1509            expression.quoted
    1510            or self.dialect.can_identify(text, self.identify)
    1511            or lower in self.RESERVED_KEYWORDS
    1512            or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
    1513        ):
    1514            text = f"{self._identifier_start}{text}{self._identifier_end}"
    1515        return text

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

    1517    def hex_sql(self, expression: exp.Hex) -> str:
    1518        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1519        if self.dialect.HEX_LOWERCASE:
    1520            text = self.func("LOWER", text)
    1521
    1522        return text

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

    1524    def lowerhex_sql(self, expression: exp.LowerHex) -> str:
    1525        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1526        if not self.dialect.HEX_LOWERCASE:
    1527            text = self.func("LOWER", text)
    1528        return text

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

    1530    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    1531        input_format = self.sql(expression, "input_format")
    1532        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    1533        output_format = self.sql(expression, "output_format")
    1534        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    1535        return self.sep().join((input_format, output_format))

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

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

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

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

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

    1544    def properties_sql(self, expression: exp.Properties) -> str:
    1545        root_properties = []
    1546        with_properties = []
    1547
    1548        for p in expression.expressions:
    1549            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1550            if p_loc == exp.Properties.Location.POST_WITH:
    1551                with_properties.append(p)
    1552            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    1553                root_properties.append(p)
    1554
    1555        root_props = self.root_properties(exp.Properties(expressions=root_properties))
    1556        with_props = self.with_properties(exp.Properties(expressions=with_properties))
    1557
    1558        if root_props and with_props and not self.pretty:
    1559            with_props = " " + with_props
    1560
    1561        return root_props + with_props

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

    1563    def root_properties(self, properties: exp.Properties) -> str:
    1564        if properties.expressions:
    1565            return self.expressions(properties, indent=False, sep=" ")
    1566        return ""

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

    1568    def properties(
    1569        self,
    1570        properties: exp.Properties,
    1571        prefix: str = "",
    1572        sep: str = ", ",
    1573        suffix: str = "",
    1574        wrapped: bool = True,
    1575    ) -> str:
    1576        if properties.expressions:
    1577            expressions = self.expressions(properties, sep=sep, indent=False)
    1578            if expressions:
    1579                expressions = self.wrap(expressions) if wrapped else expressions
    1580                return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}"
    1581        return ""

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

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

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

    1586    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
    1587        properties_locs = defaultdict(list)
    1588        for p in properties.expressions:
    1589            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1590            if p_loc != exp.Properties.Location.UNSUPPORTED:
    1591                properties_locs[p_loc].append(p)
    1592            else:
    1593                self.unsupported(f"Unsupported property {p.key}")
    1594
    1595        return properties_locs

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

    1597    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
    1598        if isinstance(expression.this, exp.Dot):
    1599            return self.sql(expression, "this")
    1600        return f"'{expression.name}'" if string_key else expression.name

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

    1602    def property_sql(self, expression: exp.Property) -> str:
    1603        property_cls = expression.__class__
    1604        if property_cls == exp.Property:
    1605            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
    1606
    1607        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    1608        if not property_name:
    1609            self.unsupported(f"Unsupported property {expression.key}")
    1610
    1611        return f"{property_name}={self.sql(expression, 'this')}"

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

    1613    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
    1614        if self.SUPPORTS_CREATE_TABLE_LIKE:
    1615            options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
    1616            options = f" {options}" if options else ""
    1617
    1618            like = f"LIKE {self.sql(expression, 'this')}{options}"
    1619            if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema):
    1620                like = f"({like})"
    1621
    1622            return like
    1623
    1624        if expression.expressions:
    1625            self.unsupported("Transpilation of LIKE property options is unsupported")
    1626
    1627        select = exp.select("*").from_(expression.this).limit(0)
    1628        return f"AS {self.sql(select)}"

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

    1630    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1631        no = "NO " if expression.args.get("no") else ""
    1632        protection = " PROTECTION" if expression.args.get("protection") else ""
    1633        return f"{no}FALLBACK{protection}"

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

    1635    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1636        no = "NO " if expression.args.get("no") else ""
    1637        local = expression.args.get("local")
    1638        local = f"{local} " if local else ""
    1639        dual = "DUAL " if expression.args.get("dual") else ""
    1640        before = "BEFORE " if expression.args.get("before") else ""
    1641        after = "AFTER " if expression.args.get("after") else ""
    1642        return f"{no}{local}{dual}{before}{after}JOURNAL"

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

    1644    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1645        freespace = self.sql(expression, "this")
    1646        percent = " PERCENT" if expression.args.get("percent") else ""
    1647        return f"FREESPACE={freespace}{percent}"

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

    1649    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1650        if expression.args.get("default"):
    1651            property = "DEFAULT"
    1652        elif expression.args.get("on"):
    1653            property = "ON"
    1654        else:
    1655            property = "OFF"
    1656        return f"CHECKSUM={property}"

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

    1658    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1659        if expression.args.get("no"):
    1660            return "NO MERGEBLOCKRATIO"
    1661        if expression.args.get("default"):
    1662            return "DEFAULT MERGEBLOCKRATIO"
    1663
    1664        percent = " PERCENT" if expression.args.get("percent") else ""
    1665        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"

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

    1667    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1668        default = expression.args.get("default")
    1669        minimum = expression.args.get("minimum")
    1670        maximum = expression.args.get("maximum")
    1671        if default or minimum or maximum:
    1672            if default:
    1673                prop = "DEFAULT"
    1674            elif minimum:
    1675                prop = "MINIMUM"
    1676            else:
    1677                prop = "MAXIMUM"
    1678            return f"{prop} DATABLOCKSIZE"
    1679        units = expression.args.get("units")
    1680        units = f" {units}" if units else ""
    1681        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"

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

    1683    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1684        autotemp = expression.args.get("autotemp")
    1685        always = expression.args.get("always")
    1686        default = expression.args.get("default")
    1687        manual = expression.args.get("manual")
    1688        never = expression.args.get("never")
    1689
    1690        if autotemp is not None:
    1691            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1692        elif always:
    1693            prop = "ALWAYS"
    1694        elif default:
    1695            prop = "DEFAULT"
    1696        elif manual:
    1697            prop = "MANUAL"
    1698        elif never:
    1699            prop = "NEVER"
    1700        return f"BLOCKCOMPRESSION={prop}"

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

    1702    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1703        no = expression.args.get("no")
    1704        no = " NO" if no else ""
    1705        concurrent = expression.args.get("concurrent")
    1706        concurrent = " CONCURRENT" if concurrent else ""
    1707        target = self.sql(expression, "target")
    1708        target = f" {target}" if target else ""
    1709        return f"WITH{no}{concurrent} ISOLATED LOADING{target}"

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

    1711    def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str:
    1712        if isinstance(expression.this, list):
    1713            return f"IN ({self.expressions(expression, key='this', flat=True)})"
    1714        if expression.this:
    1715            modulus = self.sql(expression, "this")
    1716            remainder = self.sql(expression, "expression")
    1717            return f"WITH (MODULUS {modulus}, REMAINDER {remainder})"
    1718
    1719        from_expressions = self.expressions(expression, key="from_expressions", flat=True)
    1720        to_expressions = self.expressions(expression, key="to_expressions", flat=True)
    1721        return f"FROM ({from_expressions}) TO ({to_expressions})"

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

    1723    def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str:
    1724        this = self.sql(expression, "this")
    1725
    1726        for_values_or_default = expression.expression
    1727        if isinstance(for_values_or_default, exp.PartitionBoundSpec):
    1728            for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}"
    1729        else:
    1730            for_values_or_default = " DEFAULT"
    1731
    1732        return f"PARTITION OF {this}{for_values_or_default}"

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

    1734    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1735        kind = expression.args.get("kind")
    1736        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1737        for_or_in = expression.args.get("for_or_in")
    1738        for_or_in = f" {for_or_in}" if for_or_in else ""
    1739        lock_type = expression.args.get("lock_type")
    1740        override = " OVERRIDE" if expression.args.get("override") else ""
    1741        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"

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

    1743    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1744        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1745        statistics = expression.args.get("statistics")
    1746        statistics_sql = ""
    1747        if statistics is not None:
    1748            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1749        return f"{data_sql}{statistics_sql}"

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

    1751    def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str:
    1752        this = self.sql(expression, "this")
    1753        this = f"HISTORY_TABLE={this}" if this else ""
    1754        data_consistency: t.Optional[str] = self.sql(expression, "data_consistency")
    1755        data_consistency = (
    1756            f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None
    1757        )
    1758        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    1759        retention_period = (
    1760            f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None
    1761        )
    1762
    1763        if this:
    1764            on_sql = self.func("ON", this, data_consistency, retention_period)
    1765        else:
    1766            on_sql = "ON" if expression.args.get("on") else "OFF"
    1767
    1768        sql = f"SYSTEM_VERSIONING={on_sql}"
    1769
    1770        return f"WITH({sql})" if expression.args.get("with") else sql

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

    1772    def insert_sql(self, expression: exp.Insert) -> str:
    1773        hint = self.sql(expression, "hint")
    1774        overwrite = expression.args.get("overwrite")
    1775
    1776        if isinstance(expression.this, exp.Directory):
    1777            this = " OVERWRITE" if overwrite else " INTO"
    1778        else:
    1779            this = self.INSERT_OVERWRITE if overwrite else " INTO"
    1780
    1781        stored = self.sql(expression, "stored")
    1782        stored = f" {stored}" if stored else ""
    1783        alternative = expression.args.get("alternative")
    1784        alternative = f" OR {alternative}" if alternative else ""
    1785        ignore = " IGNORE" if expression.args.get("ignore") else ""
    1786        is_function = expression.args.get("is_function")
    1787        if is_function:
    1788            this = f"{this} FUNCTION"
    1789        this = f"{this} {self.sql(expression, 'this')}"
    1790
    1791        exists = " IF EXISTS" if expression.args.get("exists") else ""
    1792        where = self.sql(expression, "where")
    1793        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
    1794        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
    1795        on_conflict = self.sql(expression, "conflict")
    1796        on_conflict = f" {on_conflict}" if on_conflict else ""
    1797        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1798        returning = self.sql(expression, "returning")
    1799
    1800        if self.RETURNING_END:
    1801            expression_sql = f"{expression_sql}{on_conflict}{returning}"
    1802        else:
    1803            expression_sql = f"{returning}{expression_sql}{on_conflict}"
    1804
    1805        partition_by = self.sql(expression, "partition")
    1806        partition_by = f" {partition_by}" if partition_by else ""
    1807        settings = self.sql(expression, "settings")
    1808        settings = f" {settings}" if settings else ""
    1809
    1810        source = self.sql(expression, "source")
    1811        source = f"TABLE {source}" if source else ""
    1812
    1813        sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}"
    1814        return self.prepend_ctes(expression, sql)

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

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

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

    1819    def kill_sql(self, expression: exp.Kill) -> str:
    1820        kind = self.sql(expression, "kind")
    1821        kind = f" {kind}" if kind else ""
    1822        this = self.sql(expression, "this")
    1823        this = f" {this}" if this else ""
    1824        return f"KILL{kind}{this}"

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

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

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

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

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

    1832    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1833        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1834
    1835        constraint = self.sql(expression, "constraint")
    1836        constraint = f" ON CONSTRAINT {constraint}" if constraint else ""
    1837
    1838        conflict_keys = self.expressions(expression, key="conflict_keys", flat=True)
    1839        conflict_keys = f"({conflict_keys}) " if conflict_keys else " "
    1840        action = self.sql(expression, "action")
    1841
    1842        expressions = self.expressions(expression, flat=True)
    1843        if expressions:
    1844            set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
    1845            expressions = f" {set_keyword}{expressions}"
    1846
    1847        return f"{conflict}{constraint}{conflict_keys}{action}{expressions}"

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

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

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

    1852    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1853        fields = self.sql(expression, "fields")
    1854        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1855        escaped = self.sql(expression, "escaped")
    1856        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1857        items = self.sql(expression, "collection_items")
    1858        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1859        keys = self.sql(expression, "map_keys")
    1860        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1861        lines = self.sql(expression, "lines")
    1862        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1863        null = self.sql(expression, "null")
    1864        null = f" NULL DEFINED AS {null}" if null else ""
    1865        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"

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

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

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

    1870    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1871        this = f"{self.sql(expression, 'this')} INDEX"
    1872        target = self.sql(expression, "target")
    1873        target = f" FOR {target}" if target else ""
    1874        return f"{this}{target} ({self.expressions(expression, flat=True)})"

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

    1876    def historicaldata_sql(self, expression: exp.HistoricalData) -> str:
    1877        this = self.sql(expression, "this")
    1878        kind = self.sql(expression, "kind")
    1879        expr = self.sql(expression, "expression")
    1880        return f"{this} ({kind} => {expr})"

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

    1882    def table_parts(self, expression: exp.Table) -> str:
    1883        return ".".join(
    1884            self.sql(part)
    1885            for part in (
    1886                expression.args.get("catalog"),
    1887                expression.args.get("db"),
    1888                expression.args.get("this"),
    1889            )
    1890            if part is not None
    1891        )

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

    1893    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1894        table = self.table_parts(expression)
    1895        only = "ONLY " if expression.args.get("only") else ""
    1896        partition = self.sql(expression, "partition")
    1897        partition = f" {partition}" if partition else ""
    1898        version = self.sql(expression, "version")
    1899        version = f" {version}" if version else ""
    1900        alias = self.sql(expression, "alias")
    1901        alias = f"{sep}{alias}" if alias else ""
    1902
    1903        sample = self.sql(expression, "sample")
    1904        if self.dialect.ALIAS_POST_TABLESAMPLE:
    1905            sample_pre_alias = sample
    1906            sample_post_alias = ""
    1907        else:
    1908            sample_pre_alias = ""
    1909            sample_post_alias = sample
    1910
    1911        hints = self.expressions(expression, key="hints", sep=" ")
    1912        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
    1913        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    1914        joins = self.indent(
    1915            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
    1916        )
    1917        laterals = self.expressions(expression, key="laterals", sep="")
    1918
    1919        file_format = self.sql(expression, "format")
    1920        if file_format:
    1921            pattern = self.sql(expression, "pattern")
    1922            pattern = f", PATTERN => {pattern}" if pattern else ""
    1923            file_format = f" (FILE_FORMAT => {file_format}{pattern})"
    1924
    1925        ordinality = expression.args.get("ordinality") or ""
    1926        if ordinality:
    1927            ordinality = f" WITH ORDINALITY{alias}"
    1928            alias = ""
    1929
    1930        when = self.sql(expression, "when")
    1931        if when:
    1932            table = f"{table} {when}"
    1933
    1934        changes = self.sql(expression, "changes")
    1935        changes = f" {changes}" if changes else ""
    1936
    1937        rows_from = self.expressions(expression, key="rows_from")
    1938        if rows_from:
    1939            table = f"ROWS FROM {self.wrap(rows_from)}"
    1940
    1941        return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}"

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

    1943    def tablesample_sql(
    1944        self,
    1945        expression: exp.TableSample,
    1946        tablesample_keyword: t.Optional[str] = None,
    1947    ) -> str:
    1948        method = self.sql(expression, "method")
    1949        method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    1950        numerator = self.sql(expression, "bucket_numerator")
    1951        denominator = self.sql(expression, "bucket_denominator")
    1952        field = self.sql(expression, "bucket_field")
    1953        field = f" ON {field}" if field else ""
    1954        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    1955        seed = self.sql(expression, "seed")
    1956        seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else ""
    1957
    1958        size = self.sql(expression, "size")
    1959        if size and self.TABLESAMPLE_SIZE_IS_ROWS:
    1960            size = f"{size} ROWS"
    1961
    1962        percent = self.sql(expression, "percent")
    1963        if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT:
    1964            percent = f"{percent} PERCENT"
    1965
    1966        expr = f"{bucket}{percent}{size}"
    1967        if self.TABLESAMPLE_REQUIRES_PARENS:
    1968            expr = f"({expr})"
    1969
    1970        return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}"

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

    1972    def pivot_sql(self, expression: exp.Pivot) -> str:
    1973        expressions = self.expressions(expression, flat=True)
    1974
    1975        if expression.this:
    1976            this = self.sql(expression, "this")
    1977            if not expressions:
    1978                return f"UNPIVOT {this}"
    1979
    1980            on = f"{self.seg('ON')} {expressions}"
    1981            using = self.expressions(expression, key="using", flat=True)
    1982            using = f"{self.seg('USING')} {using}" if using else ""
    1983            group = self.sql(expression, "group")
    1984            return f"PIVOT {this}{on}{using}{group}"
    1985
    1986        alias = self.sql(expression, "alias")
    1987        alias = f" AS {alias}" if alias else ""
    1988        direction = self.seg("UNPIVOT" if expression.unpivot else "PIVOT")
    1989
    1990        field = self.sql(expression, "field")
    1991
    1992        include_nulls = expression.args.get("include_nulls")
    1993        if include_nulls is not None:
    1994            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
    1995        else:
    1996            nulls = ""
    1997
    1998        default_on_null = self.sql(expression, "default_on_null")
    1999        default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else ""
    2000        return f"{direction}{nulls}({expressions} FOR {field}{default_on_null}){alias}"

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

    2002    def version_sql(self, expression: exp.Version) -> str:
    2003        this = f"FOR {expression.name}"
    2004        kind = expression.text("kind")
    2005        expr = self.sql(expression, "expression")
    2006        return f"{this} {kind} {expr}"

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

    2008    def tuple_sql(self, expression: exp.Tuple) -> str:
    2009        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

    2011    def update_sql(self, expression: exp.Update) -> str:
    2012        this = self.sql(expression, "this")
    2013        set_sql = self.expressions(expression, flat=True)
    2014        from_sql = self.sql(expression, "from")
    2015        where_sql = self.sql(expression, "where")
    2016        returning = self.sql(expression, "returning")
    2017        order = self.sql(expression, "order")
    2018        limit = self.sql(expression, "limit")
    2019        if self.RETURNING_END:
    2020            expression_sql = f"{from_sql}{where_sql}{returning}"
    2021        else:
    2022            expression_sql = f"{returning}{from_sql}{where_sql}"
    2023        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
    2024        return self.prepend_ctes(expression, sql)

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

    2026    def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str:
    2027        values_as_table = values_as_table and self.VALUES_AS_TABLE
    2028
    2029        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
    2030        if values_as_table or not expression.find_ancestor(exp.From, exp.Join):
    2031            args = self.expressions(expression)
    2032            alias = self.sql(expression, "alias")
    2033            values = f"VALUES{self.seg('')}{args}"
    2034            values = (
    2035                f"({values})"
    2036                if self.WRAP_DERIVED_VALUES
    2037                and (alias or isinstance(expression.parent, (exp.From, exp.Table)))
    2038                else values
    2039            )
    2040            return f"{values} AS {alias}" if alias else values
    2041
    2042        # Converts `VALUES...` expression into a series of select unions.
    2043        alias_node = expression.args.get("alias")
    2044        column_names = alias_node and alias_node.columns
    2045
    2046        selects: t.List[exp.Query] = []
    2047
    2048        for i, tup in enumerate(expression.expressions):
    2049            row = tup.expressions
    2050
    2051            if i == 0 and column_names:
    2052                row = [
    2053                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
    2054                ]
    2055
    2056            selects.append(exp.Select(expressions=row))
    2057
    2058        if self.pretty:
    2059            # This may result in poor performance for large-cardinality `VALUES` tables, due to
    2060            # the deep nesting of the resulting exp.Unions. If this is a problem, either increase
    2061            # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`.
    2062            query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects)
    2063            return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False))
    2064
    2065        alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else ""
    2066        unions = " UNION ALL ".join(self.sql(select) for select in selects)
    2067        return f"({unions}){alias}"

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

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

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

    2072    @unsupported_args("expressions")
    2073    def into_sql(self, expression: exp.Into) -> str:
    2074        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    2075        unlogged = " UNLOGGED" if expression.args.get("unlogged") else ""
    2076        return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"

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

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

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

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

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

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

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

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

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

    2093    def group_sql(self, expression: exp.Group) -> str:
    2094        group_by_all = expression.args.get("all")
    2095        if group_by_all is True:
    2096            modifier = " ALL"
    2097        elif group_by_all is False:
    2098            modifier = " DISTINCT"
    2099        else:
    2100            modifier = ""
    2101
    2102        group_by = self.op_expressions(f"GROUP BY{modifier}", expression)
    2103
    2104        grouping_sets = self.expressions(expression, key="grouping_sets")
    2105        cube = self.expressions(expression, key="cube")
    2106        rollup = self.expressions(expression, key="rollup")
    2107
    2108        groupings = csv(
    2109            self.seg(grouping_sets) if grouping_sets else "",
    2110            self.seg(cube) if cube else "",
    2111            self.seg(rollup) if rollup else "",
    2112            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    2113            sep=self.GROUPINGS_SEP,
    2114        )
    2115
    2116        if (
    2117            expression.expressions
    2118            and groupings
    2119            and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP")
    2120        ):
    2121            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    2122
    2123        return f"{group_by}{groupings}"

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

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

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

    2129    def connect_sql(self, expression: exp.Connect) -> str:
    2130        start = self.sql(expression, "start")
    2131        start = self.seg(f"START WITH {start}") if start else ""
    2132        nocycle = " NOCYCLE" if expression.args.get("nocycle") else ""
    2133        connect = self.sql(expression, "connect")
    2134        connect = self.seg(f"CONNECT BY{nocycle} {connect}")
    2135        return start + connect

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

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

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

    2140    def join_sql(self, expression: exp.Join) -> str:
    2141        if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"):
    2142            side = None
    2143        else:
    2144            side = expression.side
    2145
    2146        op_sql = " ".join(
    2147            op
    2148            for op in (
    2149                expression.method,
    2150                "GLOBAL" if expression.args.get("global") else None,
    2151                side,
    2152                expression.kind,
    2153                expression.hint if self.JOIN_HINTS else None,
    2154            )
    2155            if op
    2156        )
    2157        match_cond = self.sql(expression, "match_condition")
    2158        match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else ""
    2159        on_sql = self.sql(expression, "on")
    2160        using = expression.args.get("using")
    2161
    2162        if not on_sql and using:
    2163            on_sql = csv(*(self.sql(column) for column in using))
    2164
    2165        this = expression.this
    2166        this_sql = self.sql(this)
    2167
    2168        exprs = self.expressions(expression)
    2169        if exprs:
    2170            this_sql = f"{this_sql},{self.seg(exprs)}"
    2171
    2172        if on_sql:
    2173            on_sql = self.indent(on_sql, skip_first=True)
    2174            space = self.seg(" " * self.pad) if self.pretty else " "
    2175            if using:
    2176                on_sql = f"{space}USING ({on_sql})"
    2177            else:
    2178                on_sql = f"{space}ON {on_sql}"
    2179        elif not op_sql:
    2180            if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None:
    2181                return f" {this_sql}"
    2182
    2183            return f", {this_sql}"
    2184
    2185        if op_sql != "STRAIGHT_JOIN":
    2186            op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    2187
    2188        return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}"

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

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

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

    2195    def lateral_op(self, expression: exp.Lateral) -> str:
    2196        cross_apply = expression.args.get("cross_apply")
    2197
    2198        # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/
    2199        if cross_apply is True:
    2200            op = "INNER JOIN "
    2201        elif cross_apply is False:
    2202            op = "LEFT JOIN "
    2203        else:
    2204            op = ""
    2205
    2206        return f"{op}LATERAL"

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

    2208    def lateral_sql(self, expression: exp.Lateral) -> str:
    2209        this = self.sql(expression, "this")
    2210
    2211        if expression.args.get("view"):
    2212            alias = expression.args["alias"]
    2213            columns = self.expressions(alias, key="columns", flat=True)
    2214            table = f" {alias.name}" if alias.name else ""
    2215            columns = f" AS {columns}" if columns else ""
    2216            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    2217            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    2218
    2219        alias = self.sql(expression, "alias")
    2220        alias = f" AS {alias}" if alias else ""
    2221        return f"{self.lateral_op(expression)} {this}{alias}"

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

    2223    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    2224        this = self.sql(expression, "this")
    2225
    2226        args = [
    2227            self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e
    2228            for e in (expression.args.get(k) for k in ("offset", "expression"))
    2229            if e
    2230        ]
    2231
    2232        args_sql = ", ".join(self.sql(e) for e in args)
    2233        args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql
    2234        expressions = self.expressions(expression, flat=True)
    2235        expressions = f" BY {expressions}" if expressions else ""
    2236
    2237        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{expressions}"

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

    2239    def offset_sql(self, expression: exp.Offset) -> str:
    2240        this = self.sql(expression, "this")
    2241        value = expression.expression
    2242        value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value
    2243        expressions = self.expressions(expression, flat=True)
    2244        expressions = f" BY {expressions}" if expressions else ""
    2245        return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"

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

    2247    def setitem_sql(self, expression: exp.SetItem) -> str:
    2248        kind = self.sql(expression, "kind")
    2249        kind = f"{kind} " if kind else ""
    2250        this = self.sql(expression, "this")
    2251        expressions = self.expressions(expression)
    2252        collate = self.sql(expression, "collate")
    2253        collate = f" COLLATE {collate}" if collate else ""
    2254        global_ = "GLOBAL " if expression.args.get("global") else ""
    2255        return f"{global_}{kind}{this}{expressions}{collate}"

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

    2257    def set_sql(self, expression: exp.Set) -> str:
    2258        expressions = (
    2259            f" {self.expressions(expression, flat=True)}" if expression.expressions else ""
    2260        )
    2261        tag = " TAG" if expression.args.get("tag") else ""
    2262        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"

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

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

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

    2267    def lock_sql(self, expression: exp.Lock) -> str:
    2268        if not self.LOCKING_READS_SUPPORTED:
    2269            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    2270            return ""
    2271
    2272        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    2273        expressions = self.expressions(expression, flat=True)
    2274        expressions = f" OF {expressions}" if expressions else ""
    2275        wait = expression.args.get("wait")
    2276
    2277        if wait is not None:
    2278            if isinstance(wait, exp.Literal):
    2279                wait = f" WAIT {self.sql(wait)}"
    2280            else:
    2281                wait = " NOWAIT" if wait else " SKIP LOCKED"
    2282
    2283        return f"{lock_type}{expressions}{wait or ''}"

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

    2285    def literal_sql(self, expression: exp.Literal) -> str:
    2286        text = expression.this or ""
    2287        if expression.is_string:
    2288            text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}"
    2289        return text

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

    2291    def escape_str(self, text: str, escape_backslash: bool = True) -> str:
    2292        if self.dialect.ESCAPED_SEQUENCES:
    2293            to_escaped = self.dialect.ESCAPED_SEQUENCES
    2294            text = "".join(
    2295                to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text
    2296            )
    2297
    2298        return self._replace_line_breaks(text).replace(
    2299            self.dialect.QUOTE_END, self._escaped_quote_end
    2300        )

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

    2302    def loaddata_sql(self, expression: exp.LoadData) -> str:
    2303        local = " LOCAL" if expression.args.get("local") else ""
    2304        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    2305        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    2306        this = f" INTO TABLE {self.sql(expression, 'this')}"
    2307        partition = self.sql(expression, "partition")
    2308        partition = f" {partition}" if partition else ""
    2309        input_format = self.sql(expression, "input_format")
    2310        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    2311        serde = self.sql(expression, "serde")
    2312        serde = f" SERDE {serde}" if serde else ""
    2313        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"

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

    2315    def null_sql(self, *_) -> str:
    2316        return "NULL"

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

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

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

    2321    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    2322        this = self.sql(expression, "this")
    2323        this = f"{this} " if this else this
    2324        siblings = "SIBLINGS " if expression.args.get("siblings") else ""
    2325        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

    2327    def withfill_sql(self, expression: exp.WithFill) -> str:
    2328        from_sql = self.sql(expression, "from")
    2329        from_sql = f" FROM {from_sql}" if from_sql else ""
    2330        to_sql = self.sql(expression, "to")
    2331        to_sql = f" TO {to_sql}" if to_sql else ""
    2332        step_sql = self.sql(expression, "step")
    2333        step_sql = f" STEP {step_sql}" if step_sql else ""
    2334        interpolated_values = [
    2335            f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}"
    2336            if isinstance(e, exp.Alias)
    2337            else self.sql(e, "this")
    2338            for e in expression.args.get("interpolate") or []
    2339        ]
    2340        interpolate = (
    2341            f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else ""
    2342        )
    2343        return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}"

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

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

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

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

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

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

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

    2354    def ordered_sql(self, expression: exp.Ordered) -> str:
    2355        desc = expression.args.get("desc")
    2356        asc = not desc
    2357
    2358        nulls_first = expression.args.get("nulls_first")
    2359        nulls_last = not nulls_first
    2360        nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large"
    2361        nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small"
    2362        nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last"
    2363
    2364        this = self.sql(expression, "this")
    2365
    2366        sort_order = " DESC" if desc else (" ASC" if desc is False else "")
    2367        nulls_sort_change = ""
    2368        if nulls_first and (
    2369            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
    2370        ):
    2371            nulls_sort_change = " NULLS FIRST"
    2372        elif (
    2373            nulls_last
    2374            and ((asc and nulls_are_small) or (desc and nulls_are_large))
    2375            and not nulls_are_last
    2376        ):
    2377            nulls_sort_change = " NULLS LAST"
    2378
    2379        # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it
    2380        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
    2381            window = expression.find_ancestor(exp.Window, exp.Select)
    2382            if isinstance(window, exp.Window) and window.args.get("spec"):
    2383                self.unsupported(
    2384                    f"'{nulls_sort_change.strip()}' translation not supported in window functions"
    2385                )
    2386                nulls_sort_change = ""
    2387            elif (
    2388                self.NULL_ORDERING_SUPPORTED is False
    2389                and (isinstance(expression.find_ancestor(exp.AggFunc, exp.Select), exp.AggFunc))
    2390                and (
    2391                    (asc and nulls_sort_change == " NULLS LAST")
    2392                    or (desc and nulls_sort_change == " NULLS FIRST")
    2393                )
    2394            ):
    2395                self.unsupported(
    2396                    f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order"
    2397                )
    2398                nulls_sort_change = ""
    2399            elif self.NULL_ORDERING_SUPPORTED is None:
    2400                if expression.this.is_int:
    2401                    self.unsupported(
    2402                        f"'{nulls_sort_change.strip()}' translation not supported with positional ordering"
    2403                    )
    2404                elif not isinstance(expression.this, exp.Rand):
    2405                    null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else ""
    2406                    this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}"
    2407                nulls_sort_change = ""
    2408
    2409        with_fill = self.sql(expression, "with_fill")
    2410        with_fill = f" {with_fill}" if with_fill else ""
    2411
    2412        return f"{this}{sort_order}{nulls_sort_change}{with_fill}"

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

    2414    def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str:
    2415        window_frame = self.sql(expression, "window_frame")
    2416        window_frame = f"{window_frame} " if window_frame else ""
    2417
    2418        this = self.sql(expression, "this")
    2419
    2420        return f"{window_frame}{this}"

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

    2422    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    2423        partition = self.partition_by_sql(expression)
    2424        order = self.sql(expression, "order")
    2425        measures = self.expressions(expression, key="measures")
    2426        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    2427        rows = self.sql(expression, "rows")
    2428        rows = self.seg(rows) if rows else ""
    2429        after = self.sql(expression, "after")
    2430        after = self.seg(after) if after else ""
    2431        pattern = self.sql(expression, "pattern")
    2432        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    2433        definition_sqls = [
    2434            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    2435            for definition in expression.args.get("define", [])
    2436        ]
    2437        definitions = self.expressions(sqls=definition_sqls)
    2438        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    2439        body = "".join(
    2440            (
    2441                partition,
    2442                order,
    2443                measures,
    2444                rows,
    2445                after,
    2446                pattern,
    2447                define,
    2448            )
    2449        )
    2450        alias = self.sql(expression, "alias")
    2451        alias = f" {alias}" if alias else ""
    2452        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"

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

    2454    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    2455        limit = expression.args.get("limit")
    2456
    2457        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    2458            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
    2459        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    2460            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
    2461
    2462        return csv(
    2463            *sqls,
    2464            *[self.sql(join) for join in expression.args.get("joins") or []],
    2465            self.sql(expression, "connect"),
    2466            self.sql(expression, "match"),
    2467            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    2468            self.sql(expression, "prewhere"),
    2469            self.sql(expression, "where"),
    2470            self.sql(expression, "group"),
    2471            self.sql(expression, "having"),
    2472            *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()],
    2473            self.sql(expression, "order"),
    2474            *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit),
    2475            *self.after_limit_modifiers(expression),
    2476            self.options_modifier(expression),
    2477            sep="",
    2478        )

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

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

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

    2484    def queryoption_sql(self, expression: exp.QueryOption) -> str:
    2485        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

    2487    def offset_limit_modifiers(
    2488        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    2489    ) -> t.List[str]:
    2490        return [
    2491            self.sql(expression, "offset") if fetch else self.sql(limit),
    2492            self.sql(limit) if fetch else self.sql(expression, "offset"),
    2493        ]

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

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

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

    2500    def select_sql(self, expression: exp.Select) -> str:
    2501        into = expression.args.get("into")
    2502        if not self.SUPPORTS_SELECT_INTO and into:
    2503            into.pop()
    2504
    2505        hint = self.sql(expression, "hint")
    2506        distinct = self.sql(expression, "distinct")
    2507        distinct = f" {distinct}" if distinct else ""
    2508        kind = self.sql(expression, "kind")
    2509
    2510        limit = expression.args.get("limit")
    2511        if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP:
    2512            top = self.limit_sql(limit, top=True)
    2513            limit.pop()
    2514        else:
    2515            top = ""
    2516
    2517        expressions = self.expressions(expression)
    2518
    2519        if kind:
    2520            if kind in self.SELECT_KINDS:
    2521                kind = f" AS {kind}"
    2522            else:
    2523                if kind == "STRUCT":
    2524                    expressions = self.expressions(
    2525                        sqls=[
    2526                            self.sql(
    2527                                exp.Struct(
    2528                                    expressions=[
    2529                                        exp.PropertyEQ(this=e.args.get("alias"), expression=e.this)
    2530                                        if isinstance(e, exp.Alias)
    2531                                        else e
    2532                                        for e in expression.expressions
    2533                                    ]
    2534                                )
    2535                            )
    2536                        ]
    2537                    )
    2538                kind = ""
    2539
    2540        operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ")
    2541        operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else ""
    2542
    2543        # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata
    2544        # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first.
    2545        top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}"
    2546        expressions = f"{self.sep()}{expressions}" if expressions else expressions
    2547        sql = self.query_modifiers(
    2548            expression,
    2549            f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}",
    2550            self.sql(expression, "into", comment=False),
    2551            self.sql(expression, "from", comment=False),
    2552        )
    2553
    2554        # If both the CTE and SELECT clauses have comments, generate the latter earlier
    2555        if expression.args.get("with"):
    2556            sql = self.maybe_comment(sql, expression)
    2557            expression.pop_comments()
    2558
    2559        sql = self.prepend_ctes(expression, sql)
    2560
    2561        if not self.SUPPORTS_SELECT_INTO and into:
    2562            if into.args.get("temporary"):
    2563                table_kind = " TEMPORARY"
    2564            elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"):
    2565                table_kind = " UNLOGGED"
    2566            else:
    2567                table_kind = ""
    2568            sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}"
    2569
    2570        return sql

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

    2572    def schema_sql(self, expression: exp.Schema) -> str:
    2573        this = self.sql(expression, "this")
    2574        sql = self.schema_columns_sql(expression)
    2575        return f"{this} {sql}" if this and sql else this or sql

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

    2577    def schema_columns_sql(self, expression: exp.Schema) -> str:
    2578        if expression.expressions:
    2579            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
    2580        return ""

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

    2582    def star_sql(self, expression: exp.Star) -> str:
    2583        except_ = self.expressions(expression, key="except", flat=True)
    2584        except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else ""
    2585        replace = self.expressions(expression, key="replace", flat=True)
    2586        replace = f"{self.seg('REPLACE')} ({replace})" if replace else ""
    2587        rename = self.expressions(expression, key="rename", flat=True)
    2588        rename = f"{self.seg('RENAME')} ({rename})" if rename else ""
    2589        return f"*{except_}{replace}{rename}"

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

    2591    def parameter_sql(self, expression: exp.Parameter) -> str:
    2592        this = self.sql(expression, "this")
    2593        return f"{self.PARAMETER_TOKEN}{this}"

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

    2595    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    2596        this = self.sql(expression, "this")
    2597        kind = expression.text("kind")
    2598        if kind:
    2599            kind = f"{kind}."
    2600        return f"@@{kind}{this}"

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

    2602    def placeholder_sql(self, expression: exp.Placeholder) -> str:
    2603        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

    2605    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    2606        alias = self.sql(expression, "alias")
    2607        alias = f"{sep}{alias}" if alias else ""
    2608        sample = self.sql(expression, "sample")
    2609        if self.dialect.ALIAS_POST_TABLESAMPLE and sample:
    2610            alias = f"{sample}{alias}"
    2611
    2612            # Set to None so it's not generated again by self.query_modifiers()
    2613            expression.set("sample", None)
    2614
    2615        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    2616        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    2617        return self.prepend_ctes(expression, sql)

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

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

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

    2623    def unnest_sql(self, expression: exp.Unnest) -> str:
    2624        args = self.expressions(expression, flat=True)
    2625
    2626        alias = expression.args.get("alias")
    2627        offset = expression.args.get("offset")
    2628
    2629        if self.UNNEST_WITH_ORDINALITY:
    2630            if alias and isinstance(offset, exp.Expression):
    2631                alias.append("columns", offset)
    2632
    2633        if alias and self.dialect.UNNEST_COLUMN_ONLY:
    2634            columns = alias.columns
    2635            alias = self.sql(columns[0]) if columns else ""
    2636        else:
    2637            alias = self.sql(alias)
    2638
    2639        alias = f" AS {alias}" if alias else alias
    2640        if self.UNNEST_WITH_ORDINALITY:
    2641            suffix = f" WITH ORDINALITY{alias}" if offset else alias
    2642        else:
    2643            if isinstance(offset, exp.Expression):
    2644                suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}"
    2645            elif offset:
    2646                suffix = f"{alias} WITH OFFSET"
    2647            else:
    2648                suffix = alias
    2649
    2650        return f"UNNEST({args}){suffix}"

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

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

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

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

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

    2659    def window_sql(self, expression: exp.Window) -> str:
    2660        this = self.sql(expression, "this")
    2661        partition = self.partition_by_sql(expression)
    2662        order = expression.args.get("order")
    2663        order = self.order_sql(order, flat=True) if order else ""
    2664        spec = self.sql(expression, "spec")
    2665        alias = self.sql(expression, "alias")
    2666        over = self.sql(expression, "over") or "OVER"
    2667
    2668        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    2669
    2670        first = expression.args.get("first")
    2671        if first is None:
    2672            first = ""
    2673        else:
    2674            first = "FIRST" if first else "LAST"
    2675
    2676        if not partition and not order and not spec and alias:
    2677            return f"{this} {alias}"
    2678
    2679        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
    2680        return f"{this} ({args})"

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

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

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

    2686    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    2687        kind = self.sql(expression, "kind")
    2688        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    2689        end = (
    2690            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    2691            or "CURRENT ROW"
    2692        )
    2693        return f"{kind} BETWEEN {start} AND {end}"

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

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

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

    2700    def between_sql(self, expression: exp.Between) -> str:
    2701        this = self.sql(expression, "this")
    2702        low = self.sql(expression, "low")
    2703        high = self.sql(expression, "high")
    2704        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

    2706    def bracket_offset_expressions(
    2707        self, expression: exp.Bracket, index_offset: t.Optional[int] = None
    2708    ) -> t.List[exp.Expression]:
    2709        return apply_index_offset(
    2710            expression.this,
    2711            expression.expressions,
    2712            (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0),
    2713        )

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

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

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

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

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

    2723    def any_sql(self, expression: exp.Any) -> str:
    2724        this = self.sql(expression, "this")
    2725        if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)):
    2726            if isinstance(expression.this, exp.UNWRAPPED_QUERIES):
    2727                this = self.wrap(this)
    2728            return f"ANY{this}"
    2729        return f"ANY {this}"

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

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

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

    2734    def case_sql(self, expression: exp.Case) -> str:
    2735        this = self.sql(expression, "this")
    2736        statements = [f"CASE {this}" if this else "CASE"]
    2737
    2738        for e in expression.args["ifs"]:
    2739            statements.append(f"WHEN {self.sql(e, 'this')}")
    2740            statements.append(f"THEN {self.sql(e, 'true')}")
    2741
    2742        default = self.sql(expression, "default")
    2743
    2744        if default:
    2745            statements.append(f"ELSE {default}")
    2746
    2747        statements.append("END")
    2748
    2749        if self.pretty and self.too_wide(statements):
    2750            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    2751
    2752        return " ".join(statements)

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

    2754    def constraint_sql(self, expression: exp.Constraint) -> str:
    2755        this = self.sql(expression, "this")
    2756        expressions = self.expressions(expression, flat=True)
    2757        return f"CONSTRAINT {this} {expressions}"

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

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

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

    2764    def extract_sql(self, expression: exp.Extract) -> str:
    2765        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
    2766        expression_sql = self.sql(expression, "expression")
    2767        return f"EXTRACT({this} FROM {expression_sql})"

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

    2769    def trim_sql(self, expression: exp.Trim) -> str:
    2770        trim_type = self.sql(expression, "position")
    2771
    2772        if trim_type == "LEADING":
    2773            func_name = "LTRIM"
    2774        elif trim_type == "TRAILING":
    2775            func_name = "RTRIM"
    2776        else:
    2777            func_name = "TRIM"
    2778
    2779        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

    2781    def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]:
    2782        args = expression.expressions
    2783        if isinstance(expression, exp.ConcatWs):
    2784            args = args[1:]  # Skip the delimiter
    2785
    2786        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    2787            args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args]
    2788
    2789        if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"):
    2790            args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args]
    2791
    2792        return args

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

    2794    def concat_sql(self, expression: exp.Concat) -> str:
    2795        expressions = self.convert_concat_args(expression)
    2796
    2797        # Some dialects don't allow a single-argument CONCAT call
    2798        if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1:
    2799            return self.sql(expressions[0])
    2800
    2801        return self.func("CONCAT", *expressions)

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

    2803    def concatws_sql(self, expression: exp.ConcatWs) -> str:
    2804        return self.func(
    2805            "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression)
    2806        )

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

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

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

    2812    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    2813        expressions = self.expressions(expression, flat=True)
    2814        reference = self.sql(expression, "reference")
    2815        reference = f" {reference}" if reference else ""
    2816        delete = self.sql(expression, "delete")
    2817        delete = f" ON DELETE {delete}" if delete else ""
    2818        update = self.sql(expression, "update")
    2819        update = f" ON UPDATE {update}" if update else ""
    2820        return f"FOREIGN KEY ({expressions}){reference}{delete}{update}"

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

    2822    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    2823        expressions = self.expressions(expression, flat=True)
    2824        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2825        options = f" {options}" if options else ""
    2826        return f"PRIMARY KEY ({expressions}){options}"

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

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

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

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

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

    2836    def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str:
    2837        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

    2839    def jsonpath_sql(self, expression: exp.JSONPath) -> str:
    2840        path = self.expressions(expression, sep="", flat=True).lstrip(".")
    2841
    2842        if expression.args.get("escape"):
    2843            path = self.escape_str(path)
    2844
    2845        if self.QUOTE_JSON_PATH:
    2846            path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"
    2847
    2848        return path

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

    2850    def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str:
    2851        if isinstance(expression, exp.JSONPathPart):
    2852            transform = self.TRANSFORMS.get(expression.__class__)
    2853            if not callable(transform):
    2854                self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}")
    2855                return ""
    2856
    2857            return transform(self, expression)
    2858
    2859        if isinstance(expression, int):
    2860            return str(expression)
    2861
    2862        if self.JSON_PATH_SINGLE_QUOTE_ESCAPE:
    2863            escaped = expression.replace("'", "\\'")
    2864            escaped = f"\\'{expression}\\'"
    2865        else:
    2866            escaped = expression.replace('"', '\\"')
    2867            escaped = f'"{escaped}"'
    2868
    2869        return escaped

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

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

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

    2874    def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str:
    2875        null_handling = expression.args.get("null_handling")
    2876        null_handling = f" {null_handling}" if null_handling else ""
    2877
    2878        unique_keys = expression.args.get("unique_keys")
    2879        if unique_keys is not None:
    2880            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    2881        else:
    2882            unique_keys = ""
    2883
    2884        return_type = self.sql(expression, "return_type")
    2885        return_type = f" RETURNING {return_type}" if return_type else ""
    2886        encoding = self.sql(expression, "encoding")
    2887        encoding = f" ENCODING {encoding}" if encoding else ""
    2888
    2889        return self.func(
    2890            "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG",
    2891            *expression.expressions,
    2892            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
    2893        )

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

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

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

    2898    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
    2899        null_handling = expression.args.get("null_handling")
    2900        null_handling = f" {null_handling}" if null_handling else ""
    2901        return_type = self.sql(expression, "return_type")
    2902        return_type = f" RETURNING {return_type}" if return_type else ""
    2903        strict = " STRICT" if expression.args.get("strict") else ""
    2904        return self.func(
    2905            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
    2906        )

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

    2908    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
    2909        this = self.sql(expression, "this")
    2910        order = self.sql(expression, "order")
    2911        null_handling = expression.args.get("null_handling")
    2912        null_handling = f" {null_handling}" if null_handling else ""
    2913        return_type = self.sql(expression, "return_type")
    2914        return_type = f" RETURNING {return_type}" if return_type else ""
    2915        strict = " STRICT" if expression.args.get("strict") else ""
    2916        return self.func(
    2917            "JSON_ARRAYAGG",
    2918            this,
    2919            suffix=f"{order}{null_handling}{return_type}{strict})",
    2920        )

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

    2922    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
    2923        path = self.sql(expression, "path")
    2924        path = f" PATH {path}" if path else ""
    2925        nested_schema = self.sql(expression, "nested_schema")
    2926
    2927        if nested_schema:
    2928            return f"NESTED{path} {nested_schema}"
    2929
    2930        this = self.sql(expression, "this")
    2931        kind = self.sql(expression, "kind")
    2932        kind = f" {kind}" if kind else ""
    2933        return f"{this}{kind}{path}"

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

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

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

    2938    def jsontable_sql(self, expression: exp.JSONTable) -> str:
    2939        this = self.sql(expression, "this")
    2940        path = self.sql(expression, "path")
    2941        path = f", {path}" if path else ""
    2942        error_handling = expression.args.get("error_handling")
    2943        error_handling = f" {error_handling}" if error_handling else ""
    2944        empty_handling = expression.args.get("empty_handling")
    2945        empty_handling = f" {empty_handling}" if empty_handling else ""
    2946        schema = self.sql(expression, "schema")
    2947        return self.func(
    2948            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
    2949        )

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

    2951    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    2952        this = self.sql(expression, "this")
    2953        kind = self.sql(expression, "kind")
    2954        path = self.sql(expression, "path")
    2955        path = f" {path}" if path else ""
    2956        as_json = " AS JSON" if expression.args.get("as_json") else ""
    2957        return f"{this} {kind}{path}{as_json}"

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

    2959    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    2960        this = self.sql(expression, "this")
    2961        path = self.sql(expression, "path")
    2962        path = f", {path}" if path else ""
    2963        expressions = self.expressions(expression)
    2964        with_ = (
    2965            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    2966            if expressions
    2967            else ""
    2968        )
    2969        return f"OPENJSON({this}{path}){with_}"

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

    2971    def in_sql(self, expression: exp.In) -> str:
    2972        query = expression.args.get("query")
    2973        unnest = expression.args.get("unnest")
    2974        field = expression.args.get("field")
    2975        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    2976
    2977        if query:
    2978            in_sql = self.sql(query)
    2979        elif unnest:
    2980            in_sql = self.in_unnest_op(unnest)
    2981        elif field:
    2982            in_sql = self.sql(field)
    2983        else:
    2984            in_sql = f"({self.expressions(expression, flat=True)})"
    2985
    2986        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"

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

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

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

    2991    def interval_sql(self, expression: exp.Interval) -> str:
    2992        unit = self.sql(expression, "unit")
    2993        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    2994            unit = self.TIME_PART_SINGULARS.get(unit, unit)
    2995        unit = f" {unit}" if unit else ""
    2996
    2997        if self.SINGLE_STRING_INTERVAL:
    2998            this = expression.this.name if expression.this else ""
    2999            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    3000
    3001        this = self.sql(expression, "this")
    3002        if this:
    3003            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    3004            this = f" {this}" if unwrapped else f" ({this})"
    3005
    3006        return f"INTERVAL{this}{unit}"

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

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

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

    3011    def reference_sql(self, expression: exp.Reference) -> str:
    3012        this = self.sql(expression, "this")
    3013        expressions = self.expressions(expression, flat=True)
    3014        expressions = f"({expressions})" if expressions else ""
    3015        options = self.expressions(expression, key="options", flat=True, sep=" ")
    3016        options = f" {options}" if options else ""
    3017        return f"REFERENCES {this}{expressions}{options}"

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

    3019    def anonymous_sql(self, expression: exp.Anonymous) -> str:
    3020        # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive
    3021        parent = expression.parent
    3022        is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression
    3023        return self.func(
    3024            self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified
    3025        )

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

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

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

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

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

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

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

    3040    def alias_sql(self, expression: exp.Alias) -> str:
    3041        alias = self.sql(expression, "alias")
    3042        alias = f" AS {alias}" if alias else ""
    3043        return f"{self.sql(expression, 'this')}{alias}"

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

    3045    def pivotalias_sql(self, expression: exp.PivotAlias) -> str:
    3046        alias = expression.args["alias"]
    3047
    3048        identifier_alias = isinstance(alias, exp.Identifier)
    3049        literal_alias = isinstance(alias, exp.Literal)
    3050
    3051        if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    3052            alias.replace(exp.Literal.string(alias.output_name))
    3053        elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    3054            alias.replace(exp.to_identifier(alias.output_name))
    3055
    3056        return self.alias_sql(expression)

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

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

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

    3061    def atindex_sql(self, expression: exp.AtTimeZone) -> str:
    3062        this = self.sql(expression, "this")
    3063        index = self.sql(expression, "expression")
    3064        return f"{this} AT {index}"

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

    3066    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    3067        this = self.sql(expression, "this")
    3068        zone = self.sql(expression, "zone")
    3069        return f"{this} AT TIME ZONE {zone}"

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

    3071    def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str:
    3072        this = self.sql(expression, "this")
    3073        zone = self.sql(expression, "zone")
    3074        return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'"

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

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

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

    3079    def and_sql(
    3080        self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None
    3081    ) -> str:
    3082        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

    3084    def or_sql(
    3085        self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None
    3086    ) -> str:
    3087        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

    3089    def xor_sql(
    3090        self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None
    3091    ) -> str:
    3092        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

    3094    def connector_sql(
    3095        self,
    3096        expression: exp.Connector,
    3097        op: str,
    3098        stack: t.Optional[t.List[str | exp.Expression]] = None,
    3099    ) -> str:
    3100        if stack is not None:
    3101            if expression.expressions:
    3102                stack.append(self.expressions(expression, sep=f" {op} "))
    3103            else:
    3104                stack.append(expression.right)
    3105                if expression.comments and self.comments:
    3106                    for comment in expression.comments:
    3107                        if comment:
    3108                            op += f" /*{self.pad_comment(comment)}*/"
    3109                stack.extend((op, expression.left))
    3110            return op
    3111
    3112        stack = [expression]
    3113        sqls: t.List[str] = []
    3114        ops = set()
    3115
    3116        while stack:
    3117            node = stack.pop()
    3118            if isinstance(node, exp.Connector):
    3119                ops.add(getattr(self, f"{node.key}_sql")(node, stack))
    3120            else:
    3121                sql = self.sql(node)
    3122                if sqls and sqls[-1] in ops:
    3123                    sqls[-1] += f" {sql}"
    3124                else:
    3125                    sqls.append(sql)
    3126
    3127        sep = "\n" if self.pretty and self.too_wide(sqls) else " "
    3128        return sep.join(sqls)

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

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

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

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

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

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

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

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

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

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

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

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

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

    3148    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    3149        format_sql = self.sql(expression, "format")
    3150        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    3151        to_sql = self.sql(expression, "to")
    3152        to_sql = f" {to_sql}" if to_sql else ""
    3153        action = self.sql(expression, "action")
    3154        action = f" {action}" if action else ""
    3155        return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{format_sql}{action})"

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

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

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

    3161    def collate_sql(self, expression: exp.Collate) -> str:
    3162        if self.COLLATE_IS_FUNC:
    3163            return self.function_fallback_sql(expression)
    3164        return self.binary(expression, "COLLATE")

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

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

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

    3169    def comment_sql(self, expression: exp.Comment) -> str:
    3170        this = self.sql(expression, "this")
    3171        kind = expression.args["kind"]
    3172        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    3173        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    3174        expression_sql = self.sql(expression, "expression")
    3175        return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"

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

    3177    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    3178        this = self.sql(expression, "this")
    3179        delete = " DELETE" if expression.args.get("delete") else ""
    3180        recompress = self.sql(expression, "recompress")
    3181        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    3182        to_disk = self.sql(expression, "to_disk")
    3183        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    3184        to_volume = self.sql(expression, "to_volume")
    3185        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    3186        return f"{this}{delete}{recompress}{to_disk}{to_volume}"

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

    3188    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    3189        where = self.sql(expression, "where")
    3190        group = self.sql(expression, "group")
    3191        aggregates = self.expressions(expression, key="aggregates")
    3192        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    3193
    3194        if not (where or group or aggregates) and len(expression.expressions) == 1:
    3195            return f"TTL {self.expressions(expression, flat=True)}"
    3196
    3197        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"

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

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

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

    3202    def commit_sql(self, expression: exp.Commit) -> str:
    3203        chain = expression.args.get("chain")
    3204        if chain is not None:
    3205            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    3206
    3207        return f"COMMIT{chain or ''}"

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

    3209    def rollback_sql(self, expression: exp.Rollback) -> str:
    3210        savepoint = expression.args.get("savepoint")
    3211        savepoint = f" TO {savepoint}" if savepoint else ""
    3212        return f"ROLLBACK{savepoint}"

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

    3214    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    3215        this = self.sql(expression, "this")
    3216
    3217        dtype = self.sql(expression, "dtype")
    3218        if dtype:
    3219            collate = self.sql(expression, "collate")
    3220            collate = f" COLLATE {collate}" if collate else ""
    3221            using = self.sql(expression, "using")
    3222            using = f" USING {using}" if using else ""
    3223            return f"ALTER COLUMN {this} SET DATA TYPE {dtype}{collate}{using}"
    3224
    3225        default = self.sql(expression, "default")
    3226        if default:
    3227            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    3228
    3229        comment = self.sql(expression, "comment")
    3230        if comment:
    3231            return f"ALTER COLUMN {this} COMMENT {comment}"
    3232
    3233        allow_null = expression.args.get("allow_null")
    3234        drop = expression.args.get("drop")
    3235
    3236        if not drop and not allow_null:
    3237            self.unsupported("Unsupported ALTER COLUMN syntax")
    3238
    3239        if allow_null is not None:
    3240            keyword = "DROP" if drop else "SET"
    3241            return f"ALTER COLUMN {this} {keyword} NOT NULL"
    3242
    3243        return f"ALTER COLUMN {this} DROP DEFAULT"

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

    3245    def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str:
    3246        this = self.sql(expression, "this")
    3247        if not isinstance(expression.this, exp.Var):
    3248            this = f"KEY DISTKEY {this}"
    3249        return f"ALTER DISTSTYLE {this}"

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

    3251    def altersortkey_sql(self, expression: exp.AlterSortKey) -> str:
    3252        compound = " COMPOUND" if expression.args.get("compound") else ""
    3253        this = self.sql(expression, "this")
    3254        expressions = self.expressions(expression, flat=True)
    3255        expressions = f"({expressions})" if expressions else ""
    3256        return f"ALTER{compound} SORTKEY {this or expressions}"

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

    3258    def alterrename_sql(self, expression: exp.AlterRename) -> str:
    3259        if not self.RENAME_TABLE_WITH_DB:
    3260            # Remove db from tables
    3261            expression = expression.transform(
    3262                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    3263            ).assert_is(exp.AlterRename)
    3264        this = self.sql(expression, "this")
    3265        return f"RENAME TO {this}"

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

    3267    def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
    3268        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3269        old_column = self.sql(expression, "this")
    3270        new_column = self.sql(expression, "to")
    3271        return f"RENAME COLUMN{exists} {old_column} TO {new_column}"

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

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

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

    3277    def alter_sql(self, expression: exp.Alter) -> str:
    3278        actions = expression.args["actions"]
    3279
    3280        if isinstance(actions[0], exp.ColumnDef):
    3281            actions = self.add_column_sql(expression)
    3282        elif isinstance(actions[0], exp.Schema):
    3283            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    3284        elif isinstance(actions[0], exp.Delete):
    3285            actions = self.expressions(expression, key="actions", flat=True)
    3286        elif isinstance(actions[0], exp.Query):
    3287            actions = "AS " + self.expressions(expression, key="actions")
    3288        else:
    3289            actions = self.expressions(expression, key="actions", flat=True)
    3290
    3291        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3292        on_cluster = self.sql(expression, "cluster")
    3293        on_cluster = f" {on_cluster}" if on_cluster else ""
    3294        only = " ONLY" if expression.args.get("only") else ""
    3295        options = self.expressions(expression, key="options")
    3296        options = f", {options}" if options else ""
    3297        kind = self.sql(expression, "kind")
    3298        not_valid = " NOT VALID" if expression.args.get("not_valid") else ""
    3299
    3300        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

    3302    def add_column_sql(self, expression: exp.Alter) -> str:
    3303        if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD:
    3304            return self.expressions(
    3305                expression,
    3306                key="actions",
    3307                prefix="ADD COLUMN ",
    3308                skip_first=True,
    3309            )
    3310        return f"ADD {self.expressions(expression, key='actions', flat=True)}"

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

    3312    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    3313        expressions = self.expressions(expression)
    3314        exists = " IF EXISTS " if expression.args.get("exists") else " "
    3315        return f"DROP{exists}{expressions}"

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

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

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

    3320    def distinct_sql(self, expression: exp.Distinct) -> str:
    3321        this = self.expressions(expression, flat=True)
    3322
    3323        if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1:
    3324            case = exp.case()
    3325            for arg in expression.expressions:
    3326                case = case.when(arg.is_(exp.null()), exp.null())
    3327            this = self.sql(case.else_(f"({this})"))
    3328
    3329        this = f" {this}" if this else ""
    3330
    3331        on = self.sql(expression, "on")
    3332        on = f" ON {on}" if on else ""
    3333        return f"DISTINCT{this}{on}"

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

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

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

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

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

    3341    def havingmax_sql(self, expression: exp.HavingMax) -> str:
    3342        this_sql = self.sql(expression, "this")
    3343        expression_sql = self.sql(expression, "expression")
    3344        kind = "MAX" if expression.args.get("max") else "MIN"
    3345        return f"{this_sql} HAVING {kind} {expression_sql}"

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

    3347    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    3348        return self.sql(
    3349            exp.Cast(
    3350                this=exp.Div(this=expression.this, expression=expression.expression),
    3351                to=exp.DataType(this=exp.DataType.Type.INT),
    3352            )
    3353        )

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

    3355    def dpipe_sql(self, expression: exp.DPipe) -> str:
    3356        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    3357            return self.func(
    3358                "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten())
    3359            )
    3360        return self.binary(expression, "||")

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

    3362    def div_sql(self, expression: exp.Div) -> str:
    3363        l, r = expression.left, expression.right
    3364
    3365        if not self.dialect.SAFE_DIVISION and expression.args.get("safe"):
    3366            r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0)))
    3367
    3368        if self.dialect.TYPED_DIVISION and not expression.args.get("typed"):
    3369            if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES):
    3370                l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE))
    3371
    3372        elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"):
    3373            if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES):
    3374                return self.sql(
    3375                    exp.cast(
    3376                        l / r,
    3377                        to=exp.DataType.Type.BIGINT,
    3378                    )
    3379                )
    3380
    3381        return self.binary(expression, "/")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3416    def is_sql(self, expression: exp.Is) -> str:
    3417        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    3418            return self.sql(
    3419                expression.this if expression.expression.this else exp.not_(expression.this)
    3420            )
    3421        return self.binary(expression, "IS")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3462    def try_sql(self, expression: exp.Try) -> str:
    3463        if not self.TRY_SUPPORTED:
    3464            self.unsupported("Unsupported TRY function")
    3465            return self.sql(expression, "this")
    3466
    3467        return self.func("TRY", expression.this)

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

    3469    def log_sql(self, expression: exp.Log) -> str:
    3470        this = expression.this
    3471        expr = expression.expression
    3472
    3473        if self.dialect.LOG_BASE_FIRST is False:
    3474            this, expr = expr, this
    3475        elif self.dialect.LOG_BASE_FIRST is None and expr:
    3476            if this.name in ("2", "10"):
    3477                return self.func(f"LOG{this.name}", expr)
    3478
    3479            self.unsupported(f"Unsupported logarithm with base {self.sql(this)}")
    3480
    3481        return self.func("LOG", this, expr)

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

    3483    def use_sql(self, expression: exp.Use) -> str:
    3484        kind = self.sql(expression, "kind")
    3485        kind = f" {kind}" if kind else ""
    3486        this = self.sql(expression, "this")
    3487        this = f" {this}" if this else ""
    3488        return f"USE{kind}{this}"

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

    3490    def binary(self, expression: exp.Binary, op: str) -> str:
    3491        sqls: t.List[str] = []
    3492        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    3493        binary_type = type(expression)
    3494
    3495        while stack:
    3496            node = stack.pop()
    3497
    3498            if type(node) is binary_type:
    3499                op_func = node.args.get("operator")
    3500                if op_func:
    3501                    op = f"OPERATOR({self.sql(op_func)})"
    3502
    3503                stack.append(node.right)
    3504                stack.append(f" {self.maybe_comment(op, comments=node.comments)} ")
    3505                stack.append(node.left)
    3506            else:
    3507                sqls.append(self.sql(node))
    3508
    3509        return "".join(sqls)

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

    3511    def function_fallback_sql(self, expression: exp.Func) -> str:
    3512        args = []
    3513
    3514        for key in expression.arg_types:
    3515            arg_value = expression.args.get(key)
    3516
    3517            if isinstance(arg_value, list):
    3518                for value in arg_value:
    3519                    args.append(value)
    3520            elif arg_value is not None:
    3521                args.append(arg_value)
    3522
    3523        if self.normalize_functions:
    3524            name = expression.sql_name()
    3525        else:
    3526            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
    3527
    3528        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

    3530    def func(
    3531        self,
    3532        name: str,
    3533        *args: t.Optional[exp.Expression | str],
    3534        prefix: str = "(",
    3535        suffix: str = ")",
    3536        normalize: bool = True,
    3537    ) -> str:
    3538        name = self.normalize_func(name) if normalize else name
    3539        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

    3541    def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str:
    3542        arg_sqls = tuple(
    3543            self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool)
    3544        )
    3545        if self.pretty and self.too_wide(arg_sqls):
    3546            return self.indent(
    3547                "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True
    3548            )
    3549        return sep.join(arg_sqls)

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

    3551    def too_wide(self, args: t.Iterable) -> bool:
    3552        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

    3554    def format_time(
    3555        self,
    3556        expression: exp.Expression,
    3557        inverse_time_mapping: t.Optional[t.Dict[str, str]] = None,
    3558        inverse_time_trie: t.Optional[t.Dict] = None,
    3559    ) -> t.Optional[str]:
    3560        return format_time(
    3561            self.sql(expression, "format"),
    3562            inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING,
    3563            inverse_time_trie or self.dialect.INVERSE_TIME_TRIE,
    3564        )

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

    3566    def expressions(
    3567        self,
    3568        expression: t.Optional[exp.Expression] = None,
    3569        key: t.Optional[str] = None,
    3570        sqls: t.Optional[t.Collection[str | exp.Expression]] = None,
    3571        flat: bool = False,
    3572        indent: bool = True,
    3573        skip_first: bool = False,
    3574        skip_last: bool = False,
    3575        sep: str = ", ",
    3576        prefix: str = "",
    3577        dynamic: bool = False,
    3578        new_line: bool = False,
    3579    ) -> str:
    3580        expressions = expression.args.get(key or "expressions") if expression else sqls
    3581
    3582        if not expressions:
    3583            return ""
    3584
    3585        if flat:
    3586            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
    3587
    3588        num_sqls = len(expressions)
    3589        result_sqls = []
    3590
    3591        for i, e in enumerate(expressions):
    3592            sql = self.sql(e, comment=False)
    3593            if not sql:
    3594                continue
    3595
    3596            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    3597
    3598            if self.pretty:
    3599                if self.leading_comma:
    3600                    result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}")
    3601                else:
    3602                    result_sqls.append(
    3603                        f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}"
    3604                    )
    3605            else:
    3606                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    3607
    3608        if self.pretty and (not dynamic or self.too_wide(result_sqls)):
    3609            if new_line:
    3610                result_sqls.insert(0, "")
    3611                result_sqls.append("")
    3612            result_sql = "\n".join(s.rstrip() for s in result_sqls)
    3613        else:
    3614            result_sql = "".join(result_sqls)
    3615
    3616        return (
    3617            self.indent(result_sql, skip_first=skip_first, skip_last=skip_last)
    3618            if indent
    3619            else result_sql
    3620        )

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

    3622    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    3623        flat = flat or isinstance(expression.parent, exp.Properties)
    3624        expressions_sql = self.expressions(expression, flat=flat)
    3625        if flat:
    3626            return f"{op} {expressions_sql}"
    3627        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"

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

    3629    def naked_property(self, expression: exp.Property) -> str:
    3630        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    3631        if not property_name:
    3632            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    3633        return f"{property_name} {self.sql(expression, 'this')}"

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

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

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

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

    3641    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    3642        this = self.sql(expression, "this")
    3643        expressions = self.no_identify(self.expressions, expression)
    3644        expressions = (
    3645            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    3646        )
    3647        return f"{this}{expressions}" if expressions.strip() != "" else this

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

    3649    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    3650        this = self.sql(expression, "this")
    3651        expressions = self.expressions(expression, flat=True)
    3652        return f"{this}({expressions})"

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

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

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

    3657    def when_sql(self, expression: exp.When) -> str:
    3658        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    3659        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    3660        condition = self.sql(expression, "condition")
    3661        condition = f" AND {condition}" if condition else ""
    3662
    3663        then_expression = expression.args.get("then")
    3664        if isinstance(then_expression, exp.Insert):
    3665            this = self.sql(then_expression, "this")
    3666            this = f"INSERT {this}" if this else "INSERT"
    3667            then = self.sql(then_expression, "expression")
    3668            then = f"{this} VALUES {then}" if then else this
    3669        elif isinstance(then_expression, exp.Update):
    3670            if isinstance(then_expression.args.get("expressions"), exp.Star):
    3671                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    3672            else:
    3673                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    3674        else:
    3675            then = self.sql(then_expression)
    3676        return f"WHEN {matched}{source}{condition} THEN {then}"

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

    3678    def merge_sql(self, expression: exp.Merge) -> str:
    3679        table = expression.this
    3680        table_alias = ""
    3681
    3682        hints = table.args.get("hints")
    3683        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
    3684            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
    3685            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
    3686
    3687        this = self.sql(table)
    3688        using = f"USING {self.sql(expression, 'using')}"
    3689        on = f"ON {self.sql(expression, 'on')}"
    3690        expressions = self.expressions(expression, sep=" ", indent=False)
    3691        returning = self.sql(expression, "returning")
    3692        if returning:
    3693            expressions = f"{expressions}{returning}"
    3694
    3695        sep = self.sep()
    3696
    3697        return self.prepend_ctes(
    3698            expression,
    3699            f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{expressions}",
    3700        )

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

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

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

    3706    def tonumber_sql(self, expression: exp.ToNumber) -> str:
    3707        if not self.SUPPORTS_TO_NUMBER:
    3708            self.unsupported("Unsupported TO_NUMBER function")
    3709            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3710
    3711        fmt = expression.args.get("format")
    3712        if not fmt:
    3713            self.unsupported("Conversion format is required for TO_NUMBER")
    3714            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3715
    3716        return self.func("TO_NUMBER", expression.this, fmt)

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

    3718    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    3719        this = self.sql(expression, "this")
    3720        kind = self.sql(expression, "kind")
    3721        settings_sql = self.expressions(expression, key="settings", sep=" ")
    3722        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    3723        return f"{this}({kind}{args})"

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

    3725    def dictrange_sql(self, expression: exp.DictRange) -> str:
    3726        this = self.sql(expression, "this")
    3727        max = self.sql(expression, "max")
    3728        min = self.sql(expression, "min")
    3729        return f"{this}(MIN {min} MAX {max})"

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

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

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

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

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

    3738    def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str:
    3739        expressions = self.expressions(expression, flat=True)
    3740        expressions = f" {self.wrap(expressions)}" if expressions else ""
    3741        buckets = self.sql(expression, "buckets")
    3742        kind = self.sql(expression, "kind")
    3743        buckets = f" BUCKETS {buckets}" if buckets else ""
    3744        order = self.sql(expression, "order")
    3745        return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}"

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

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

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

    3750    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    3751        expressions = self.expressions(expression, key="expressions", flat=True)
    3752        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    3753        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    3754        buckets = self.sql(expression, "buckets")
    3755        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"

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

    3757    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    3758        this = self.sql(expression, "this")
    3759        having = self.sql(expression, "having")
    3760
    3761        if having:
    3762            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    3763
    3764        return self.func("ANY_VALUE", this)

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

    3766    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
    3767        transform = self.func("TRANSFORM", *expression.expressions)
    3768        row_format_before = self.sql(expression, "row_format_before")
    3769        row_format_before = f" {row_format_before}" if row_format_before else ""
    3770        record_writer = self.sql(expression, "record_writer")
    3771        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
    3772        using = f" USING {self.sql(expression, 'command_script')}"
    3773        schema = self.sql(expression, "schema")
    3774        schema = f" AS {schema}" if schema else ""
    3775        row_format_after = self.sql(expression, "row_format_after")
    3776        row_format_after = f" {row_format_after}" if row_format_after else ""
    3777        record_reader = self.sql(expression, "record_reader")
    3778        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
    3779        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

    3781    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
    3782        key_block_size = self.sql(expression, "key_block_size")
    3783        if key_block_size:
    3784            return f"KEY_BLOCK_SIZE = {key_block_size}"
    3785
    3786        using = self.sql(expression, "using")
    3787        if using:
    3788            return f"USING {using}"
    3789
    3790        parser = self.sql(expression, "parser")
    3791        if parser:
    3792            return f"WITH PARSER {parser}"
    3793
    3794        comment = self.sql(expression, "comment")
    3795        if comment:
    3796            return f"COMMENT {comment}"
    3797
    3798        visible = expression.args.get("visible")
    3799        if visible is not None:
    3800            return "VISIBLE" if visible else "INVISIBLE"
    3801
    3802        engine_attr = self.sql(expression, "engine_attr")
    3803        if engine_attr:
    3804            return f"ENGINE_ATTRIBUTE = {engine_attr}"
    3805
    3806        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
    3807        if secondary_engine_attr:
    3808            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
    3809
    3810        self.unsupported("Unsupported index constraint option.")
    3811        return ""

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

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

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

    3817    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
    3818        kind = self.sql(expression, "kind")
    3819        kind = f"{kind} INDEX" if kind else "INDEX"
    3820        this = self.sql(expression, "this")
    3821        this = f" {this}" if this else ""
    3822        index_type = self.sql(expression, "index_type")
    3823        index_type = f" USING {index_type}" if index_type else ""
    3824        expressions = self.expressions(expression, flat=True)
    3825        expressions = f" ({expressions})" if expressions else ""
    3826        options = self.expressions(expression, key="options", sep=" ")
    3827        options = f" {options}" if options else ""
    3828        return f"{kind}{this}{index_type}{expressions}{options}"

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

    3830    def nvl2_sql(self, expression: exp.Nvl2) -> str:
    3831        if self.NVL2_SUPPORTED:
    3832            return self.function_fallback_sql(expression)
    3833
    3834        case = exp.Case().when(
    3835            expression.this.is_(exp.null()).not_(copy=False),
    3836            expression.args["true"],
    3837            copy=False,
    3838        )
    3839        else_cond = expression.args.get("false")
    3840        if else_cond:
    3841            case.else_(else_cond, copy=False)
    3842
    3843        return self.sql(case)

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

    3845    def comprehension_sql(self, expression: exp.Comprehension) -> str:
    3846        this = self.sql(expression, "this")
    3847        expr = self.sql(expression, "expression")
    3848        iterator = self.sql(expression, "iterator")
    3849        condition = self.sql(expression, "condition")
    3850        condition = f" IF {condition}" if condition else ""
    3851        return f"{this} FOR {expr} IN {iterator}{condition}"

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

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

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

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

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

    3859    def predict_sql(self, expression: exp.Predict) -> str:
    3860        model = self.sql(expression, "this")
    3861        model = f"MODEL {model}"
    3862        table = self.sql(expression, "expression")
    3863        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
    3864        parameters = self.sql(expression, "params_struct")
    3865        return self.func("PREDICT", model, table, parameters or None)

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

    3867    def forin_sql(self, expression: exp.ForIn) -> str:
    3868        this = self.sql(expression, "this")
    3869        expression_sql = self.sql(expression, "expression")
    3870        return f"FOR {this} DO {expression_sql}"

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

    3872    def refresh_sql(self, expression: exp.Refresh) -> str:
    3873        this = self.sql(expression, "this")
    3874        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
    3875        return f"REFRESH {table}{this}"

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

    3877    def toarray_sql(self, expression: exp.ToArray) -> str:
    3878        arg = expression.this
    3879        if not arg.type:
    3880            from sqlglot.optimizer.annotate_types import annotate_types
    3881
    3882            arg = annotate_types(arg)
    3883
    3884        if arg.is_type(exp.DataType.Type.ARRAY):
    3885            return self.sql(arg)
    3886
    3887        cond_for_null = arg.is_(exp.null())
    3888        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

    3890    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
    3891        this = expression.this
    3892        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
    3893            return self.sql(this)
    3894
    3895        return self.sql(exp.cast(this, exp.DataType.Type.TIME))

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

    3897    def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str:
    3898        this = expression.this
    3899        if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP):
    3900            return self.sql(this)
    3901
    3902        return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect))

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

    3904    def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str:
    3905        this = expression.this
    3906        if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME):
    3907            return self.sql(this)
    3908
    3909        return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect))

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

    3911    def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:
    3912        this = expression.this
    3913        time_format = self.format_time(expression)
    3914
    3915        if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT):
    3916            return self.sql(
    3917                exp.cast(
    3918                    exp.StrToTime(this=this, format=expression.args["format"]),
    3919                    exp.DataType.Type.DATE,
    3920                )
    3921            )
    3922
    3923        if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE):
    3924            return self.sql(this)
    3925
    3926        return self.sql(exp.cast(this, exp.DataType.Type.DATE))

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

    3928    def unixdate_sql(self, expression: exp.UnixDate) -> str:
    3929        return self.sql(
    3930            exp.func(
    3931                "DATEDIFF",
    3932                expression.this,
    3933                exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE),
    3934                "day",
    3935            )
    3936        )

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

    3938    def lastday_sql(self, expression: exp.LastDay) -> str:
    3939        if self.LAST_DAY_SUPPORTS_DATE_PART:
    3940            return self.function_fallback_sql(expression)
    3941
    3942        unit = expression.text("unit")
    3943        if unit and unit != "MONTH":
    3944            self.unsupported("Date parts are not supported in LAST_DAY.")
    3945
    3946        return self.func("LAST_DAY", expression.this)

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

    3948    def dateadd_sql(self, expression: exp.DateAdd) -> str:
    3949        from sqlglot.dialects.dialect import unit_to_str
    3950
    3951        return self.func(
    3952            "DATE_ADD", expression.this, expression.expression, unit_to_str(expression)
    3953        )

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

    3955    def arrayany_sql(self, expression: exp.ArrayAny) -> str:
    3956        if self.CAN_IMPLEMENT_ARRAY_ANY:
    3957            filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression)
    3958            filtered_not_empty = exp.ArraySize(this=filtered).neq(0)
    3959            original_is_empty = exp.ArraySize(this=expression.this).eq(0)
    3960            return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty)))
    3961
    3962        from sqlglot.dialects import Dialect
    3963
    3964        # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect
    3965        if self.dialect.__class__ != Dialect:
    3966            self.unsupported("ARRAY_ANY is unsupported")
    3967
    3968        return self.function_fallback_sql(expression)

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

    3970    def struct_sql(self, expression: exp.Struct) -> str:
    3971        expression.set(
    3972            "expressions",
    3973            [
    3974                exp.alias_(e.expression, e.name if e.this.is_string else e.this)
    3975                if isinstance(e, exp.PropertyEQ)
    3976                else e
    3977                for e in expression.expressions
    3978            ],
    3979        )
    3980
    3981        return self.function_fallback_sql(expression)

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

    3983    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
    3984        low = self.sql(expression, "this")
    3985        high = self.sql(expression, "expression")
    3986
    3987        return f"{low} TO {high}"

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

    3989    def truncatetable_sql(self, expression: exp.TruncateTable) -> str:
    3990        target = "DATABASE" if expression.args.get("is_database") else "TABLE"
    3991        tables = f" {self.expressions(expression)}"
    3992
    3993        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3994
    3995        on_cluster = self.sql(expression, "cluster")
    3996        on_cluster = f" {on_cluster}" if on_cluster else ""
    3997
    3998        identity = self.sql(expression, "identity")
    3999        identity = f" {identity} IDENTITY" if identity else ""
    4000
    4001        option = self.sql(expression, "option")
    4002        option = f" {option}" if option else ""
    4003
    4004        partition = self.sql(expression, "partition")
    4005        partition = f" {partition}" if partition else ""
    4006
    4007        return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"

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

    4011    def convert_sql(self, expression: exp.Convert) -> str:
    4012        to = expression.this
    4013        value = expression.expression
    4014        style = expression.args.get("style")
    4015        safe = expression.args.get("safe")
    4016        strict = expression.args.get("strict")
    4017
    4018        if not to or not value:
    4019            return ""
    4020
    4021        # Retrieve length of datatype and override to default if not specified
    4022        if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    4023            to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
    4024
    4025        transformed: t.Optional[exp.Expression] = None
    4026        cast = exp.Cast if strict else exp.TryCast
    4027
    4028        # Check whether a conversion with format (T-SQL calls this 'style') is applicable
    4029        if isinstance(style, exp.Literal) and style.is_int:
    4030            from sqlglot.dialects.tsql import TSQL
    4031
    4032            style_value = style.name
    4033            converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value)
    4034            if not converted_style:
    4035                self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}")
    4036
    4037            fmt = exp.Literal.string(converted_style)
    4038
    4039            if to.this == exp.DataType.Type.DATE:
    4040                transformed = exp.StrToDate(this=value, format=fmt)
    4041            elif to.this == exp.DataType.Type.DATETIME:
    4042                transformed = exp.StrToTime(this=value, format=fmt)
    4043            elif to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    4044                transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe)
    4045            elif to.this == exp.DataType.Type.TEXT:
    4046                transformed = exp.TimeToStr(this=value, format=fmt)
    4047
    4048        if not transformed:
    4049            transformed = cast(this=value, to=to, safe=safe)
    4050
    4051        return self.sql(transformed)

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

    4107    def copyparameter_sql(self, expression: exp.CopyParameter) -> str:
    4108        option = self.sql(expression, "this")
    4109
    4110        if expression.expressions:
    4111            upper = option.upper()
    4112
    4113            # Snowflake FILE_FORMAT options are separated by whitespace
    4114            sep = " " if upper == "FILE_FORMAT" else ", "
    4115
    4116            # Databricks copy/format options do not set their list of values with EQ
    4117            op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = "
    4118            values = self.expressions(expression, flat=True, sep=sep)
    4119            return f"{option}{op}({values})"
    4120
    4121        value = self.sql(expression, "expression")
    4122
    4123        if not value:
    4124            return option
    4125
    4126        op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " "
    4127
    4128        return f"{option}{op}{value}"

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

    4130    def credentials_sql(self, expression: exp.Credentials) -> str:
    4131        cred_expr = expression.args.get("credentials")
    4132        if isinstance(cred_expr, exp.Literal):
    4133            # Redshift case: CREDENTIALS <string>
    4134            credentials = self.sql(expression, "credentials")
    4135            credentials = f"CREDENTIALS {credentials}" if credentials else ""
    4136        else:
    4137            # Snowflake case: CREDENTIALS = (...)
    4138            credentials = self.expressions(expression, key="credentials", flat=True, sep=" ")
    4139            credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else ""
    4140
    4141        storage = self.sql(expression, "storage")
    4142        storage = f"STORAGE_INTEGRATION = {storage}" if storage else ""
    4143
    4144        encryption = self.expressions(expression, key="encryption", flat=True, sep=" ")
    4145        encryption = f" ENCRYPTION = ({encryption})" if encryption else ""
    4146
    4147        iam_role = self.sql(expression, "iam_role")
    4148        iam_role = f"IAM_ROLE {iam_role}" if iam_role else ""
    4149
    4150        region = self.sql(expression, "region")
    4151        region = f" REGION {region}" if region else ""
    4152
    4153        return f"{credentials}{storage}{encryption}{iam_role}{region}"

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

    4155    def copy_sql(self, expression: exp.Copy) -> str:
    4156        this = self.sql(expression, "this")
    4157        this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}"
    4158
    4159        credentials = self.sql(expression, "credentials")
    4160        credentials = self.seg(credentials) if credentials else ""
    4161        kind = self.seg("FROM" if expression.args.get("kind") else "TO")
    4162        files = self.expressions(expression, key="files", flat=True)
    4163
    4164        sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " "
    4165        params = self.expressions(
    4166            expression,
    4167            key="params",
    4168            sep=sep,
    4169            new_line=True,
    4170            skip_last=True,
    4171            skip_first=True,
    4172            indent=self.COPY_PARAMS_ARE_WRAPPED,
    4173        )
    4174
    4175        if params:
    4176            if self.COPY_PARAMS_ARE_WRAPPED:
    4177                params = f" WITH ({params})"
    4178            elif not self.pretty:
    4179                params = f" {params}"
    4180
    4181        return f"COPY{this}{kind} {files}{credentials}{params}"

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

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

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

    4186    def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str:
    4187        on_sql = "ON" if expression.args.get("on") else "OFF"
    4188        filter_col: t.Optional[str] = self.sql(expression, "filter_column")
    4189        filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None
    4190        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    4191        retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None
    4192
    4193        if filter_col or retention_period:
    4194            on_sql = self.func("ON", filter_col, retention_period)
    4195
    4196        return f"DATA_DELETION={on_sql}"

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

    4198    def maskingpolicycolumnconstraint_sql(
    4199        self, expression: exp.MaskingPolicyColumnConstraint
    4200    ) -> str:
    4201        this = self.sql(expression, "this")
    4202        expressions = self.expressions(expression, flat=True)
    4203        expressions = f" USING ({expressions})" if expressions else ""
    4204        return f"MASKING POLICY {this}{expressions}"

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

    4206    def gapfill_sql(self, expression: exp.GapFill) -> str:
    4207        this = self.sql(expression, "this")
    4208        this = f"TABLE {this}"
    4209        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

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

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

    4214    def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str:
    4215        this = self.sql(expression, "this")
    4216        expr = expression.expression
    4217
    4218        if isinstance(expr, exp.Func):
    4219            # T-SQL's CLR functions are case sensitive
    4220            expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})"
    4221        else:
    4222            expr = self.sql(expression, "expression")
    4223
    4224        return self.scope_resolution(expr, this)

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

    4226    def parsejson_sql(self, expression: exp.ParseJSON) -> str:
    4227        if self.PARSE_JSON_NAME is None:
    4228            return self.sql(expression.this)
    4229
    4230        return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression)

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

    4232    def rand_sql(self, expression: exp.Rand) -> str:
    4233        lower = self.sql(expression, "lower")
    4234        upper = self.sql(expression, "upper")
    4235
    4236        if lower and upper:
    4237            return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}"
    4238        return self.func("RAND", expression.this)

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

    4240    def changes_sql(self, expression: exp.Changes) -> str:
    4241        information = self.sql(expression, "information")
    4242        information = f"INFORMATION => {information}"
    4243        at_before = self.sql(expression, "at_before")
    4244        at_before = f"{self.seg('')}{at_before}" if at_before else ""
    4245        end = self.sql(expression, "end")
    4246        end = f"{self.seg('')}{end}" if end else ""
    4247
    4248        return f"CHANGES ({information}){at_before}{end}"

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

    4250    def pad_sql(self, expression: exp.Pad) -> str:
    4251        prefix = "L" if expression.args.get("is_left") else "R"
    4252
    4253        fill_pattern = self.sql(expression, "fill_pattern") or None
    4254        if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED:
    4255            fill_pattern = "' '"
    4256
    4257        return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)

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

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

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

    4263    def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str:
    4264        generate_series = exp.GenerateSeries(**expression.args)
    4265
    4266        parent = expression.parent
    4267        if isinstance(parent, (exp.Alias, exp.TableAlias)):
    4268            parent = parent.parent
    4269
    4270        if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)):
    4271            return self.sql(exp.Unnest(expressions=[generate_series]))
    4272
    4273        if isinstance(parent, exp.Select):
    4274            self.unsupported("GenerateSeries projection unnesting is not supported.")
    4275
    4276        return self.sql(generate_series)

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

    4278    def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str:
    4279        exprs = expression.expressions
    4280        if not self.ARRAY_CONCAT_IS_VAR_LEN:
    4281            rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs)
    4282        else:
    4283            rhs = self.expressions(expression)
    4284
    4285        return self.func(name, expression.this, rhs or None)

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

    4287    def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str:
    4288        if self.SUPPORTS_CONVERT_TIMEZONE:
    4289            return self.function_fallback_sql(expression)
    4290
    4291        source_tz = expression.args.get("source_tz")
    4292        target_tz = expression.args.get("target_tz")
    4293        timestamp = expression.args.get("timestamp")
    4294
    4295        if source_tz and timestamp:
    4296            timestamp = exp.AtTimeZone(
    4297                this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz
    4298            )
    4299
    4300        expr = exp.AtTimeZone(this=timestamp, zone=target_tz)
    4301
    4302        return self.sql(expr)

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

    4304    def json_sql(self, expression: exp.JSON) -> str:
    4305        this = self.sql(expression, "this")
    4306        this = f" {this}" if this else ""
    4307
    4308        _with = expression.args.get("with")
    4309
    4310        if _with is None:
    4311            with_sql = ""
    4312        elif not _with:
    4313            with_sql = " WITHOUT"
    4314        else:
    4315            with_sql = " WITH"
    4316
    4317        unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else ""
    4318
    4319        return f"JSON{this}{with_sql}{unique_sql}"

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

    4321    def jsonvalue_sql(self, expression: exp.JSONValue) -> str:
    4322        def _generate_on_options(arg: t.Any) -> str:
    4323            return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}"
    4324
    4325        path = self.sql(expression, "path")
    4326        returning = self.sql(expression, "returning")
    4327        returning = f" RETURNING {returning}" if returning else ""
    4328
    4329        on_condition = self.sql(expression, "on_condition")
    4330        on_condition = f" {on_condition}" if on_condition else ""
    4331
    4332        return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}")

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

    4334    def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str:
    4335        else_ = "ELSE " if expression.args.get("else_") else ""
    4336        condition = self.sql(expression, "expression")
    4337        condition = f"WHEN {condition} THEN " if condition else else_
    4338        insert = self.sql(expression, "this")[len("INSERT") :].strip()
    4339        return f"{condition}{insert}"

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

    4341    def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str:
    4342        kind = self.sql(expression, "kind")
    4343        expressions = self.seg(self.expressions(expression, sep=" "))
    4344        res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}"
    4345        return res

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

    4347    def oncondition_sql(self, expression: exp.OnCondition) -> str:
    4348        # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR"
    4349        empty = expression.args.get("empty")
    4350        empty = (
    4351            f"DEFAULT {empty} ON EMPTY"
    4352            if isinstance(empty, exp.Expression)
    4353            else self.sql(expression, "empty")
    4354        )
    4355
    4356        error = expression.args.get("error")
    4357        error = (
    4358            f"DEFAULT {error} ON ERROR"
    4359            if isinstance(error, exp.Expression)
    4360            else self.sql(expression, "error")
    4361        )
    4362
    4363        if error and empty:
    4364            error = (
    4365                f"{empty} {error}"
    4366                if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR
    4367                else f"{error} {empty}"
    4368            )
    4369            empty = ""
    4370
    4371        null = self.sql(expression, "null")
    4372
    4373        return f"{empty}{error}{null}"

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

    4375    def jsonexists_sql(self, expression: exp.JSONExists) -> str:
    4376        this = self.sql(expression, "this")
    4377        path = self.sql(expression, "path")
    4378
    4379        passing = self.expressions(expression, "passing")
    4380        passing = f" PASSING {passing}" if passing else ""
    4381
    4382        on_condition = self.sql(expression, "on_condition")
    4383        on_condition = f" {on_condition}" if on_condition else ""
    4384
    4385        path = f"{path}{passing}{on_condition}"
    4386
    4387        return self.func("JSON_EXISTS", this, path)

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

    4389    def arrayagg_sql(self, expression: exp.ArrayAgg) -> str:
    4390        array_agg = self.function_fallback_sql(expression)
    4391
    4392        # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls
    4393        # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB)
    4394        if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"):
    4395            parent = expression.parent
    4396            if isinstance(parent, exp.Filter):
    4397                parent_cond = parent.expression.this
    4398                parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_()))
    4399            else:
    4400                this = expression.this
    4401                # Do not add the filter if the input is not a column (e.g. literal, struct etc)
    4402                if this.find(exp.Column):
    4403                    # DISTINCT is already present in the agg function, do not propagate it to FILTER as well
    4404                    this_sql = (
    4405                        self.expressions(this)
    4406                        if isinstance(this, exp.Distinct)
    4407                        else self.sql(expression, "this")
    4408                    )
    4409
    4410                    array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)"
    4411
    4412        return array_agg

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

    4414    def apply_sql(self, expression: exp.Apply) -> str:
    4415        this = self.sql(expression, "this")
    4416        expr = self.sql(expression, "expression")
    4417
    4418        return f"{this} APPLY({expr})"

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

    4420    def grant_sql(self, expression: exp.Grant) -> str:
    4421        privileges_sql = self.expressions(expression, key="privileges", flat=True)
    4422
    4423        kind = self.sql(expression, "kind")
    4424        kind = f" {kind}" if kind else ""
    4425
    4426        securable = self.sql(expression, "securable")
    4427        securable = f" {securable}" if securable else ""
    4428
    4429        principals = self.expressions(expression, key="principals", flat=True)
    4430
    4431        grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else ""
    4432
    4433        return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}"

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

    4435    def grantprivilege_sql(self, expression: exp.GrantPrivilege):
    4436        this = self.sql(expression, "this")
    4437        columns = self.expressions(expression, flat=True)
    4438        columns = f"({columns})" if columns else ""
    4439
    4440        return f"{this}{columns}"

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

    4442    def grantprincipal_sql(self, expression: exp.GrantPrincipal):
    4443        this = self.sql(expression, "this")
    4444
    4445        kind = self.sql(expression, "kind")
    4446        kind = f"{kind} " if kind else ""
    4447
    4448        return f"{kind}{this}"

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

    4450    def columns_sql(self, expression: exp.Columns):
    4451        func = self.function_fallback_sql(expression)
    4452        if expression.args.get("unpack"):
    4453            func = f"*{func}"
    4454
    4455        return func

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

    4457    def overlay_sql(self, expression: exp.Overlay):
    4458        this = self.sql(expression, "this")
    4459        expr = self.sql(expression, "expression")
    4460        from_sql = self.sql(expression, "from")
    4461        for_sql = self.sql(expression, "for")
    4462        for_sql = f" FOR {for_sql}" if for_sql else ""
    4463
    4464        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

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

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

    4470    def string_sql(self, expression: exp.String) -> str:
    4471        this = expression.this
    4472        zone = expression.args.get("zone")
    4473
    4474        if zone:
    4475            # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>)
    4476            # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC
    4477            # set for source_tz to transpile the time conversion before the STRING cast
    4478            this = exp.ConvertTimezone(
    4479                source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this
    4480            )
    4481
    4482        return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR))

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

    4484    def median_sql(self, expression: exp.Median):
    4485        if not self.SUPPORTS_MEDIAN:
    4486            return self.sql(
    4487                exp.PercentileCont(this=expression.this, expression=exp.Literal.number(0.5))
    4488            )
    4489
    4490        return self.function_fallback_sql(expression)

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

    4492    def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str:
    4493        filler = self.sql(expression, "this")
    4494        filler = f" {filler}" if filler else ""
    4495        with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT"
    4496        return f"TRUNCATE{filler} {with_count}"

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

    4498    def unixseconds_sql(self, expression: exp.UnixSeconds) -> str:
    4499        if self.SUPPORTS_UNIX_SECONDS:
    4500            return self.function_fallback_sql(expression)
    4501
    4502        start_ts = exp.cast(
    4503            exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ
    4504        )
    4505
    4506        return self.sql(
    4507            exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS"))
    4508        )

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

    4510    def arraysize_sql(self, expression: exp.ArraySize) -> str:
    4511        dim = expression.expression
    4512
    4513        # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension)
    4514        if dim and self.ARRAY_SIZE_DIM_REQUIRED is None:
    4515            if not (dim.is_int and dim.name == "1"):
    4516                self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH")
    4517            dim = None
    4518
    4519        # If dimension is required but not specified, default initialize it
    4520        if self.ARRAY_SIZE_DIM_REQUIRED and not dim:
    4521            dim = exp.Literal.number(1)
    4522
    4523        return self.func(self.ARRAY_SIZE_NAME, expression.this, dim)