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

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

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

###### Arguments:

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

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

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

TRANSFORMS: Dict[Type[sqlglot.expressions.Expression], Callable[..., str]] = {<class 'sqlglot.expressions.JSONPathFilter'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathKey'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathRecursive'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathRoot'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathScript'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSelector'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSlice'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSubscript'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathUnion'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathWildcard'>: <function <lambda>>, <class 'sqlglot.expressions.AllowedValuesProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ArrayContainsAll'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ArrayOverlaps'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AutoRefreshProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.BackupProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CaseSpecificColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CommentColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ConnectByRoot'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DateFormatColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DefaultColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DynamicProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EmptyProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EncodeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EphemeralColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExcludeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Except'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExternalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.GlobalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.HeapProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.IcebergProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InheritsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InlineLengthColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Intersect'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.IntervalSpan'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Int64'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LanguageProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LocationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.MaterializedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NonClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NotForReplicationColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnCommitProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnUpdateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Operator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OutputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PivotAny'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ProjectionPolicyColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ReturnsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SampleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SecureProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetConfigProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SharingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlReadWriteProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StabilityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Stream'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StreamingTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StrictProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SwapTable'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TemporaryProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Tags'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Union'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UnloggedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Uuid'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VarMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ViewAttributeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithProcedureOptions'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithSchemaBindingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithOperator'>: <function Generator.<lambda>>}
NULL_ORDERING_SUPPORTED: Optional[bool] = True
IGNORE_NULLS_IN_FUNC = False
LOCKING_READS_SUPPORTED = False
EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = True
WRAP_DERIVED_VALUES = True
CREATE_FUNCTION_RETURN_AS = True
MATCHED_BY_SOURCE = True
SINGLE_STRING_INTERVAL = False
INTERVAL_ALLOWS_PLURAL_FORM = True
LIMIT_FETCH = 'ALL'
LIMIT_ONLY_LITERALS = False
RENAME_TABLE_WITH_DB = True
GROUPINGS_SEP = ','
INDEX_ON = 'ON'
JOIN_HINTS = True
TABLE_HINTS = True
QUERY_HINTS = True
QUERY_HINT_SEP = ', '
IS_BOOL_ALLOWED = True
DUPLICATE_KEY_UPDATE_WITH_SET = True
LIMIT_IS_TOP = False
RETURNING_END = True
EXTRACT_ALLOWS_QUOTES = True
TZ_TO_WITH_TIME_ZONE = False
NVL2_SUPPORTED = True
SELECT_KINDS: Tuple[str, ...] = ('STRUCT', 'VALUE')
VALUES_AS_TABLE = True
ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = True
UNNEST_WITH_ORDINALITY = True
AGGREGATE_FILTER_SUPPORTED = True
SEMI_ANTI_JOIN_WITH_SIDE = True
COMPUTED_COLUMN_WITH_TYPE = True
SUPPORTS_TABLE_COPY = True
TABLESAMPLE_REQUIRES_PARENS = True
TABLESAMPLE_SIZE_IS_ROWS = True
TABLESAMPLE_KEYWORDS = 'TABLESAMPLE'
TABLESAMPLE_WITH_METHOD = True
TABLESAMPLE_SEED_KEYWORD = 'SEED'
COLLATE_IS_FUNC = False
DATA_TYPE_SPECIFIERS_ALLOWED = False
ENSURE_BOOLS = False
CTE_RECURSIVE_KEYWORD_REQUIRED = True
SUPPORTS_SINGLE_ARG_CONCAT = True
LAST_DAY_SUPPORTS_DATE_PART = True
SUPPORTS_TABLE_ALIAS_COLUMNS = True
UNPIVOT_ALIASES_ARE_IDENTIFIERS = True
JSON_KEY_VALUE_PAIR_SEP = ':'
INSERT_OVERWRITE = ' OVERWRITE TABLE'
SUPPORTS_SELECT_INTO = False
SUPPORTS_UNLOGGED_TABLES = False
SUPPORTS_CREATE_TABLE_LIKE = True
LIKE_PROPERTY_INSIDE_SCHEMA = False
MULTI_ARG_DISTINCT = True
JSON_TYPE_REQUIRED_FOR_EXTRACTION = False
JSON_PATH_BRACKETED_KEY_SUPPORTED = True
JSON_PATH_SINGLE_QUOTE_ESCAPE = False
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 = ':'
EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: Set[str] = set()
PROPERTIES_LOCATION = {<class 'sqlglot.expressions.AllowedValuesProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.AlgorithmProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.AutoIncrementProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.AutoRefreshProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.BackupProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.BlockCompressionProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CharacterSetProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ChecksumProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CollateProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Cluster'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ClusteredByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistributedByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DuplicateKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DataBlocksizeProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.DataDeletionProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DefinerProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.DictRange'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DictProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DynamicProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.DistKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistStyleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EmptyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EncodeProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.EngineProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExternalProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.FallbackProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.FileFormatProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.FreespaceProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.GlobalProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.HeapProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.InheritsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.IcebergProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.IncludeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.InputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.IsolatedLoadingProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.JournalProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.LanguageProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LikeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LocationProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LockProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LockingProperty'>: <Location.POST_ALIAS: 'POST_ALIAS'>, <class 'sqlglot.expressions.LogProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.MaterializedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.MergeBlockRatioProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.OnProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OnCommitProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.Order'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OutputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PartitionedByProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.PartitionedOfProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PrimaryKey'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Property'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ReturnsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatDelimitedProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatSerdeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SampleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SchemaCommentProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SecureProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.SecurityProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SerdeProperties'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Set'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SettingsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SetProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.SetConfigProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SharingProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.SequenceProperties'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.SortKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlReadWriteProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StabilityProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.StreamingTableProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StrictProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Tags'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.TemporaryProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.ToTableProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TransientProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.TransformModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.MergeTreeTTL'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.UnloggedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.ViewAttributeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.VolatileProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.WithDataProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.WithProcedureOptions'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.WithSchemaBindingProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.WithSystemVersioningProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>}
RESERVED_KEYWORDS: Set[str] = set()
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.VARCHAR: 'VARCHAR'>, <Type.NVARCHAR: 'NVARCHAR'>, <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

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

    744    def preprocess(self, expression: exp.Expression) -> exp.Expression:
    745        """Apply generic preprocessing transformations to a given expression."""
    746        expression = self._move_ctes_to_top_level(expression)
    747
    748        if self.ENSURE_BOOLS:
    749            from sqlglot.transforms import ensure_bools
    750
    751            expression = ensure_bools(expression)
    752
    753        return expression

Apply generic preprocessing transformations to a given expression.

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

    766    def unsupported(self, message: str) -> None:
    767        if self.unsupported_level == ErrorLevel.IMMEDIATE:
    768            raise UnsupportedError(message)
    769        self.unsupported_messages.append(message)

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

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

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

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

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

    777    def pad_comment(self, comment: str) -> str:
    778        comment = " " + comment if comment[0].strip() else comment
    779        comment = comment + " " if comment[-1].strip() else comment
    780        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

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

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

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

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

    828    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
    829        original = self.identify
    830        self.identify = False
    831        result = func(*args, **kwargs)
    832        self.identify = original
    833        return result

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

    835    def normalize_func(self, name: str) -> str:
    836        if self.normalize_functions == "upper" or self.normalize_functions is True:
    837            return name.upper()
    838        if self.normalize_functions == "lower":
    839            return name.lower()
    840        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

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

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

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

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

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

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

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

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

    918    def characterset_sql(self, expression: exp.CharacterSet) -> str:
    919        if isinstance(expression.parent, exp.Cast):
    920            return f"CHAR CHARACTER SET {self.sql(expression, 'this')}"
    921        default = "DEFAULT " if expression.args.get("default") else ""
    922        return f"{default}CHARACTER SET={self.sql(expression, 'this')}"

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

    924    def column_parts(self, expression: exp.Column) -> str:
    925        return ".".join(
    926            self.sql(part)
    927            for part in (
    928                expression.args.get("catalog"),
    929                expression.args.get("db"),
    930                expression.args.get("table"),
    931                expression.args.get("this"),
    932            )
    933            if part
    934        )

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

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

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

    945    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
    946        this = self.sql(expression, "this")
    947        this = f" {this}" if this else ""
    948        position = self.sql(expression, "position")
    949        return f"{position}{this}"

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

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

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

    966    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
    967        this = self.sql(expression, "this")
    968        kind_sql = self.sql(expression, "kind").strip()
    969        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql

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

    971    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
    972        this = self.sql(expression, "this")
    973        if expression.args.get("not_null"):
    974            persisted = " PERSISTED NOT NULL"
    975        elif expression.args.get("persisted"):
    976            persisted = " PERSISTED"
    977        else:
    978            persisted = ""
    979        return f"AS {this}{persisted}"

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

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

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

    984    def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str:
    985        if isinstance(expression.this, list):
    986            this = self.wrap(self.expressions(expression, key="this", flat=True))
    987        else:
    988            this = self.sql(expression, "this")
    989
    990        return f"COMPRESS {this}"

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

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

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

    1025    def generatedasrowcolumnconstraint_sql(
    1026        self, expression: exp.GeneratedAsRowColumnConstraint
    1027    ) -> str:
    1028        start = "START" if expression.args.get("start") else "END"
    1029        hidden = " HIDDEN" if expression.args.get("hidden") else ""
    1030        return f"GENERATED ALWAYS AS ROW {start}{hidden}"

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

    1032    def periodforsystemtimeconstraint_sql(
    1033        self, expression: exp.PeriodForSystemTimeConstraint
    1034    ) -> str:
    1035        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

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

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

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

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

    1043    def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str:
    1044        desc = expression.args.get("desc")
    1045        if desc is not None:
    1046            return f"PRIMARY KEY{' DESC' if desc else ' ASC'}"
    1047        return "PRIMARY KEY"

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

    1049    def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str:
    1050        this = self.sql(expression, "this")
    1051        this = f" {this}" if this else ""
    1052        index_type = expression.args.get("index_type")
    1053        index_type = f" USING {index_type}" if index_type else ""
    1054        on_conflict = self.sql(expression, "on_conflict")
    1055        on_conflict = f" {on_conflict}" if on_conflict else ""
    1056        nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else ""
    1057        return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}"

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

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

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

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

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

    1171    def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str:
    1172        start = self.sql(expression, "start")
    1173        start = f"START WITH {start}" if start else ""
    1174        increment = self.sql(expression, "increment")
    1175        increment = f" INCREMENT BY {increment}" if increment else ""
    1176        minvalue = self.sql(expression, "minvalue")
    1177        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    1178        maxvalue = self.sql(expression, "maxvalue")
    1179        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    1180        owned = self.sql(expression, "owned")
    1181        owned = f" OWNED BY {owned}" if owned else ""
    1182
    1183        cache = expression.args.get("cache")
    1184        if cache is None:
    1185            cache_str = ""
    1186        elif cache is True:
    1187            cache_str = " CACHE"
    1188        else:
    1189            cache_str = f" CACHE {cache}"
    1190
    1191        options = self.expressions(expression, key="options", flat=True, sep=" ")
    1192        options = f" {options}" if options else ""
    1193
    1194        return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip()

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

    1196    def clone_sql(self, expression: exp.Clone) -> str:
    1197        this = self.sql(expression, "this")
    1198        shallow = "SHALLOW " if expression.args.get("shallow") else ""
    1199        keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE"
    1200        return f"{shallow}{keyword} {this}"

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

    1202    def describe_sql(self, expression: exp.Describe) -> str:
    1203        style = expression.args.get("style")
    1204        style = f" {style}" if style else ""
    1205        partition = self.sql(expression, "partition")
    1206        partition = f" {partition}" if partition else ""
    1207        format = self.sql(expression, "format")
    1208        format = f" {format}" if format else ""
    1209
    1210        return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}"

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

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

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

    1216    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
    1217        with_ = self.sql(expression, "with")
    1218        if with_:
    1219            sql = f"{with_}{self.sep()}{sql}"
    1220        return sql

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

    1222    def with_sql(self, expression: exp.With) -> str:
    1223        sql = self.expressions(expression, flat=True)
    1224        recursive = (
    1225            "RECURSIVE "
    1226            if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive")
    1227            else ""
    1228        )
    1229
    1230        return f"WITH {recursive}{sql}"

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

    1232    def cte_sql(self, expression: exp.CTE) -> str:
    1233        alias = expression.args.get("alias")
    1234        if alias:
    1235            alias.add_comments(expression.pop_comments())
    1236
    1237        alias_sql = self.sql(expression, "alias")
    1238
    1239        materialized = expression.args.get("materialized")
    1240        if materialized is False:
    1241            materialized = "NOT MATERIALIZED "
    1242        elif materialized:
    1243            materialized = "MATERIALIZED "
    1244
    1245        return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}"

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

    1247    def tablealias_sql(self, expression: exp.TableAlias) -> str:
    1248        alias = self.sql(expression, "this")
    1249        columns = self.expressions(expression, key="columns", flat=True)
    1250        columns = f"({columns})" if columns else ""
    1251
    1252        if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS:
    1253            columns = ""
    1254            self.unsupported("Named columns are not supported in table alias.")
    1255
    1256        if not alias and not self.dialect.UNNEST_COLUMN_ONLY:
    1257            alias = self._next_name()
    1258
    1259        return f"{alias}{columns}"

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

    1261    def bitstring_sql(self, expression: exp.BitString) -> str:
    1262        this = self.sql(expression, "this")
    1263        if self.dialect.BIT_START:
    1264            return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}"
    1265        return f"{int(this, 2)}"

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

    1267    def hexstring_sql(self, expression: exp.HexString) -> str:
    1268        this = self.sql(expression, "this")
    1269        if self.dialect.HEX_START:
    1270            return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"
    1271        return f"{int(this, 16)}"

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

    1273    def bytestring_sql(self, expression: exp.ByteString) -> str:
    1274        this = self.sql(expression, "this")
    1275        if self.dialect.BYTE_START:
    1276            return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}"
    1277        return this

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

    1279    def unicodestring_sql(self, expression: exp.UnicodeString) -> str:
    1280        this = self.sql(expression, "this")
    1281        escape = expression.args.get("escape")
    1282
    1283        if self.dialect.UNICODE_START:
    1284            escape_substitute = r"\\\1"
    1285            left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END
    1286        else:
    1287            escape_substitute = r"\\u\1"
    1288            left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END
    1289
    1290        if escape:
    1291            escape_pattern = re.compile(rf"{escape.name}(\d+)")
    1292            escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else ""
    1293        else:
    1294            escape_pattern = ESCAPED_UNICODE_RE
    1295            escape_sql = ""
    1296
    1297        if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE):
    1298            this = escape_pattern.sub(escape_substitute, this)
    1299
    1300        return f"{left_quote}{this}{right_quote}{escape_sql}"

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

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

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

    1306    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
    1307        this = self.sql(expression, "this")
    1308        specifier = self.sql(expression, "expression")
    1309        specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else ""
    1310        return f"{this}{specifier}"

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

    1312    def datatype_sql(self, expression: exp.DataType) -> str:
    1313        nested = ""
    1314        values = ""
    1315        interior = self.expressions(expression, flat=True)
    1316
    1317        type_value = expression.this
    1318        if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"):
    1319            type_sql = self.sql(expression, "kind")
    1320        else:
    1321            type_sql = (
    1322                self.TYPE_MAPPING.get(type_value, type_value.value)
    1323                if isinstance(type_value, exp.DataType.Type)
    1324                else type_value
    1325            )
    1326
    1327        if interior:
    1328            if expression.args.get("nested"):
    1329                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
    1330                if expression.args.get("values") is not None:
    1331                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
    1332                    values = self.expressions(expression, key="values", flat=True)
    1333                    values = f"{delimiters[0]}{values}{delimiters[1]}"
    1334            elif type_value == exp.DataType.Type.INTERVAL:
    1335                nested = f" {interior}"
    1336            else:
    1337                nested = f"({interior})"
    1338
    1339        type_sql = f"{type_sql}{nested}{values}"
    1340        if self.TZ_TO_WITH_TIME_ZONE and type_value in (
    1341            exp.DataType.Type.TIMETZ,
    1342            exp.DataType.Type.TIMESTAMPTZ,
    1343        ):
    1344            type_sql = f"{type_sql} WITH TIME ZONE"
    1345
    1346        return type_sql

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

    1348    def directory_sql(self, expression: exp.Directory) -> str:
    1349        local = "LOCAL " if expression.args.get("local") else ""
    1350        row_format = self.sql(expression, "row_format")
    1351        row_format = f" {row_format}" if row_format else ""
    1352        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"

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

    1354    def delete_sql(self, expression: exp.Delete) -> str:
    1355        this = self.sql(expression, "this")
    1356        this = f" FROM {this}" if this else ""
    1357        using = self.sql(expression, "using")
    1358        using = f" USING {using}" if using else ""
    1359        cluster = self.sql(expression, "cluster")
    1360        cluster = f" {cluster}" if cluster else ""
    1361        where = self.sql(expression, "where")
    1362        returning = self.sql(expression, "returning")
    1363        limit = self.sql(expression, "limit")
    1364        tables = self.expressions(expression, key="tables")
    1365        tables = f" {tables}" if tables else ""
    1366        if self.RETURNING_END:
    1367            expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}"
    1368        else:
    1369            expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}"
    1370        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")

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

    1372    def drop_sql(self, expression: exp.Drop) -> str:
    1373        this = self.sql(expression, "this")
    1374        expressions = self.expressions(expression, flat=True)
    1375        expressions = f" ({expressions})" if expressions else ""
    1376        kind = expression.args["kind"]
    1377        kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind
    1378        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    1379        concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else ""
    1380        on_cluster = self.sql(expression, "cluster")
    1381        on_cluster = f" {on_cluster}" if on_cluster else ""
    1382        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    1383        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    1384        cascade = " CASCADE" if expression.args.get("cascade") else ""
    1385        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
    1386        purge = " PURGE" if expression.args.get("purge") else ""
    1387        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

    1389    def set_operation(self, expression: exp.SetOperation) -> str:
    1390        op_type = type(expression)
    1391        op_name = op_type.key.upper()
    1392
    1393        distinct = expression.args.get("distinct")
    1394        if (
    1395            distinct is False
    1396            and op_type in (exp.Except, exp.Intersect)
    1397            and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE
    1398        ):
    1399            self.unsupported(f"{op_name} ALL is not supported")
    1400
    1401        default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type]
    1402
    1403        if distinct is None:
    1404            distinct = default_distinct
    1405            if distinct is None:
    1406                self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified")
    1407
    1408        if distinct is default_distinct:
    1409            kind = ""
    1410        else:
    1411            kind = " DISTINCT" if distinct else " ALL"
    1412
    1413        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1414        return f"{op_name}{kind}{by_name}"

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

    1416    def set_operations(self, expression: exp.SetOperation) -> str:
    1417        if not self.SET_OP_MODIFIERS:
    1418            limit = expression.args.get("limit")
    1419            order = expression.args.get("order")
    1420
    1421            if limit or order:
    1422                select = self._move_ctes_to_top_level(
    1423                    exp.subquery(expression, "_l_0", copy=False).select("*", copy=False)
    1424                )
    1425
    1426                if limit:
    1427                    select = select.limit(limit.pop(), copy=False)
    1428                if order:
    1429                    select = select.order_by(order.pop(), copy=False)
    1430                return self.sql(select)
    1431
    1432        sqls: t.List[str] = []
    1433        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    1434
    1435        while stack:
    1436            node = stack.pop()
    1437
    1438            if isinstance(node, exp.SetOperation):
    1439                stack.append(node.expression)
    1440                stack.append(
    1441                    self.maybe_comment(
    1442                        self.set_operation(node), comments=node.comments, separated=True
    1443                    )
    1444                )
    1445                stack.append(node.this)
    1446            else:
    1447                sqls.append(self.sql(node))
    1448
    1449        this = self.sep().join(sqls)
    1450        this = self.query_modifiers(expression, this)
    1451        return self.prepend_ctes(expression, this)

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

    1453    def fetch_sql(self, expression: exp.Fetch) -> str:
    1454        direction = expression.args.get("direction")
    1455        direction = f" {direction}" if direction else ""
    1456        count = self.sql(expression, "count")
    1457        count = f" {count}" if count else ""
    1458        if expression.args.get("percent"):
    1459            count = f"{count} PERCENT"
    1460        with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY"
    1461        return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}"

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

    1463    def filter_sql(self, expression: exp.Filter) -> str:
    1464        if self.AGGREGATE_FILTER_SUPPORTED:
    1465            this = self.sql(expression, "this")
    1466            where = self.sql(expression, "expression").strip()
    1467            return f"{this} FILTER({where})"
    1468
    1469        agg = expression.this
    1470        agg_arg = agg.this
    1471        cond = expression.expression.this
    1472        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
    1473        return self.sql(agg)

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

    1475    def hint_sql(self, expression: exp.Hint) -> str:
    1476        if not self.QUERY_HINTS:
    1477            self.unsupported("Hints are not supported")
    1478            return ""
    1479
    1480        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"

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

    1482    def indexparameters_sql(self, expression: exp.IndexParameters) -> str:
    1483        using = self.sql(expression, "using")
    1484        using = f" USING {using}" if using else ""
    1485        columns = self.expressions(expression, key="columns", flat=True)
    1486        columns = f"({columns})" if columns else ""
    1487        partition_by = self.expressions(expression, key="partition_by", flat=True)
    1488        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
    1489        where = self.sql(expression, "where")
    1490        include = self.expressions(expression, key="include", flat=True)
    1491        if include:
    1492            include = f" INCLUDE ({include})"
    1493        with_storage = self.expressions(expression, key="with_storage", flat=True)
    1494        with_storage = f" WITH ({with_storage})" if with_storage else ""
    1495        tablespace = self.sql(expression, "tablespace")
    1496        tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else ""
    1497        on = self.sql(expression, "on")
    1498        on = f" ON {on}" if on else ""
    1499
    1500        return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"

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

    1502    def index_sql(self, expression: exp.Index) -> str:
    1503        unique = "UNIQUE " if expression.args.get("unique") else ""
    1504        primary = "PRIMARY " if expression.args.get("primary") else ""
    1505        amp = "AMP " if expression.args.get("amp") else ""
    1506        name = self.sql(expression, "this")
    1507        name = f"{name} " if name else ""
    1508        table = self.sql(expression, "table")
    1509        table = f"{self.INDEX_ON} {table}" if table else ""
    1510
    1511        index = "INDEX " if not table else ""
    1512
    1513        params = self.sql(expression, "params")
    1514        return f"{unique}{primary}{amp}{index}{name}{table}{params}"

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

    1516    def identifier_sql(self, expression: exp.Identifier) -> str:
    1517        text = expression.name
    1518        lower = text.lower()
    1519        text = lower if self.normalize and not expression.quoted else text
    1520        text = text.replace(self._identifier_end, self._escaped_identifier_end)
    1521        if (
    1522            expression.quoted
    1523            or self.dialect.can_identify(text, self.identify)
    1524            or lower in self.RESERVED_KEYWORDS
    1525            or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
    1526        ):
    1527            text = f"{self._identifier_start}{text}{self._identifier_end}"
    1528        return text

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

    1530    def hex_sql(self, expression: exp.Hex) -> str:
    1531        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1532        if self.dialect.HEX_LOWERCASE:
    1533            text = self.func("LOWER", text)
    1534
    1535        return text

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

    1537    def lowerhex_sql(self, expression: exp.LowerHex) -> str:
    1538        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1539        if not self.dialect.HEX_LOWERCASE:
    1540            text = self.func("LOWER", text)
    1541        return text

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

    1543    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    1544        input_format = self.sql(expression, "input_format")
    1545        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    1546        output_format = self.sql(expression, "output_format")
    1547        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    1548        return self.sep().join((input_format, output_format))

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

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

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

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

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

    1557    def properties_sql(self, expression: exp.Properties) -> str:
    1558        root_properties = []
    1559        with_properties = []
    1560
    1561        for p in expression.expressions:
    1562            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1563            if p_loc == exp.Properties.Location.POST_WITH:
    1564                with_properties.append(p)
    1565            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    1566                root_properties.append(p)
    1567
    1568        root_props = self.root_properties(exp.Properties(expressions=root_properties))
    1569        with_props = self.with_properties(exp.Properties(expressions=with_properties))
    1570
    1571        if root_props and with_props and not self.pretty:
    1572            with_props = " " + with_props
    1573
    1574        return root_props + with_props

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

    1576    def root_properties(self, properties: exp.Properties) -> str:
    1577        if properties.expressions:
    1578            return self.expressions(properties, indent=False, sep=" ")
    1579        return ""

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

    1581    def properties(
    1582        self,
    1583        properties: exp.Properties,
    1584        prefix: str = "",
    1585        sep: str = ", ",
    1586        suffix: str = "",
    1587        wrapped: bool = True,
    1588    ) -> str:
    1589        if properties.expressions:
    1590            expressions = self.expressions(properties, sep=sep, indent=False)
    1591            if expressions:
    1592                expressions = self.wrap(expressions) if wrapped else expressions
    1593                return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}"
    1594        return ""

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

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

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

    1599    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
    1600        properties_locs = defaultdict(list)
    1601        for p in properties.expressions:
    1602            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1603            if p_loc != exp.Properties.Location.UNSUPPORTED:
    1604                properties_locs[p_loc].append(p)
    1605            else:
    1606                self.unsupported(f"Unsupported property {p.key}")
    1607
    1608        return properties_locs

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

    1610    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
    1611        if isinstance(expression.this, exp.Dot):
    1612            return self.sql(expression, "this")
    1613        return f"'{expression.name}'" if string_key else expression.name

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

    1615    def property_sql(self, expression: exp.Property) -> str:
    1616        property_cls = expression.__class__
    1617        if property_cls == exp.Property:
    1618            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
    1619
    1620        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    1621        if not property_name:
    1622            self.unsupported(f"Unsupported property {expression.key}")
    1623
    1624        return f"{property_name}={self.sql(expression, 'this')}"

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

    1626    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
    1627        if self.SUPPORTS_CREATE_TABLE_LIKE:
    1628            options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
    1629            options = f" {options}" if options else ""
    1630
    1631            like = f"LIKE {self.sql(expression, 'this')}{options}"
    1632            if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema):
    1633                like = f"({like})"
    1634
    1635            return like
    1636
    1637        if expression.expressions:
    1638            self.unsupported("Transpilation of LIKE property options is unsupported")
    1639
    1640        select = exp.select("*").from_(expression.this).limit(0)
    1641        return f"AS {self.sql(select)}"

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

    1643    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1644        no = "NO " if expression.args.get("no") else ""
    1645        protection = " PROTECTION" if expression.args.get("protection") else ""
    1646        return f"{no}FALLBACK{protection}"

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

    1648    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1649        no = "NO " if expression.args.get("no") else ""
    1650        local = expression.args.get("local")
    1651        local = f"{local} " if local else ""
    1652        dual = "DUAL " if expression.args.get("dual") else ""
    1653        before = "BEFORE " if expression.args.get("before") else ""
    1654        after = "AFTER " if expression.args.get("after") else ""
    1655        return f"{no}{local}{dual}{before}{after}JOURNAL"

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

    1657    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1658        freespace = self.sql(expression, "this")
    1659        percent = " PERCENT" if expression.args.get("percent") else ""
    1660        return f"FREESPACE={freespace}{percent}"

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

    1662    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1663        if expression.args.get("default"):
    1664            property = "DEFAULT"
    1665        elif expression.args.get("on"):
    1666            property = "ON"
    1667        else:
    1668            property = "OFF"
    1669        return f"CHECKSUM={property}"

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

    1671    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1672        if expression.args.get("no"):
    1673            return "NO MERGEBLOCKRATIO"
    1674        if expression.args.get("default"):
    1675            return "DEFAULT MERGEBLOCKRATIO"
    1676
    1677        percent = " PERCENT" if expression.args.get("percent") else ""
    1678        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"

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

    1680    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1681        default = expression.args.get("default")
    1682        minimum = expression.args.get("minimum")
    1683        maximum = expression.args.get("maximum")
    1684        if default or minimum or maximum:
    1685            if default:
    1686                prop = "DEFAULT"
    1687            elif minimum:
    1688                prop = "MINIMUM"
    1689            else:
    1690                prop = "MAXIMUM"
    1691            return f"{prop} DATABLOCKSIZE"
    1692        units = expression.args.get("units")
    1693        units = f" {units}" if units else ""
    1694        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"

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

    1696    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1697        autotemp = expression.args.get("autotemp")
    1698        always = expression.args.get("always")
    1699        default = expression.args.get("default")
    1700        manual = expression.args.get("manual")
    1701        never = expression.args.get("never")
    1702
    1703        if autotemp is not None:
    1704            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1705        elif always:
    1706            prop = "ALWAYS"
    1707        elif default:
    1708            prop = "DEFAULT"
    1709        elif manual:
    1710            prop = "MANUAL"
    1711        elif never:
    1712            prop = "NEVER"
    1713        return f"BLOCKCOMPRESSION={prop}"

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

    1715    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1716        no = expression.args.get("no")
    1717        no = " NO" if no else ""
    1718        concurrent = expression.args.get("concurrent")
    1719        concurrent = " CONCURRENT" if concurrent else ""
    1720        target = self.sql(expression, "target")
    1721        target = f" {target}" if target else ""
    1722        return f"WITH{no}{concurrent} ISOLATED LOADING{target}"

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

    1724    def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str:
    1725        if isinstance(expression.this, list):
    1726            return f"IN ({self.expressions(expression, key='this', flat=True)})"
    1727        if expression.this:
    1728            modulus = self.sql(expression, "this")
    1729            remainder = self.sql(expression, "expression")
    1730            return f"WITH (MODULUS {modulus}, REMAINDER {remainder})"
    1731
    1732        from_expressions = self.expressions(expression, key="from_expressions", flat=True)
    1733        to_expressions = self.expressions(expression, key="to_expressions", flat=True)
    1734        return f"FROM ({from_expressions}) TO ({to_expressions})"

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

    1736    def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str:
    1737        this = self.sql(expression, "this")
    1738
    1739        for_values_or_default = expression.expression
    1740        if isinstance(for_values_or_default, exp.PartitionBoundSpec):
    1741            for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}"
    1742        else:
    1743            for_values_or_default = " DEFAULT"
    1744
    1745        return f"PARTITION OF {this}{for_values_or_default}"

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

    1747    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1748        kind = expression.args.get("kind")
    1749        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1750        for_or_in = expression.args.get("for_or_in")
    1751        for_or_in = f" {for_or_in}" if for_or_in else ""
    1752        lock_type = expression.args.get("lock_type")
    1753        override = " OVERRIDE" if expression.args.get("override") else ""
    1754        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"

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

    1756    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1757        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1758        statistics = expression.args.get("statistics")
    1759        statistics_sql = ""
    1760        if statistics is not None:
    1761            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1762        return f"{data_sql}{statistics_sql}"

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

    1764    def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str:
    1765        this = self.sql(expression, "this")
    1766        this = f"HISTORY_TABLE={this}" if this else ""
    1767        data_consistency: t.Optional[str] = self.sql(expression, "data_consistency")
    1768        data_consistency = (
    1769            f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None
    1770        )
    1771        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    1772        retention_period = (
    1773            f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None
    1774        )
    1775
    1776        if this:
    1777            on_sql = self.func("ON", this, data_consistency, retention_period)
    1778        else:
    1779            on_sql = "ON" if expression.args.get("on") else "OFF"
    1780
    1781        sql = f"SYSTEM_VERSIONING={on_sql}"
    1782
    1783        return f"WITH({sql})" if expression.args.get("with") else sql

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

    1785    def insert_sql(self, expression: exp.Insert) -> str:
    1786        hint = self.sql(expression, "hint")
    1787        overwrite = expression.args.get("overwrite")
    1788
    1789        if isinstance(expression.this, exp.Directory):
    1790            this = " OVERWRITE" if overwrite else " INTO"
    1791        else:
    1792            this = self.INSERT_OVERWRITE if overwrite else " INTO"
    1793
    1794        stored = self.sql(expression, "stored")
    1795        stored = f" {stored}" if stored else ""
    1796        alternative = expression.args.get("alternative")
    1797        alternative = f" OR {alternative}" if alternative else ""
    1798        ignore = " IGNORE" if expression.args.get("ignore") else ""
    1799        is_function = expression.args.get("is_function")
    1800        if is_function:
    1801            this = f"{this} FUNCTION"
    1802        this = f"{this} {self.sql(expression, 'this')}"
    1803
    1804        exists = " IF EXISTS" if expression.args.get("exists") else ""
    1805        where = self.sql(expression, "where")
    1806        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
    1807        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
    1808        on_conflict = self.sql(expression, "conflict")
    1809        on_conflict = f" {on_conflict}" if on_conflict else ""
    1810        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1811        returning = self.sql(expression, "returning")
    1812
    1813        if self.RETURNING_END:
    1814            expression_sql = f"{expression_sql}{on_conflict}{returning}"
    1815        else:
    1816            expression_sql = f"{returning}{expression_sql}{on_conflict}"
    1817
    1818        partition_by = self.sql(expression, "partition")
    1819        partition_by = f" {partition_by}" if partition_by else ""
    1820        settings = self.sql(expression, "settings")
    1821        settings = f" {settings}" if settings else ""
    1822
    1823        source = self.sql(expression, "source")
    1824        source = f"TABLE {source}" if source else ""
    1825
    1826        sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}"
    1827        return self.prepend_ctes(expression, sql)

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

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

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

    1832    def kill_sql(self, expression: exp.Kill) -> str:
    1833        kind = self.sql(expression, "kind")
    1834        kind = f" {kind}" if kind else ""
    1835        this = self.sql(expression, "this")
    1836        this = f" {this}" if this else ""
    1837        return f"KILL{kind}{this}"

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

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

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

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

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

    1845    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1846        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1847
    1848        constraint = self.sql(expression, "constraint")
    1849        constraint = f" ON CONSTRAINT {constraint}" if constraint else ""
    1850
    1851        conflict_keys = self.expressions(expression, key="conflict_keys", flat=True)
    1852        conflict_keys = f"({conflict_keys}) " if conflict_keys else " "
    1853        action = self.sql(expression, "action")
    1854
    1855        expressions = self.expressions(expression, flat=True)
    1856        if expressions:
    1857            set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
    1858            expressions = f" {set_keyword}{expressions}"
    1859
    1860        return f"{conflict}{constraint}{conflict_keys}{action}{expressions}"

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

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

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

    1865    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1866        fields = self.sql(expression, "fields")
    1867        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1868        escaped = self.sql(expression, "escaped")
    1869        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1870        items = self.sql(expression, "collection_items")
    1871        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1872        keys = self.sql(expression, "map_keys")
    1873        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1874        lines = self.sql(expression, "lines")
    1875        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1876        null = self.sql(expression, "null")
    1877        null = f" NULL DEFINED AS {null}" if null else ""
    1878        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"

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

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

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

    1883    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1884        this = f"{self.sql(expression, 'this')} INDEX"
    1885        target = self.sql(expression, "target")
    1886        target = f" FOR {target}" if target else ""
    1887        return f"{this}{target} ({self.expressions(expression, flat=True)})"

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

    1889    def historicaldata_sql(self, expression: exp.HistoricalData) -> str:
    1890        this = self.sql(expression, "this")
    1891        kind = self.sql(expression, "kind")
    1892        expr = self.sql(expression, "expression")
    1893        return f"{this} ({kind} => {expr})"

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

    1895    def table_parts(self, expression: exp.Table) -> str:
    1896        return ".".join(
    1897            self.sql(part)
    1898            for part in (
    1899                expression.args.get("catalog"),
    1900                expression.args.get("db"),
    1901                expression.args.get("this"),
    1902            )
    1903            if part is not None
    1904        )

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

    1906    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1907        table = self.table_parts(expression)
    1908        only = "ONLY " if expression.args.get("only") else ""
    1909        partition = self.sql(expression, "partition")
    1910        partition = f" {partition}" if partition else ""
    1911        version = self.sql(expression, "version")
    1912        version = f" {version}" if version else ""
    1913        alias = self.sql(expression, "alias")
    1914        alias = f"{sep}{alias}" if alias else ""
    1915
    1916        sample = self.sql(expression, "sample")
    1917        if self.dialect.ALIAS_POST_TABLESAMPLE:
    1918            sample_pre_alias = sample
    1919            sample_post_alias = ""
    1920        else:
    1921            sample_pre_alias = ""
    1922            sample_post_alias = sample
    1923
    1924        hints = self.expressions(expression, key="hints", sep=" ")
    1925        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
    1926        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    1927        joins = self.indent(
    1928            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
    1929        )
    1930        laterals = self.expressions(expression, key="laterals", sep="")
    1931
    1932        file_format = self.sql(expression, "format")
    1933        if file_format:
    1934            pattern = self.sql(expression, "pattern")
    1935            pattern = f", PATTERN => {pattern}" if pattern else ""
    1936            file_format = f" (FILE_FORMAT => {file_format}{pattern})"
    1937
    1938        ordinality = expression.args.get("ordinality") or ""
    1939        if ordinality:
    1940            ordinality = f" WITH ORDINALITY{alias}"
    1941            alias = ""
    1942
    1943        when = self.sql(expression, "when")
    1944        if when:
    1945            table = f"{table} {when}"
    1946
    1947        changes = self.sql(expression, "changes")
    1948        changes = f" {changes}" if changes else ""
    1949
    1950        rows_from = self.expressions(expression, key="rows_from")
    1951        if rows_from:
    1952            table = f"ROWS FROM {self.wrap(rows_from)}"
    1953
    1954        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

    1956    def tablesample_sql(
    1957        self,
    1958        expression: exp.TableSample,
    1959        tablesample_keyword: t.Optional[str] = None,
    1960    ) -> str:
    1961        method = self.sql(expression, "method")
    1962        method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    1963        numerator = self.sql(expression, "bucket_numerator")
    1964        denominator = self.sql(expression, "bucket_denominator")
    1965        field = self.sql(expression, "bucket_field")
    1966        field = f" ON {field}" if field else ""
    1967        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    1968        seed = self.sql(expression, "seed")
    1969        seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else ""
    1970
    1971        size = self.sql(expression, "size")
    1972        if size and self.TABLESAMPLE_SIZE_IS_ROWS:
    1973            size = f"{size} ROWS"
    1974
    1975        percent = self.sql(expression, "percent")
    1976        if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT:
    1977            percent = f"{percent} PERCENT"
    1978
    1979        expr = f"{bucket}{percent}{size}"
    1980        if self.TABLESAMPLE_REQUIRES_PARENS:
    1981            expr = f"({expr})"
    1982
    1983        return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}"

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

    1985    def pivot_sql(self, expression: exp.Pivot) -> str:
    1986        expressions = self.expressions(expression, flat=True)
    1987
    1988        if expression.this:
    1989            this = self.sql(expression, "this")
    1990            if not expressions:
    1991                return f"UNPIVOT {this}"
    1992
    1993            on = f"{self.seg('ON')} {expressions}"
    1994            using = self.expressions(expression, key="using", flat=True)
    1995            using = f"{self.seg('USING')} {using}" if using else ""
    1996            group = self.sql(expression, "group")
    1997            return f"PIVOT {this}{on}{using}{group}"
    1998
    1999        alias = self.sql(expression, "alias")
    2000        alias = f" AS {alias}" if alias else ""
    2001        direction = self.seg("UNPIVOT" if expression.unpivot else "PIVOT")
    2002
    2003        field = self.sql(expression, "field")
    2004
    2005        include_nulls = expression.args.get("include_nulls")
    2006        if include_nulls is not None:
    2007            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
    2008        else:
    2009            nulls = ""
    2010
    2011        default_on_null = self.sql(expression, "default_on_null")
    2012        default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else ""
    2013        return f"{direction}{nulls}({expressions} FOR {field}{default_on_null}){alias}"

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

    2015    def version_sql(self, expression: exp.Version) -> str:
    2016        this = f"FOR {expression.name}"
    2017        kind = expression.text("kind")
    2018        expr = self.sql(expression, "expression")
    2019        return f"{this} {kind} {expr}"

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

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

    2024    def update_sql(self, expression: exp.Update) -> str:
    2025        this = self.sql(expression, "this")
    2026        set_sql = self.expressions(expression, flat=True)
    2027        from_sql = self.sql(expression, "from")
    2028        where_sql = self.sql(expression, "where")
    2029        returning = self.sql(expression, "returning")
    2030        order = self.sql(expression, "order")
    2031        limit = self.sql(expression, "limit")
    2032        if self.RETURNING_END:
    2033            expression_sql = f"{from_sql}{where_sql}{returning}"
    2034        else:
    2035            expression_sql = f"{returning}{from_sql}{where_sql}"
    2036        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
    2037        return self.prepend_ctes(expression, sql)

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

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

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

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

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

    2085    @unsupported_args("expressions")
    2086    def into_sql(self, expression: exp.Into) -> str:
    2087        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    2088        unlogged = " UNLOGGED" if expression.args.get("unlogged") else ""
    2089        return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"

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

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

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

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

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

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

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

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

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

    2106    def group_sql(self, expression: exp.Group) -> str:
    2107        group_by_all = expression.args.get("all")
    2108        if group_by_all is True:
    2109            modifier = " ALL"
    2110        elif group_by_all is False:
    2111            modifier = " DISTINCT"
    2112        else:
    2113            modifier = ""
    2114
    2115        group_by = self.op_expressions(f"GROUP BY{modifier}", expression)
    2116
    2117        grouping_sets = self.expressions(expression, key="grouping_sets")
    2118        cube = self.expressions(expression, key="cube")
    2119        rollup = self.expressions(expression, key="rollup")
    2120
    2121        groupings = csv(
    2122            self.seg(grouping_sets) if grouping_sets else "",
    2123            self.seg(cube) if cube else "",
    2124            self.seg(rollup) if rollup else "",
    2125            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    2126            sep=self.GROUPINGS_SEP,
    2127        )
    2128
    2129        if (
    2130            expression.expressions
    2131            and groupings
    2132            and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP")
    2133        ):
    2134            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    2135
    2136        return f"{group_by}{groupings}"

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

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

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

    2142    def connect_sql(self, expression: exp.Connect) -> str:
    2143        start = self.sql(expression, "start")
    2144        start = self.seg(f"START WITH {start}") if start else ""
    2145        nocycle = " NOCYCLE" if expression.args.get("nocycle") else ""
    2146        connect = self.sql(expression, "connect")
    2147        connect = self.seg(f"CONNECT BY{nocycle} {connect}")
    2148        return start + connect

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

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

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

    2153    def join_sql(self, expression: exp.Join) -> str:
    2154        if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"):
    2155            side = None
    2156        else:
    2157            side = expression.side
    2158
    2159        op_sql = " ".join(
    2160            op
    2161            for op in (
    2162                expression.method,
    2163                "GLOBAL" if expression.args.get("global") else None,
    2164                side,
    2165                expression.kind,
    2166                expression.hint if self.JOIN_HINTS else None,
    2167            )
    2168            if op
    2169        )
    2170        match_cond = self.sql(expression, "match_condition")
    2171        match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else ""
    2172        on_sql = self.sql(expression, "on")
    2173        using = expression.args.get("using")
    2174
    2175        if not on_sql and using:
    2176            on_sql = csv(*(self.sql(column) for column in using))
    2177
    2178        this = expression.this
    2179        this_sql = self.sql(this)
    2180
    2181        exprs = self.expressions(expression)
    2182        if exprs:
    2183            this_sql = f"{this_sql},{self.seg(exprs)}"
    2184
    2185        if on_sql:
    2186            on_sql = self.indent(on_sql, skip_first=True)
    2187            space = self.seg(" " * self.pad) if self.pretty else " "
    2188            if using:
    2189                on_sql = f"{space}USING ({on_sql})"
    2190            else:
    2191                on_sql = f"{space}ON {on_sql}"
    2192        elif not op_sql:
    2193            if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None:
    2194                return f" {this_sql}"
    2195
    2196            return f", {this_sql}"
    2197
    2198        if op_sql != "STRAIGHT_JOIN":
    2199            op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    2200
    2201        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

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

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

    2208    def lateral_op(self, expression: exp.Lateral) -> str:
    2209        cross_apply = expression.args.get("cross_apply")
    2210
    2211        # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/
    2212        if cross_apply is True:
    2213            op = "INNER JOIN "
    2214        elif cross_apply is False:
    2215            op = "LEFT JOIN "
    2216        else:
    2217            op = ""
    2218
    2219        return f"{op}LATERAL"

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

    2221    def lateral_sql(self, expression: exp.Lateral) -> str:
    2222        this = self.sql(expression, "this")
    2223
    2224        if expression.args.get("view"):
    2225            alias = expression.args["alias"]
    2226            columns = self.expressions(alias, key="columns", flat=True)
    2227            table = f" {alias.name}" if alias.name else ""
    2228            columns = f" AS {columns}" if columns else ""
    2229            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    2230            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    2231
    2232        alias = self.sql(expression, "alias")
    2233        alias = f" AS {alias}" if alias else ""
    2234        return f"{self.lateral_op(expression)} {this}{alias}"

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

    2236    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    2237        this = self.sql(expression, "this")
    2238
    2239        args = [
    2240            self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e
    2241            for e in (expression.args.get(k) for k in ("offset", "expression"))
    2242            if e
    2243        ]
    2244
    2245        args_sql = ", ".join(self.sql(e) for e in args)
    2246        args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql
    2247        expressions = self.expressions(expression, flat=True)
    2248        expressions = f" BY {expressions}" if expressions else ""
    2249
    2250        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{expressions}"

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

    2252    def offset_sql(self, expression: exp.Offset) -> str:
    2253        this = self.sql(expression, "this")
    2254        value = expression.expression
    2255        value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value
    2256        expressions = self.expressions(expression, flat=True)
    2257        expressions = f" BY {expressions}" if expressions else ""
    2258        return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"

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

    2260    def setitem_sql(self, expression: exp.SetItem) -> str:
    2261        kind = self.sql(expression, "kind")
    2262        kind = f"{kind} " if kind else ""
    2263        this = self.sql(expression, "this")
    2264        expressions = self.expressions(expression)
    2265        collate = self.sql(expression, "collate")
    2266        collate = f" COLLATE {collate}" if collate else ""
    2267        global_ = "GLOBAL " if expression.args.get("global") else ""
    2268        return f"{global_}{kind}{this}{expressions}{collate}"

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

    2270    def set_sql(self, expression: exp.Set) -> str:
    2271        expressions = (
    2272            f" {self.expressions(expression, flat=True)}" if expression.expressions else ""
    2273        )
    2274        tag = " TAG" if expression.args.get("tag") else ""
    2275        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"

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

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

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

    2280    def lock_sql(self, expression: exp.Lock) -> str:
    2281        if not self.LOCKING_READS_SUPPORTED:
    2282            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    2283            return ""
    2284
    2285        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    2286        expressions = self.expressions(expression, flat=True)
    2287        expressions = f" OF {expressions}" if expressions else ""
    2288        wait = expression.args.get("wait")
    2289
    2290        if wait is not None:
    2291            if isinstance(wait, exp.Literal):
    2292                wait = f" WAIT {self.sql(wait)}"
    2293            else:
    2294                wait = " NOWAIT" if wait else " SKIP LOCKED"
    2295
    2296        return f"{lock_type}{expressions}{wait or ''}"

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

    2298    def literal_sql(self, expression: exp.Literal) -> str:
    2299        text = expression.this or ""
    2300        if expression.is_string:
    2301            text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}"
    2302        return text

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

    2304    def escape_str(self, text: str, escape_backslash: bool = True) -> str:
    2305        if self.dialect.ESCAPED_SEQUENCES:
    2306            to_escaped = self.dialect.ESCAPED_SEQUENCES
    2307            text = "".join(
    2308                to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text
    2309            )
    2310
    2311        return self._replace_line_breaks(text).replace(
    2312            self.dialect.QUOTE_END, self._escaped_quote_end
    2313        )

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

    2315    def loaddata_sql(self, expression: exp.LoadData) -> str:
    2316        local = " LOCAL" if expression.args.get("local") else ""
    2317        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    2318        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    2319        this = f" INTO TABLE {self.sql(expression, 'this')}"
    2320        partition = self.sql(expression, "partition")
    2321        partition = f" {partition}" if partition else ""
    2322        input_format = self.sql(expression, "input_format")
    2323        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    2324        serde = self.sql(expression, "serde")
    2325        serde = f" SERDE {serde}" if serde else ""
    2326        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"

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

    2328    def null_sql(self, *_) -> str:
    2329        return "NULL"

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

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

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

    2334    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    2335        this = self.sql(expression, "this")
    2336        this = f"{this} " if this else this
    2337        siblings = "SIBLINGS " if expression.args.get("siblings") else ""
    2338        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

    2340    def withfill_sql(self, expression: exp.WithFill) -> str:
    2341        from_sql = self.sql(expression, "from")
    2342        from_sql = f" FROM {from_sql}" if from_sql else ""
    2343        to_sql = self.sql(expression, "to")
    2344        to_sql = f" TO {to_sql}" if to_sql else ""
    2345        step_sql = self.sql(expression, "step")
    2346        step_sql = f" STEP {step_sql}" if step_sql else ""
    2347        interpolated_values = [
    2348            f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}"
    2349            if isinstance(e, exp.Alias)
    2350            else self.sql(e, "this")
    2351            for e in expression.args.get("interpolate") or []
    2352        ]
    2353        interpolate = (
    2354            f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else ""
    2355        )
    2356        return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}"

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

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

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

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

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

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

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

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

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

    2427    def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str:
    2428        window_frame = self.sql(expression, "window_frame")
    2429        window_frame = f"{window_frame} " if window_frame else ""
    2430
    2431        this = self.sql(expression, "this")
    2432
    2433        return f"{window_frame}{this}"

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

    2435    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    2436        partition = self.partition_by_sql(expression)
    2437        order = self.sql(expression, "order")
    2438        measures = self.expressions(expression, key="measures")
    2439        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    2440        rows = self.sql(expression, "rows")
    2441        rows = self.seg(rows) if rows else ""
    2442        after = self.sql(expression, "after")
    2443        after = self.seg(after) if after else ""
    2444        pattern = self.sql(expression, "pattern")
    2445        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    2446        definition_sqls = [
    2447            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    2448            for definition in expression.args.get("define", [])
    2449        ]
    2450        definitions = self.expressions(sqls=definition_sqls)
    2451        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    2452        body = "".join(
    2453            (
    2454                partition,
    2455                order,
    2456                measures,
    2457                rows,
    2458                after,
    2459                pattern,
    2460                define,
    2461            )
    2462        )
    2463        alias = self.sql(expression, "alias")
    2464        alias = f" {alias}" if alias else ""
    2465        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"

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

    2467    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    2468        limit = expression.args.get("limit")
    2469
    2470        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    2471            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
    2472        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    2473            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
    2474
    2475        return csv(
    2476            *sqls,
    2477            *[self.sql(join) for join in expression.args.get("joins") or []],
    2478            self.sql(expression, "connect"),
    2479            self.sql(expression, "match"),
    2480            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    2481            self.sql(expression, "prewhere"),
    2482            self.sql(expression, "where"),
    2483            self.sql(expression, "group"),
    2484            self.sql(expression, "having"),
    2485            *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()],
    2486            self.sql(expression, "order"),
    2487            *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit),
    2488            *self.after_limit_modifiers(expression),
    2489            self.options_modifier(expression),
    2490            sep="",
    2491        )

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

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

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

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

    2500    def offset_limit_modifiers(
    2501        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    2502    ) -> t.List[str]:
    2503        return [
    2504            self.sql(expression, "offset") if fetch else self.sql(limit),
    2505            self.sql(limit) if fetch else self.sql(expression, "offset"),
    2506        ]

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

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

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

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

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

    2585    def schema_sql(self, expression: exp.Schema) -> str:
    2586        this = self.sql(expression, "this")
    2587        sql = self.schema_columns_sql(expression)
    2588        return f"{this} {sql}" if this and sql else this or sql

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

    2590    def schema_columns_sql(self, expression: exp.Schema) -> str:
    2591        if expression.expressions:
    2592            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
    2593        return ""

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

    2595    def star_sql(self, expression: exp.Star) -> str:
    2596        except_ = self.expressions(expression, key="except", flat=True)
    2597        except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else ""
    2598        replace = self.expressions(expression, key="replace", flat=True)
    2599        replace = f"{self.seg('REPLACE')} ({replace})" if replace else ""
    2600        rename = self.expressions(expression, key="rename", flat=True)
    2601        rename = f"{self.seg('RENAME')} ({rename})" if rename else ""
    2602        return f"*{except_}{replace}{rename}"

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

    2604    def parameter_sql(self, expression: exp.Parameter) -> str:
    2605        this = self.sql(expression, "this")
    2606        return f"{self.PARAMETER_TOKEN}{this}"

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

    2608    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    2609        this = self.sql(expression, "this")
    2610        kind = expression.text("kind")
    2611        if kind:
    2612            kind = f"{kind}."
    2613        return f"@@{kind}{this}"

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

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

    2618    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    2619        alias = self.sql(expression, "alias")
    2620        alias = f"{sep}{alias}" if alias else ""
    2621        sample = self.sql(expression, "sample")
    2622        if self.dialect.ALIAS_POST_TABLESAMPLE and sample:
    2623            alias = f"{sample}{alias}"
    2624
    2625            # Set to None so it's not generated again by self.query_modifiers()
    2626            expression.set("sample", None)
    2627
    2628        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    2629        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    2630        return self.prepend_ctes(expression, sql)

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

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

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

    2636    def unnest_sql(self, expression: exp.Unnest) -> str:
    2637        args = self.expressions(expression, flat=True)
    2638
    2639        alias = expression.args.get("alias")
    2640        offset = expression.args.get("offset")
    2641
    2642        if self.UNNEST_WITH_ORDINALITY:
    2643            if alias and isinstance(offset, exp.Expression):
    2644                alias.append("columns", offset)
    2645
    2646        if alias and self.dialect.UNNEST_COLUMN_ONLY:
    2647            columns = alias.columns
    2648            alias = self.sql(columns[0]) if columns else ""
    2649        else:
    2650            alias = self.sql(alias)
    2651
    2652        alias = f" AS {alias}" if alias else alias
    2653        if self.UNNEST_WITH_ORDINALITY:
    2654            suffix = f" WITH ORDINALITY{alias}" if offset else alias
    2655        else:
    2656            if isinstance(offset, exp.Expression):
    2657                suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}"
    2658            elif offset:
    2659                suffix = f"{alias} WITH OFFSET"
    2660            else:
    2661                suffix = alias
    2662
    2663        return f"UNNEST({args}){suffix}"

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

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

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

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

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

    2672    def window_sql(self, expression: exp.Window) -> str:
    2673        this = self.sql(expression, "this")
    2674        partition = self.partition_by_sql(expression)
    2675        order = expression.args.get("order")
    2676        order = self.order_sql(order, flat=True) if order else ""
    2677        spec = self.sql(expression, "spec")
    2678        alias = self.sql(expression, "alias")
    2679        over = self.sql(expression, "over") or "OVER"
    2680
    2681        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    2682
    2683        first = expression.args.get("first")
    2684        if first is None:
    2685            first = ""
    2686        else:
    2687            first = "FIRST" if first else "LAST"
    2688
    2689        if not partition and not order and not spec and alias:
    2690            return f"{this} {alias}"
    2691
    2692        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
    2693        return f"{this} ({args})"

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

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

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

    2699    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    2700        kind = self.sql(expression, "kind")
    2701        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    2702        end = (
    2703            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    2704            or "CURRENT ROW"
    2705        )
    2706        return f"{kind} BETWEEN {start} AND {end}"

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

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

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

    2713    def between_sql(self, expression: exp.Between) -> str:
    2714        this = self.sql(expression, "this")
    2715        low = self.sql(expression, "low")
    2716        high = self.sql(expression, "high")
    2717        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

    2719    def bracket_offset_expressions(
    2720        self, expression: exp.Bracket, index_offset: t.Optional[int] = None
    2721    ) -> t.List[exp.Expression]:
    2722        return apply_index_offset(
    2723            expression.this,
    2724            expression.expressions,
    2725            (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0),
    2726        )

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

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

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

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

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

    2736    def any_sql(self, expression: exp.Any) -> str:
    2737        this = self.sql(expression, "this")
    2738        if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)):
    2739            if isinstance(expression.this, exp.UNWRAPPED_QUERIES):
    2740                this = self.wrap(this)
    2741            return f"ANY{this}"
    2742        return f"ANY {this}"

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

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

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

    2747    def case_sql(self, expression: exp.Case) -> str:
    2748        this = self.sql(expression, "this")
    2749        statements = [f"CASE {this}" if this else "CASE"]
    2750
    2751        for e in expression.args["ifs"]:
    2752            statements.append(f"WHEN {self.sql(e, 'this')}")
    2753            statements.append(f"THEN {self.sql(e, 'true')}")
    2754
    2755        default = self.sql(expression, "default")
    2756
    2757        if default:
    2758            statements.append(f"ELSE {default}")
    2759
    2760        statements.append("END")
    2761
    2762        if self.pretty and self.too_wide(statements):
    2763            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    2764
    2765        return " ".join(statements)

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

    2767    def constraint_sql(self, expression: exp.Constraint) -> str:
    2768        this = self.sql(expression, "this")
    2769        expressions = self.expressions(expression, flat=True)
    2770        return f"CONSTRAINT {this} {expressions}"

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

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

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

    2777    def extract_sql(self, expression: exp.Extract) -> str:
    2778        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
    2779        expression_sql = self.sql(expression, "expression")
    2780        return f"EXTRACT({this} FROM {expression_sql})"

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

    2782    def trim_sql(self, expression: exp.Trim) -> str:
    2783        trim_type = self.sql(expression, "position")
    2784
    2785        if trim_type == "LEADING":
    2786            func_name = "LTRIM"
    2787        elif trim_type == "TRAILING":
    2788            func_name = "RTRIM"
    2789        else:
    2790            func_name = "TRIM"
    2791
    2792        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

    2794    def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]:
    2795        args = expression.expressions
    2796        if isinstance(expression, exp.ConcatWs):
    2797            args = args[1:]  # Skip the delimiter
    2798
    2799        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    2800            args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args]
    2801
    2802        if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"):
    2803            args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args]
    2804
    2805        return args

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

    2807    def concat_sql(self, expression: exp.Concat) -> str:
    2808        expressions = self.convert_concat_args(expression)
    2809
    2810        # Some dialects don't allow a single-argument CONCAT call
    2811        if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1:
    2812            return self.sql(expressions[0])
    2813
    2814        return self.func("CONCAT", *expressions)

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

    2816    def concatws_sql(self, expression: exp.ConcatWs) -> str:
    2817        return self.func(
    2818            "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression)
    2819        )

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

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

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

    2825    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    2826        expressions = self.expressions(expression, flat=True)
    2827        reference = self.sql(expression, "reference")
    2828        reference = f" {reference}" if reference else ""
    2829        delete = self.sql(expression, "delete")
    2830        delete = f" ON DELETE {delete}" if delete else ""
    2831        update = self.sql(expression, "update")
    2832        update = f" ON UPDATE {update}" if update else ""
    2833        return f"FOREIGN KEY ({expressions}){reference}{delete}{update}"

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

    2835    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    2836        expressions = self.expressions(expression, flat=True)
    2837        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2838        options = f" {options}" if options else ""
    2839        return f"PRIMARY KEY ({expressions}){options}"

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

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

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

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

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

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

    2852    def jsonpath_sql(self, expression: exp.JSONPath) -> str:
    2853        path = self.expressions(expression, sep="", flat=True).lstrip(".")
    2854
    2855        if expression.args.get("escape"):
    2856            path = self.escape_str(path)
    2857
    2858        if self.QUOTE_JSON_PATH:
    2859            path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"
    2860
    2861        return path

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

    2863    def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str:
    2864        if isinstance(expression, exp.JSONPathPart):
    2865            transform = self.TRANSFORMS.get(expression.__class__)
    2866            if not callable(transform):
    2867                self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}")
    2868                return ""
    2869
    2870            return transform(self, expression)
    2871
    2872        if isinstance(expression, int):
    2873            return str(expression)
    2874
    2875        if self.JSON_PATH_SINGLE_QUOTE_ESCAPE:
    2876            escaped = expression.replace("'", "\\'")
    2877            escaped = f"\\'{expression}\\'"
    2878        else:
    2879            escaped = expression.replace('"', '\\"')
    2880            escaped = f'"{escaped}"'
    2881
    2882        return escaped

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

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

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

    2887    def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str:
    2888        null_handling = expression.args.get("null_handling")
    2889        null_handling = f" {null_handling}" if null_handling else ""
    2890
    2891        unique_keys = expression.args.get("unique_keys")
    2892        if unique_keys is not None:
    2893            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    2894        else:
    2895            unique_keys = ""
    2896
    2897        return_type = self.sql(expression, "return_type")
    2898        return_type = f" RETURNING {return_type}" if return_type else ""
    2899        encoding = self.sql(expression, "encoding")
    2900        encoding = f" ENCODING {encoding}" if encoding else ""
    2901
    2902        return self.func(
    2903            "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG",
    2904            *expression.expressions,
    2905            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
    2906        )

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

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

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

    2911    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
    2912        null_handling = expression.args.get("null_handling")
    2913        null_handling = f" {null_handling}" if null_handling else ""
    2914        return_type = self.sql(expression, "return_type")
    2915        return_type = f" RETURNING {return_type}" if return_type else ""
    2916        strict = " STRICT" if expression.args.get("strict") else ""
    2917        return self.func(
    2918            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
    2919        )

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

    2921    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
    2922        this = self.sql(expression, "this")
    2923        order = self.sql(expression, "order")
    2924        null_handling = expression.args.get("null_handling")
    2925        null_handling = f" {null_handling}" if null_handling else ""
    2926        return_type = self.sql(expression, "return_type")
    2927        return_type = f" RETURNING {return_type}" if return_type else ""
    2928        strict = " STRICT" if expression.args.get("strict") else ""
    2929        return self.func(
    2930            "JSON_ARRAYAGG",
    2931            this,
    2932            suffix=f"{order}{null_handling}{return_type}{strict})",
    2933        )

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

    2935    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
    2936        path = self.sql(expression, "path")
    2937        path = f" PATH {path}" if path else ""
    2938        nested_schema = self.sql(expression, "nested_schema")
    2939
    2940        if nested_schema:
    2941            return f"NESTED{path} {nested_schema}"
    2942
    2943        this = self.sql(expression, "this")
    2944        kind = self.sql(expression, "kind")
    2945        kind = f" {kind}" if kind else ""
    2946        return f"{this}{kind}{path}"

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

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

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

    2951    def jsontable_sql(self, expression: exp.JSONTable) -> str:
    2952        this = self.sql(expression, "this")
    2953        path = self.sql(expression, "path")
    2954        path = f", {path}" if path else ""
    2955        error_handling = expression.args.get("error_handling")
    2956        error_handling = f" {error_handling}" if error_handling else ""
    2957        empty_handling = expression.args.get("empty_handling")
    2958        empty_handling = f" {empty_handling}" if empty_handling else ""
    2959        schema = self.sql(expression, "schema")
    2960        return self.func(
    2961            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
    2962        )

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

    2964    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    2965        this = self.sql(expression, "this")
    2966        kind = self.sql(expression, "kind")
    2967        path = self.sql(expression, "path")
    2968        path = f" {path}" if path else ""
    2969        as_json = " AS JSON" if expression.args.get("as_json") else ""
    2970        return f"{this} {kind}{path}{as_json}"

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

    2972    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    2973        this = self.sql(expression, "this")
    2974        path = self.sql(expression, "path")
    2975        path = f", {path}" if path else ""
    2976        expressions = self.expressions(expression)
    2977        with_ = (
    2978            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    2979            if expressions
    2980            else ""
    2981        )
    2982        return f"OPENJSON({this}{path}){with_}"

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

    2984    def in_sql(self, expression: exp.In) -> str:
    2985        query = expression.args.get("query")
    2986        unnest = expression.args.get("unnest")
    2987        field = expression.args.get("field")
    2988        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    2989
    2990        if query:
    2991            in_sql = self.sql(query)
    2992        elif unnest:
    2993            in_sql = self.in_unnest_op(unnest)
    2994        elif field:
    2995            in_sql = self.sql(field)
    2996        else:
    2997            in_sql = f"({self.expressions(expression, flat=True)})"
    2998
    2999        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"

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

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

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

    3004    def interval_sql(self, expression: exp.Interval) -> str:
    3005        unit = self.sql(expression, "unit")
    3006        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    3007            unit = self.TIME_PART_SINGULARS.get(unit, unit)
    3008        unit = f" {unit}" if unit else ""
    3009
    3010        if self.SINGLE_STRING_INTERVAL:
    3011            this = expression.this.name if expression.this else ""
    3012            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    3013
    3014        this = self.sql(expression, "this")
    3015        if this:
    3016            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    3017            this = f" {this}" if unwrapped else f" ({this})"
    3018
    3019        return f"INTERVAL{this}{unit}"

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

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

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

    3024    def reference_sql(self, expression: exp.Reference) -> str:
    3025        this = self.sql(expression, "this")
    3026        expressions = self.expressions(expression, flat=True)
    3027        expressions = f"({expressions})" if expressions else ""
    3028        options = self.expressions(expression, key="options", flat=True, sep=" ")
    3029        options = f" {options}" if options else ""
    3030        return f"REFERENCES {this}{expressions}{options}"

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

    3032    def anonymous_sql(self, expression: exp.Anonymous) -> str:
    3033        # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive
    3034        parent = expression.parent
    3035        is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression
    3036        return self.func(
    3037            self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified
    3038        )

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

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

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

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

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

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

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

    3053    def alias_sql(self, expression: exp.Alias) -> str:
    3054        alias = self.sql(expression, "alias")
    3055        alias = f" AS {alias}" if alias else ""
    3056        return f"{self.sql(expression, 'this')}{alias}"

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

    3058    def pivotalias_sql(self, expression: exp.PivotAlias) -> str:
    3059        alias = expression.args["alias"]
    3060
    3061        identifier_alias = isinstance(alias, exp.Identifier)
    3062        literal_alias = isinstance(alias, exp.Literal)
    3063
    3064        if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    3065            alias.replace(exp.Literal.string(alias.output_name))
    3066        elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    3067            alias.replace(exp.to_identifier(alias.output_name))
    3068
    3069        return self.alias_sql(expression)

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

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

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

    3074    def atindex_sql(self, expression: exp.AtTimeZone) -> str:
    3075        this = self.sql(expression, "this")
    3076        index = self.sql(expression, "expression")
    3077        return f"{this} AT {index}"

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

    3079    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    3080        this = self.sql(expression, "this")
    3081        zone = self.sql(expression, "zone")
    3082        return f"{this} AT TIME ZONE {zone}"

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

    3084    def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str:
    3085        this = self.sql(expression, "this")
    3086        zone = self.sql(expression, "zone")
    3087        return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'"

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

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

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

    3092    def and_sql(
    3093        self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None
    3094    ) -> str:
    3095        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

    3097    def or_sql(
    3098        self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None
    3099    ) -> str:
    3100        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

    3102    def xor_sql(
    3103        self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None
    3104    ) -> str:
    3105        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

    3107    def connector_sql(
    3108        self,
    3109        expression: exp.Connector,
    3110        op: str,
    3111        stack: t.Optional[t.List[str | exp.Expression]] = None,
    3112    ) -> str:
    3113        if stack is not None:
    3114            if expression.expressions:
    3115                stack.append(self.expressions(expression, sep=f" {op} "))
    3116            else:
    3117                stack.append(expression.right)
    3118                if expression.comments and self.comments:
    3119                    for comment in expression.comments:
    3120                        if comment:
    3121                            op += f" /*{self.pad_comment(comment)}*/"
    3122                stack.extend((op, expression.left))
    3123            return op
    3124
    3125        stack = [expression]
    3126        sqls: t.List[str] = []
    3127        ops = set()
    3128
    3129        while stack:
    3130            node = stack.pop()
    3131            if isinstance(node, exp.Connector):
    3132                ops.add(getattr(self, f"{node.key}_sql")(node, stack))
    3133            else:
    3134                sql = self.sql(node)
    3135                if sqls and sqls[-1] in ops:
    3136                    sqls[-1] += f" {sql}"
    3137                else:
    3138                    sqls.append(sql)
    3139
    3140        sep = "\n" if self.pretty and self.too_wide(sqls) else " "
    3141        return sep.join(sqls)

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

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

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

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

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

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

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

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

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

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

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

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

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

    3161    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    3162        format_sql = self.sql(expression, "format")
    3163        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    3164        to_sql = self.sql(expression, "to")
    3165        to_sql = f" {to_sql}" if to_sql else ""
    3166        action = self.sql(expression, "action")
    3167        action = f" {action}" if action else ""
    3168        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

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

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

    3174    def collate_sql(self, expression: exp.Collate) -> str:
    3175        if self.COLLATE_IS_FUNC:
    3176            return self.function_fallback_sql(expression)
    3177        return self.binary(expression, "COLLATE")

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

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

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

    3182    def comment_sql(self, expression: exp.Comment) -> str:
    3183        this = self.sql(expression, "this")
    3184        kind = expression.args["kind"]
    3185        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    3186        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    3187        expression_sql = self.sql(expression, "expression")
    3188        return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"

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

    3190    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    3191        this = self.sql(expression, "this")
    3192        delete = " DELETE" if expression.args.get("delete") else ""
    3193        recompress = self.sql(expression, "recompress")
    3194        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    3195        to_disk = self.sql(expression, "to_disk")
    3196        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    3197        to_volume = self.sql(expression, "to_volume")
    3198        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    3199        return f"{this}{delete}{recompress}{to_disk}{to_volume}"

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

    3201    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    3202        where = self.sql(expression, "where")
    3203        group = self.sql(expression, "group")
    3204        aggregates = self.expressions(expression, key="aggregates")
    3205        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    3206
    3207        if not (where or group or aggregates) and len(expression.expressions) == 1:
    3208            return f"TTL {self.expressions(expression, flat=True)}"
    3209
    3210        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"

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

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

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

    3215    def commit_sql(self, expression: exp.Commit) -> str:
    3216        chain = expression.args.get("chain")
    3217        if chain is not None:
    3218            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    3219
    3220        return f"COMMIT{chain or ''}"

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

    3222    def rollback_sql(self, expression: exp.Rollback) -> str:
    3223        savepoint = expression.args.get("savepoint")
    3224        savepoint = f" TO {savepoint}" if savepoint else ""
    3225        return f"ROLLBACK{savepoint}"

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

    3227    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    3228        this = self.sql(expression, "this")
    3229
    3230        dtype = self.sql(expression, "dtype")
    3231        if dtype:
    3232            collate = self.sql(expression, "collate")
    3233            collate = f" COLLATE {collate}" if collate else ""
    3234            using = self.sql(expression, "using")
    3235            using = f" USING {using}" if using else ""
    3236            return f"ALTER COLUMN {this} SET DATA TYPE {dtype}{collate}{using}"
    3237
    3238        default = self.sql(expression, "default")
    3239        if default:
    3240            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    3241
    3242        comment = self.sql(expression, "comment")
    3243        if comment:
    3244            return f"ALTER COLUMN {this} COMMENT {comment}"
    3245
    3246        allow_null = expression.args.get("allow_null")
    3247        drop = expression.args.get("drop")
    3248
    3249        if not drop and not allow_null:
    3250            self.unsupported("Unsupported ALTER COLUMN syntax")
    3251
    3252        if allow_null is not None:
    3253            keyword = "DROP" if drop else "SET"
    3254            return f"ALTER COLUMN {this} {keyword} NOT NULL"
    3255
    3256        return f"ALTER COLUMN {this} DROP DEFAULT"

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

    3258    def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str:
    3259        this = self.sql(expression, "this")
    3260        if not isinstance(expression.this, exp.Var):
    3261            this = f"KEY DISTKEY {this}"
    3262        return f"ALTER DISTSTYLE {this}"

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

    3264    def altersortkey_sql(self, expression: exp.AlterSortKey) -> str:
    3265        compound = " COMPOUND" if expression.args.get("compound") else ""
    3266        this = self.sql(expression, "this")
    3267        expressions = self.expressions(expression, flat=True)
    3268        expressions = f"({expressions})" if expressions else ""
    3269        return f"ALTER{compound} SORTKEY {this or expressions}"

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

    3271    def alterrename_sql(self, expression: exp.AlterRename) -> str:
    3272        if not self.RENAME_TABLE_WITH_DB:
    3273            # Remove db from tables
    3274            expression = expression.transform(
    3275                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    3276            ).assert_is(exp.AlterRename)
    3277        this = self.sql(expression, "this")
    3278        return f"RENAME TO {this}"

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

    3280    def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
    3281        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3282        old_column = self.sql(expression, "this")
    3283        new_column = self.sql(expression, "to")
    3284        return f"RENAME COLUMN{exists} {old_column} TO {new_column}"

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

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

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

    3290    def alter_sql(self, expression: exp.Alter) -> str:
    3291        actions = expression.args["actions"]
    3292
    3293        if isinstance(actions[0], exp.ColumnDef):
    3294            actions = self.add_column_sql(expression)
    3295        elif isinstance(actions[0], exp.Schema):
    3296            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    3297        elif isinstance(actions[0], exp.Delete):
    3298            actions = self.expressions(expression, key="actions", flat=True)
    3299        elif isinstance(actions[0], exp.Query):
    3300            actions = "AS " + self.expressions(expression, key="actions")
    3301        else:
    3302            actions = self.expressions(expression, key="actions", flat=True)
    3303
    3304        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3305        on_cluster = self.sql(expression, "cluster")
    3306        on_cluster = f" {on_cluster}" if on_cluster else ""
    3307        only = " ONLY" if expression.args.get("only") else ""
    3308        options = self.expressions(expression, key="options")
    3309        options = f", {options}" if options else ""
    3310        kind = self.sql(expression, "kind")
    3311        not_valid = " NOT VALID" if expression.args.get("not_valid") else ""
    3312
    3313        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

    3315    def add_column_sql(self, expression: exp.Alter) -> str:
    3316        if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD:
    3317            return self.expressions(
    3318                expression,
    3319                key="actions",
    3320                prefix="ADD COLUMN ",
    3321                skip_first=True,
    3322            )
    3323        return f"ADD {self.expressions(expression, key='actions', flat=True)}"

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

    3325    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    3326        expressions = self.expressions(expression)
    3327        exists = " IF EXISTS " if expression.args.get("exists") else " "
    3328        return f"DROP{exists}{expressions}"

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

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

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

    3333    def distinct_sql(self, expression: exp.Distinct) -> str:
    3334        this = self.expressions(expression, flat=True)
    3335
    3336        if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1:
    3337            case = exp.case()
    3338            for arg in expression.expressions:
    3339                case = case.when(arg.is_(exp.null()), exp.null())
    3340            this = self.sql(case.else_(f"({this})"))
    3341
    3342        this = f" {this}" if this else ""
    3343
    3344        on = self.sql(expression, "on")
    3345        on = f" ON {on}" if on else ""
    3346        return f"DISTINCT{this}{on}"

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

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

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

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

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

    3354    def havingmax_sql(self, expression: exp.HavingMax) -> str:
    3355        this_sql = self.sql(expression, "this")
    3356        expression_sql = self.sql(expression, "expression")
    3357        kind = "MAX" if expression.args.get("max") else "MIN"
    3358        return f"{this_sql} HAVING {kind} {expression_sql}"

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

    3360    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    3361        return self.sql(
    3362            exp.Cast(
    3363                this=exp.Div(this=expression.this, expression=expression.expression),
    3364                to=exp.DataType(this=exp.DataType.Type.INT),
    3365            )
    3366        )

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

    3368    def dpipe_sql(self, expression: exp.DPipe) -> str:
    3369        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    3370            return self.func(
    3371                "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten())
    3372            )
    3373        return self.binary(expression, "||")

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

    3375    def div_sql(self, expression: exp.Div) -> str:
    3376        l, r = expression.left, expression.right
    3377
    3378        if not self.dialect.SAFE_DIVISION and expression.args.get("safe"):
    3379            r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0)))
    3380
    3381        if self.dialect.TYPED_DIVISION and not expression.args.get("typed"):
    3382            if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES):
    3383                l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE))
    3384
    3385        elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"):
    3386            if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES):
    3387                return self.sql(
    3388                    exp.cast(
    3389                        l / r,
    3390                        to=exp.DataType.Type.BIGINT,
    3391                    )
    3392                )
    3393
    3394        return self.binary(expression, "/")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3429    def is_sql(self, expression: exp.Is) -> str:
    3430        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    3431            return self.sql(
    3432                expression.this if expression.expression.this else exp.not_(expression.this)
    3433            )
    3434        return self.binary(expression, "IS")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3475    def try_sql(self, expression: exp.Try) -> str:
    3476        if not self.TRY_SUPPORTED:
    3477            self.unsupported("Unsupported TRY function")
    3478            return self.sql(expression, "this")
    3479
    3480        return self.func("TRY", expression.this)

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

    3482    def log_sql(self, expression: exp.Log) -> str:
    3483        this = expression.this
    3484        expr = expression.expression
    3485
    3486        if self.dialect.LOG_BASE_FIRST is False:
    3487            this, expr = expr, this
    3488        elif self.dialect.LOG_BASE_FIRST is None and expr:
    3489            if this.name in ("2", "10"):
    3490                return self.func(f"LOG{this.name}", expr)
    3491
    3492            self.unsupported(f"Unsupported logarithm with base {self.sql(this)}")
    3493
    3494        return self.func("LOG", this, expr)

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

    3496    def use_sql(self, expression: exp.Use) -> str:
    3497        kind = self.sql(expression, "kind")
    3498        kind = f" {kind}" if kind else ""
    3499        this = self.sql(expression, "this")
    3500        this = f" {this}" if this else ""
    3501        return f"USE{kind}{this}"

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

    3503    def binary(self, expression: exp.Binary, op: str) -> str:
    3504        sqls: t.List[str] = []
    3505        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    3506        binary_type = type(expression)
    3507
    3508        while stack:
    3509            node = stack.pop()
    3510
    3511            if type(node) is binary_type:
    3512                op_func = node.args.get("operator")
    3513                if op_func:
    3514                    op = f"OPERATOR({self.sql(op_func)})"
    3515
    3516                stack.append(node.right)
    3517                stack.append(f" {self.maybe_comment(op, comments=node.comments)} ")
    3518                stack.append(node.left)
    3519            else:
    3520                sqls.append(self.sql(node))
    3521
    3522        return "".join(sqls)

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

    3524    def function_fallback_sql(self, expression: exp.Func) -> str:
    3525        args = []
    3526
    3527        for key in expression.arg_types:
    3528            arg_value = expression.args.get(key)
    3529
    3530            if isinstance(arg_value, list):
    3531                for value in arg_value:
    3532                    args.append(value)
    3533            elif arg_value is not None:
    3534                args.append(arg_value)
    3535
    3536        if self.dialect.PRESERVE_ORIGINAL_NAMES:
    3537            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
    3538        else:
    3539            name = expression.sql_name()
    3540
    3541        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

    3543    def func(
    3544        self,
    3545        name: str,
    3546        *args: t.Optional[exp.Expression | str],
    3547        prefix: str = "(",
    3548        suffix: str = ")",
    3549        normalize: bool = True,
    3550    ) -> str:
    3551        name = self.normalize_func(name) if normalize else name
    3552        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

    3554    def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str:
    3555        arg_sqls = tuple(
    3556            self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool)
    3557        )
    3558        if self.pretty and self.too_wide(arg_sqls):
    3559            return self.indent(
    3560                "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True
    3561            )
    3562        return sep.join(arg_sqls)

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

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

    3567    def format_time(
    3568        self,
    3569        expression: exp.Expression,
    3570        inverse_time_mapping: t.Optional[t.Dict[str, str]] = None,
    3571        inverse_time_trie: t.Optional[t.Dict] = None,
    3572    ) -> t.Optional[str]:
    3573        return format_time(
    3574            self.sql(expression, "format"),
    3575            inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING,
    3576            inverse_time_trie or self.dialect.INVERSE_TIME_TRIE,
    3577        )

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

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

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

    3635    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    3636        flat = flat or isinstance(expression.parent, exp.Properties)
    3637        expressions_sql = self.expressions(expression, flat=flat)
    3638        if flat:
    3639            return f"{op} {expressions_sql}"
    3640        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"

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

    3642    def naked_property(self, expression: exp.Property) -> str:
    3643        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    3644        if not property_name:
    3645            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    3646        return f"{property_name} {self.sql(expression, 'this')}"

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

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

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

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

    3654    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    3655        this = self.sql(expression, "this")
    3656        expressions = self.no_identify(self.expressions, expression)
    3657        expressions = (
    3658            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    3659        )
    3660        return f"{this}{expressions}" if expressions.strip() != "" else this

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

    3662    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    3663        this = self.sql(expression, "this")
    3664        expressions = self.expressions(expression, flat=True)
    3665        return f"{this}({expressions})"

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

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

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

    3670    def when_sql(self, expression: exp.When) -> str:
    3671        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    3672        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    3673        condition = self.sql(expression, "condition")
    3674        condition = f" AND {condition}" if condition else ""
    3675
    3676        then_expression = expression.args.get("then")
    3677        if isinstance(then_expression, exp.Insert):
    3678            this = self.sql(then_expression, "this")
    3679            this = f"INSERT {this}" if this else "INSERT"
    3680            then = self.sql(then_expression, "expression")
    3681            then = f"{this} VALUES {then}" if then else this
    3682        elif isinstance(then_expression, exp.Update):
    3683            if isinstance(then_expression.args.get("expressions"), exp.Star):
    3684                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    3685            else:
    3686                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    3687        else:
    3688            then = self.sql(then_expression)
    3689        return f"WHEN {matched}{source}{condition} THEN {then}"

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

    3691    def merge_sql(self, expression: exp.Merge) -> str:
    3692        table = expression.this
    3693        table_alias = ""
    3694
    3695        hints = table.args.get("hints")
    3696        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
    3697            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
    3698            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
    3699
    3700        this = self.sql(table)
    3701        using = f"USING {self.sql(expression, 'using')}"
    3702        on = f"ON {self.sql(expression, 'on')}"
    3703        expressions = self.expressions(expression, sep=" ", indent=False)
    3704        returning = self.sql(expression, "returning")
    3705        if returning:
    3706            expressions = f"{expressions}{returning}"
    3707
    3708        sep = self.sep()
    3709
    3710        return self.prepend_ctes(
    3711            expression,
    3712            f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{expressions}",
    3713        )

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

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

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

    3719    def tonumber_sql(self, expression: exp.ToNumber) -> str:
    3720        if not self.SUPPORTS_TO_NUMBER:
    3721            self.unsupported("Unsupported TO_NUMBER function")
    3722            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3723
    3724        fmt = expression.args.get("format")
    3725        if not fmt:
    3726            self.unsupported("Conversion format is required for TO_NUMBER")
    3727            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3728
    3729        return self.func("TO_NUMBER", expression.this, fmt)

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

    3731    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    3732        this = self.sql(expression, "this")
    3733        kind = self.sql(expression, "kind")
    3734        settings_sql = self.expressions(expression, key="settings", sep=" ")
    3735        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    3736        return f"{this}({kind}{args})"

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

    3738    def dictrange_sql(self, expression: exp.DictRange) -> str:
    3739        this = self.sql(expression, "this")
    3740        max = self.sql(expression, "max")
    3741        min = self.sql(expression, "min")
    3742        return f"{this}(MIN {min} MAX {max})"

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

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

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

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

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

    3751    def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str:
    3752        expressions = self.expressions(expression, flat=True)
    3753        expressions = f" {self.wrap(expressions)}" if expressions else ""
    3754        buckets = self.sql(expression, "buckets")
    3755        kind = self.sql(expression, "kind")
    3756        buckets = f" BUCKETS {buckets}" if buckets else ""
    3757        order = self.sql(expression, "order")
    3758        return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}"

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

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

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

    3763    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    3764        expressions = self.expressions(expression, key="expressions", flat=True)
    3765        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    3766        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    3767        buckets = self.sql(expression, "buckets")
    3768        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"

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

    3770    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    3771        this = self.sql(expression, "this")
    3772        having = self.sql(expression, "having")
    3773
    3774        if having:
    3775            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    3776
    3777        return self.func("ANY_VALUE", this)

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

    3779    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
    3780        transform = self.func("TRANSFORM", *expression.expressions)
    3781        row_format_before = self.sql(expression, "row_format_before")
    3782        row_format_before = f" {row_format_before}" if row_format_before else ""
    3783        record_writer = self.sql(expression, "record_writer")
    3784        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
    3785        using = f" USING {self.sql(expression, 'command_script')}"
    3786        schema = self.sql(expression, "schema")
    3787        schema = f" AS {schema}" if schema else ""
    3788        row_format_after = self.sql(expression, "row_format_after")
    3789        row_format_after = f" {row_format_after}" if row_format_after else ""
    3790        record_reader = self.sql(expression, "record_reader")
    3791        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
    3792        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

    3794    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
    3795        key_block_size = self.sql(expression, "key_block_size")
    3796        if key_block_size:
    3797            return f"KEY_BLOCK_SIZE = {key_block_size}"
    3798
    3799        using = self.sql(expression, "using")
    3800        if using:
    3801            return f"USING {using}"
    3802
    3803        parser = self.sql(expression, "parser")
    3804        if parser:
    3805            return f"WITH PARSER {parser}"
    3806
    3807        comment = self.sql(expression, "comment")
    3808        if comment:
    3809            return f"COMMENT {comment}"
    3810
    3811        visible = expression.args.get("visible")
    3812        if visible is not None:
    3813            return "VISIBLE" if visible else "INVISIBLE"
    3814
    3815        engine_attr = self.sql(expression, "engine_attr")
    3816        if engine_attr:
    3817            return f"ENGINE_ATTRIBUTE = {engine_attr}"
    3818
    3819        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
    3820        if secondary_engine_attr:
    3821            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
    3822
    3823        self.unsupported("Unsupported index constraint option.")
    3824        return ""

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

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

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

    3830    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
    3831        kind = self.sql(expression, "kind")
    3832        kind = f"{kind} INDEX" if kind else "INDEX"
    3833        this = self.sql(expression, "this")
    3834        this = f" {this}" if this else ""
    3835        index_type = self.sql(expression, "index_type")
    3836        index_type = f" USING {index_type}" if index_type else ""
    3837        expressions = self.expressions(expression, flat=True)
    3838        expressions = f" ({expressions})" if expressions else ""
    3839        options = self.expressions(expression, key="options", sep=" ")
    3840        options = f" {options}" if options else ""
    3841        return f"{kind}{this}{index_type}{expressions}{options}"

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

    3843    def nvl2_sql(self, expression: exp.Nvl2) -> str:
    3844        if self.NVL2_SUPPORTED:
    3845            return self.function_fallback_sql(expression)
    3846
    3847        case = exp.Case().when(
    3848            expression.this.is_(exp.null()).not_(copy=False),
    3849            expression.args["true"],
    3850            copy=False,
    3851        )
    3852        else_cond = expression.args.get("false")
    3853        if else_cond:
    3854            case.else_(else_cond, copy=False)
    3855
    3856        return self.sql(case)

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

    3858    def comprehension_sql(self, expression: exp.Comprehension) -> str:
    3859        this = self.sql(expression, "this")
    3860        expr = self.sql(expression, "expression")
    3861        iterator = self.sql(expression, "iterator")
    3862        condition = self.sql(expression, "condition")
    3863        condition = f" IF {condition}" if condition else ""
    3864        return f"{this} FOR {expr} IN {iterator}{condition}"

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

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

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

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

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

    3872    def predict_sql(self, expression: exp.Predict) -> str:
    3873        model = self.sql(expression, "this")
    3874        model = f"MODEL {model}"
    3875        table = self.sql(expression, "expression")
    3876        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
    3877        parameters = self.sql(expression, "params_struct")
    3878        return self.func("PREDICT", model, table, parameters or None)

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

    3880    def forin_sql(self, expression: exp.ForIn) -> str:
    3881        this = self.sql(expression, "this")
    3882        expression_sql = self.sql(expression, "expression")
    3883        return f"FOR {this} DO {expression_sql}"

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

    3885    def refresh_sql(self, expression: exp.Refresh) -> str:
    3886        this = self.sql(expression, "this")
    3887        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
    3888        return f"REFRESH {table}{this}"

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

    3890    def toarray_sql(self, expression: exp.ToArray) -> str:
    3891        arg = expression.this
    3892        if not arg.type:
    3893            from sqlglot.optimizer.annotate_types import annotate_types
    3894
    3895            arg = annotate_types(arg)
    3896
    3897        if arg.is_type(exp.DataType.Type.ARRAY):
    3898            return self.sql(arg)
    3899
    3900        cond_for_null = arg.is_(exp.null())
    3901        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

    3903    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
    3904        this = expression.this
    3905        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
    3906            return self.sql(this)
    3907
    3908        return self.sql(exp.cast(this, exp.DataType.Type.TIME))

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

    3910    def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str:
    3911        this = expression.this
    3912        if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP):
    3913            return self.sql(this)
    3914
    3915        return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect))

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

    3917    def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str:
    3918        this = expression.this
    3919        if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME):
    3920            return self.sql(this)
    3921
    3922        return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect))

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

    3924    def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:
    3925        this = expression.this
    3926        time_format = self.format_time(expression)
    3927
    3928        if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT):
    3929            return self.sql(
    3930                exp.cast(
    3931                    exp.StrToTime(this=this, format=expression.args["format"]),
    3932                    exp.DataType.Type.DATE,
    3933                )
    3934            )
    3935
    3936        if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE):
    3937            return self.sql(this)
    3938
    3939        return self.sql(exp.cast(this, exp.DataType.Type.DATE))

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

    3941    def unixdate_sql(self, expression: exp.UnixDate) -> str:
    3942        return self.sql(
    3943            exp.func(
    3944                "DATEDIFF",
    3945                expression.this,
    3946                exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE),
    3947                "day",
    3948            )
    3949        )

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

    3951    def lastday_sql(self, expression: exp.LastDay) -> str:
    3952        if self.LAST_DAY_SUPPORTS_DATE_PART:
    3953            return self.function_fallback_sql(expression)
    3954
    3955        unit = expression.text("unit")
    3956        if unit and unit != "MONTH":
    3957            self.unsupported("Date parts are not supported in LAST_DAY.")
    3958
    3959        return self.func("LAST_DAY", expression.this)

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

    3961    def dateadd_sql(self, expression: exp.DateAdd) -> str:
    3962        from sqlglot.dialects.dialect import unit_to_str
    3963
    3964        return self.func(
    3965            "DATE_ADD", expression.this, expression.expression, unit_to_str(expression)
    3966        )

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

    3968    def arrayany_sql(self, expression: exp.ArrayAny) -> str:
    3969        if self.CAN_IMPLEMENT_ARRAY_ANY:
    3970            filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression)
    3971            filtered_not_empty = exp.ArraySize(this=filtered).neq(0)
    3972            original_is_empty = exp.ArraySize(this=expression.this).eq(0)
    3973            return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty)))
    3974
    3975        from sqlglot.dialects import Dialect
    3976
    3977        # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect
    3978        if self.dialect.__class__ != Dialect:
    3979            self.unsupported("ARRAY_ANY is unsupported")
    3980
    3981        return self.function_fallback_sql(expression)

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

    3983    def struct_sql(self, expression: exp.Struct) -> str:
    3984        expression.set(
    3985            "expressions",
    3986            [
    3987                exp.alias_(e.expression, e.name if e.this.is_string else e.this)
    3988                if isinstance(e, exp.PropertyEQ)
    3989                else e
    3990                for e in expression.expressions
    3991            ],
    3992        )
    3993
    3994        return self.function_fallback_sql(expression)

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

    3996    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
    3997        low = self.sql(expression, "this")
    3998        high = self.sql(expression, "expression")
    3999
    4000        return f"{low} TO {high}"

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

    4002    def truncatetable_sql(self, expression: exp.TruncateTable) -> str:
    4003        target = "DATABASE" if expression.args.get("is_database") else "TABLE"
    4004        tables = f" {self.expressions(expression)}"
    4005
    4006        exists = " IF EXISTS" if expression.args.get("exists") else ""
    4007
    4008        on_cluster = self.sql(expression, "cluster")
    4009        on_cluster = f" {on_cluster}" if on_cluster else ""
    4010
    4011        identity = self.sql(expression, "identity")
    4012        identity = f" {identity} IDENTITY" if identity else ""
    4013
    4014        option = self.sql(expression, "option")
    4015        option = f" {option}" if option else ""
    4016
    4017        partition = self.sql(expression, "partition")
    4018        partition = f" {partition}" if partition else ""
    4019
    4020        return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"

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

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

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

    4120    def copyparameter_sql(self, expression: exp.CopyParameter) -> str:
    4121        option = self.sql(expression, "this")
    4122
    4123        if expression.expressions:
    4124            upper = option.upper()
    4125
    4126            # Snowflake FILE_FORMAT options are separated by whitespace
    4127            sep = " " if upper == "FILE_FORMAT" else ", "
    4128
    4129            # Databricks copy/format options do not set their list of values with EQ
    4130            op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = "
    4131            values = self.expressions(expression, flat=True, sep=sep)
    4132            return f"{option}{op}({values})"
    4133
    4134        value = self.sql(expression, "expression")
    4135
    4136        if not value:
    4137            return option
    4138
    4139        op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " "
    4140
    4141        return f"{option}{op}{value}"

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

    4143    def credentials_sql(self, expression: exp.Credentials) -> str:
    4144        cred_expr = expression.args.get("credentials")
    4145        if isinstance(cred_expr, exp.Literal):
    4146            # Redshift case: CREDENTIALS <string>
    4147            credentials = self.sql(expression, "credentials")
    4148            credentials = f"CREDENTIALS {credentials}" if credentials else ""
    4149        else:
    4150            # Snowflake case: CREDENTIALS = (...)
    4151            credentials = self.expressions(expression, key="credentials", flat=True, sep=" ")
    4152            credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else ""
    4153
    4154        storage = self.sql(expression, "storage")
    4155        storage = f"STORAGE_INTEGRATION = {storage}" if storage else ""
    4156
    4157        encryption = self.expressions(expression, key="encryption", flat=True, sep=" ")
    4158        encryption = f" ENCRYPTION = ({encryption})" if encryption else ""
    4159
    4160        iam_role = self.sql(expression, "iam_role")
    4161        iam_role = f"IAM_ROLE {iam_role}" if iam_role else ""
    4162
    4163        region = self.sql(expression, "region")
    4164        region = f" REGION {region}" if region else ""
    4165
    4166        return f"{credentials}{storage}{encryption}{iam_role}{region}"

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

    4168    def copy_sql(self, expression: exp.Copy) -> str:
    4169        this = self.sql(expression, "this")
    4170        this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}"
    4171
    4172        credentials = self.sql(expression, "credentials")
    4173        credentials = self.seg(credentials) if credentials else ""
    4174        kind = self.seg("FROM" if expression.args.get("kind") else "TO")
    4175        files = self.expressions(expression, key="files", flat=True)
    4176
    4177        sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " "
    4178        params = self.expressions(
    4179            expression,
    4180            key="params",
    4181            sep=sep,
    4182            new_line=True,
    4183            skip_last=True,
    4184            skip_first=True,
    4185            indent=self.COPY_PARAMS_ARE_WRAPPED,
    4186        )
    4187
    4188        if params:
    4189            if self.COPY_PARAMS_ARE_WRAPPED:
    4190                params = f" WITH ({params})"
    4191            elif not self.pretty:
    4192                params = f" {params}"
    4193
    4194        return f"COPY{this}{kind} {files}{credentials}{params}"

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

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

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

    4199    def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str:
    4200        on_sql = "ON" if expression.args.get("on") else "OFF"
    4201        filter_col: t.Optional[str] = self.sql(expression, "filter_column")
    4202        filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None
    4203        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    4204        retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None
    4205
    4206        if filter_col or retention_period:
    4207            on_sql = self.func("ON", filter_col, retention_period)
    4208
    4209        return f"DATA_DELETION={on_sql}"

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

    4211    def maskingpolicycolumnconstraint_sql(
    4212        self, expression: exp.MaskingPolicyColumnConstraint
    4213    ) -> str:
    4214        this = self.sql(expression, "this")
    4215        expressions = self.expressions(expression, flat=True)
    4216        expressions = f" USING ({expressions})" if expressions else ""
    4217        return f"MASKING POLICY {this}{expressions}"

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

    4219    def gapfill_sql(self, expression: exp.GapFill) -> str:
    4220        this = self.sql(expression, "this")
    4221        this = f"TABLE {this}"
    4222        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

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

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

    4227    def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str:
    4228        this = self.sql(expression, "this")
    4229        expr = expression.expression
    4230
    4231        if isinstance(expr, exp.Func):
    4232            # T-SQL's CLR functions are case sensitive
    4233            expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})"
    4234        else:
    4235            expr = self.sql(expression, "expression")
    4236
    4237        return self.scope_resolution(expr, this)

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

    4239    def parsejson_sql(self, expression: exp.ParseJSON) -> str:
    4240        if self.PARSE_JSON_NAME is None:
    4241            return self.sql(expression.this)
    4242
    4243        return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression)

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

    4245    def rand_sql(self, expression: exp.Rand) -> str:
    4246        lower = self.sql(expression, "lower")
    4247        upper = self.sql(expression, "upper")
    4248
    4249        if lower and upper:
    4250            return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}"
    4251        return self.func("RAND", expression.this)

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

    4253    def changes_sql(self, expression: exp.Changes) -> str:
    4254        information = self.sql(expression, "information")
    4255        information = f"INFORMATION => {information}"
    4256        at_before = self.sql(expression, "at_before")
    4257        at_before = f"{self.seg('')}{at_before}" if at_before else ""
    4258        end = self.sql(expression, "end")
    4259        end = f"{self.seg('')}{end}" if end else ""
    4260
    4261        return f"CHANGES ({information}){at_before}{end}"

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

    4263    def pad_sql(self, expression: exp.Pad) -> str:
    4264        prefix = "L" if expression.args.get("is_left") else "R"
    4265
    4266        fill_pattern = self.sql(expression, "fill_pattern") or None
    4267        if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED:
    4268            fill_pattern = "' '"
    4269
    4270        return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)

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

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

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

    4276    def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str:
    4277        generate_series = exp.GenerateSeries(**expression.args)
    4278
    4279        parent = expression.parent
    4280        if isinstance(parent, (exp.Alias, exp.TableAlias)):
    4281            parent = parent.parent
    4282
    4283        if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)):
    4284            return self.sql(exp.Unnest(expressions=[generate_series]))
    4285
    4286        if isinstance(parent, exp.Select):
    4287            self.unsupported("GenerateSeries projection unnesting is not supported.")
    4288
    4289        return self.sql(generate_series)

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

    4291    def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str:
    4292        exprs = expression.expressions
    4293        if not self.ARRAY_CONCAT_IS_VAR_LEN:
    4294            rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs)
    4295        else:
    4296            rhs = self.expressions(expression)
    4297
    4298        return self.func(name, expression.this, rhs or None)

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

    4300    def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str:
    4301        if self.SUPPORTS_CONVERT_TIMEZONE:
    4302            return self.function_fallback_sql(expression)
    4303
    4304        source_tz = expression.args.get("source_tz")
    4305        target_tz = expression.args.get("target_tz")
    4306        timestamp = expression.args.get("timestamp")
    4307
    4308        if source_tz and timestamp:
    4309            timestamp = exp.AtTimeZone(
    4310                this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz
    4311            )
    4312
    4313        expr = exp.AtTimeZone(this=timestamp, zone=target_tz)
    4314
    4315        return self.sql(expr)

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

    4317    def json_sql(self, expression: exp.JSON) -> str:
    4318        this = self.sql(expression, "this")
    4319        this = f" {this}" if this else ""
    4320
    4321        _with = expression.args.get("with")
    4322
    4323        if _with is None:
    4324            with_sql = ""
    4325        elif not _with:
    4326            with_sql = " WITHOUT"
    4327        else:
    4328            with_sql = " WITH"
    4329
    4330        unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else ""
    4331
    4332        return f"JSON{this}{with_sql}{unique_sql}"

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

    4334    def jsonvalue_sql(self, expression: exp.JSONValue) -> str:
    4335        def _generate_on_options(arg: t.Any) -> str:
    4336            return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}"
    4337
    4338        path = self.sql(expression, "path")
    4339        returning = self.sql(expression, "returning")
    4340        returning = f" RETURNING {returning}" if returning else ""
    4341
    4342        on_condition = self.sql(expression, "on_condition")
    4343        on_condition = f" {on_condition}" if on_condition else ""
    4344
    4345        return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}")

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

    4347    def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str:
    4348        else_ = "ELSE " if expression.args.get("else_") else ""
    4349        condition = self.sql(expression, "expression")
    4350        condition = f"WHEN {condition} THEN " if condition else else_
    4351        insert = self.sql(expression, "this")[len("INSERT") :].strip()
    4352        return f"{condition}{insert}"

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

    4354    def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str:
    4355        kind = self.sql(expression, "kind")
    4356        expressions = self.seg(self.expressions(expression, sep=" "))
    4357        res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}"
    4358        return res

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

    4360    def oncondition_sql(self, expression: exp.OnCondition) -> str:
    4361        # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR"
    4362        empty = expression.args.get("empty")
    4363        empty = (
    4364            f"DEFAULT {empty} ON EMPTY"
    4365            if isinstance(empty, exp.Expression)
    4366            else self.sql(expression, "empty")
    4367        )
    4368
    4369        error = expression.args.get("error")
    4370        error = (
    4371            f"DEFAULT {error} ON ERROR"
    4372            if isinstance(error, exp.Expression)
    4373            else self.sql(expression, "error")
    4374        )
    4375
    4376        if error and empty:
    4377            error = (
    4378                f"{empty} {error}"
    4379                if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR
    4380                else f"{error} {empty}"
    4381            )
    4382            empty = ""
    4383
    4384        null = self.sql(expression, "null")
    4385
    4386        return f"{empty}{error}{null}"

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

    4388    def jsonexists_sql(self, expression: exp.JSONExists) -> str:
    4389        this = self.sql(expression, "this")
    4390        path = self.sql(expression, "path")
    4391
    4392        passing = self.expressions(expression, "passing")
    4393        passing = f" PASSING {passing}" if passing else ""
    4394
    4395        on_condition = self.sql(expression, "on_condition")
    4396        on_condition = f" {on_condition}" if on_condition else ""
    4397
    4398        path = f"{path}{passing}{on_condition}"
    4399
    4400        return self.func("JSON_EXISTS", this, path)

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

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

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

    4427    def apply_sql(self, expression: exp.Apply) -> str:
    4428        this = self.sql(expression, "this")
    4429        expr = self.sql(expression, "expression")
    4430
    4431        return f"{this} APPLY({expr})"

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

    4433    def grant_sql(self, expression: exp.Grant) -> str:
    4434        privileges_sql = self.expressions(expression, key="privileges", flat=True)
    4435
    4436        kind = self.sql(expression, "kind")
    4437        kind = f" {kind}" if kind else ""
    4438
    4439        securable = self.sql(expression, "securable")
    4440        securable = f" {securable}" if securable else ""
    4441
    4442        principals = self.expressions(expression, key="principals", flat=True)
    4443
    4444        grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else ""
    4445
    4446        return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}"

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

    4448    def grantprivilege_sql(self, expression: exp.GrantPrivilege):
    4449        this = self.sql(expression, "this")
    4450        columns = self.expressions(expression, flat=True)
    4451        columns = f"({columns})" if columns else ""
    4452
    4453        return f"{this}{columns}"

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

    4455    def grantprincipal_sql(self, expression: exp.GrantPrincipal):
    4456        this = self.sql(expression, "this")
    4457
    4458        kind = self.sql(expression, "kind")
    4459        kind = f"{kind} " if kind else ""
    4460
    4461        return f"{kind}{this}"

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

    4463    def columns_sql(self, expression: exp.Columns):
    4464        func = self.function_fallback_sql(expression)
    4465        if expression.args.get("unpack"):
    4466            func = f"*{func}"
    4467
    4468        return func

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

    4470    def overlay_sql(self, expression: exp.Overlay):
    4471        this = self.sql(expression, "this")
    4472        expr = self.sql(expression, "expression")
    4473        from_sql = self.sql(expression, "from")
    4474        for_sql = self.sql(expression, "for")
    4475        for_sql = f" FOR {for_sql}" if for_sql else ""
    4476
    4477        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

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

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

    4483    def string_sql(self, expression: exp.String) -> str:
    4484        this = expression.this
    4485        zone = expression.args.get("zone")
    4486
    4487        if zone:
    4488            # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>)
    4489            # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC
    4490            # set for source_tz to transpile the time conversion before the STRING cast
    4491            this = exp.ConvertTimezone(
    4492                source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this
    4493            )
    4494
    4495        return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR))

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

    4497    def median_sql(self, expression: exp.Median):
    4498        if not self.SUPPORTS_MEDIAN:
    4499            return self.sql(
    4500                exp.PercentileCont(this=expression.this, expression=exp.Literal.number(0.5))
    4501            )
    4502
    4503        return self.function_fallback_sql(expression)

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

    4505    def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str:
    4506        filler = self.sql(expression, "this")
    4507        filler = f" {filler}" if filler else ""
    4508        with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT"
    4509        return f"TRUNCATE{filler} {with_count}"

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

    4511    def unixseconds_sql(self, expression: exp.UnixSeconds) -> str:
    4512        if self.SUPPORTS_UNIX_SECONDS:
    4513            return self.function_fallback_sql(expression)
    4514
    4515        start_ts = exp.cast(
    4516            exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ
    4517        )
    4518
    4519        return self.sql(
    4520            exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS"))
    4521        )

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

    4523    def arraysize_sql(self, expression: exp.ArraySize) -> str:
    4524        dim = expression.expression
    4525
    4526        # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension)
    4527        if dim and self.ARRAY_SIZE_DIM_REQUIRED is None:
    4528            if not (dim.is_int and dim.name == "1"):
    4529                self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH")
    4530            dim = None
    4531
    4532        # If dimension is required but not specified, default initialize it
    4533        if self.ARRAY_SIZE_DIM_REQUIRED and not dim:
    4534            dim = exp.Literal.number(1)
    4535
    4536        return self.func(self.ARRAY_SIZE_NAME, expression.this, dim)

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

    4538    def attach_sql(self, expression: exp.Attach) -> str:
    4539        this = self.sql(expression, "this")
    4540        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
    4541        expressions = self.expressions(expression)
    4542        expressions = f" ({expressions})" if expressions else ""
    4543
    4544        return f"ATTACH{exists_sql} {this}{expressions}"

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

    4546    def detach_sql(self, expression: exp.Detach) -> str:
    4547        this = self.sql(expression, "this")
    4548        exists_sql = " IF EXISTS" if expression.args.get("exists") else ""
    4549
    4550        return f"DETACH{exists_sql} {this}"

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

    4552    def attachoption_sql(self, expression: exp.AttachOption) -> str:
    4553        this = self.sql(expression, "this")
    4554        value = self.sql(expression, "expression")
    4555        value = f" {value}" if value else ""
    4556        return f"{this}{value}"

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

    4558    def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str:
    4559        this_sql = self.sql(expression, "this")
    4560        if isinstance(expression.this, exp.Table):
    4561            this_sql = f"TABLE {this_sql}"
    4562
    4563        return self.func(
    4564            "FEATURES_AT_TIME",
    4565            this_sql,
    4566            expression.args.get("time"),
    4567            expression.args.get("num_rows"),
    4568            expression.args.get("ignore_feature_nulls"),
    4569        )

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

    4571    def watermarkcolumnconstraint_sql(self, expression: exp.WatermarkColumnConstraint) -> str:
    4572        return (
    4573            f"WATERMARK FOR {self.sql(expression, 'this')} AS {self.sql(expression, 'expression')}"
    4574        )

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

    4576    def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str:
    4577        encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE"
    4578        encode = f"{encode} {self.sql(expression, 'this')}"
    4579
    4580        properties = expression.args.get("properties")
    4581        if properties:
    4582            encode = f"{encode} {self.properties(properties)}"
    4583
    4584        return encode

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

    4586    def includeproperty_sql(self, expression: exp.IncludeProperty) -> str:
    4587        this = self.sql(expression, "this")
    4588        include = f"INCLUDE {this}"
    4589
    4590        column_def = self.sql(expression, "column_def")
    4591        if column_def:
    4592            include = f"{include} {column_def}"
    4593
    4594        alias = self.sql(expression, "alias")
    4595        if alias:
    4596            include = f"{include} AS {alias}"
    4597
    4598        return include