sqlglot.generator API documentation

Edit on GitHub

# sqlglot.generator

View Source

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

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

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

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

class Generator: View Source

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

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

###### Arguments:

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

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

    679    def __init__(
    680        self,
    681        pretty: t.Optional[bool] = None,
    682        identify: str | bool = False,
    683        normalize: bool = False,
    684        pad: int = 2,
    685        indent: int = 2,
    686        normalize_functions: t.Optional[str | bool] = None,
    687        unsupported_level: ErrorLevel = ErrorLevel.WARN,
    688        max_unsupported: int = 3,
    689        leading_comma: bool = False,
    690        max_text_width: int = 80,
    691        comments: bool = True,
    692        dialect: DialectType = None,
    693    ):
    694        import sqlglot
    695        from sqlglot.dialects import Dialect
    696
    697        self.pretty = pretty if pretty is not None else sqlglot.pretty
    698        self.identify = identify
    699        self.normalize = normalize
    700        self.pad = pad
    701        self._indent = indent
    702        self.unsupported_level = unsupported_level
    703        self.max_unsupported = max_unsupported
    704        self.leading_comma = leading_comma
    705        self.max_text_width = max_text_width
    706        self.comments = comments
    707        self.dialect = Dialect.get_or_raise(dialect)
    708
    709        # This is both a Dialect property and a Generator argument, so we prioritize the latter
    710        self.normalize_functions = (
    711            self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions
    712        )
    713
    714        self.unsupported_messages: t.List[str] = []
    715        self._escaped_quote_end: str = (
    716            self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END
    717        )
    718        self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2
    719
    720        self._next_name = name_sequence("_t")
    721
    722        self._identifier_start = self.dialect.IDENTIFIER_START
    723        self._identifier_end = self.dialect.IDENTIFIER_END
    724
    725        self._quote_json_path_key_using_brackets = True

TRANSFORMS: Dict[Type[sqlglot.expressions.Expression], Callable[..., str]] = {<class 'sqlglot.expressions.JSONPathFilter'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathKey'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathRecursive'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathRoot'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathScript'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSelector'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSlice'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSubscript'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathUnion'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathWildcard'>: <function <lambda>>, <class 'sqlglot.expressions.AllowedValuesProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AnalyzeColumns'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AnalyzeWith'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ArrayContainsAll'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ArrayOverlaps'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AutoRefreshProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.BackupProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CaseSpecificColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Ceil'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CommentColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ConnectByRoot'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.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.Floor'>: <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.Tags'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TemporaryProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Union'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UnloggedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UsingData'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Uuid'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VarMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ViewAttributeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithProcedureOptions'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithSchemaBindingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithOperator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ForceProperty'>: <function Generator.<lambda>>}
NULL_ORDERING_SUPPORTED: Optional[bool] = True
IGNORE_NULLS_IN_FUNC = False
LOCKING_READS_SUPPORTED = False
EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = True
WRAP_DERIVED_VALUES = True
CREATE_FUNCTION_RETURN_AS = True
MATCHED_BY_SOURCE = True
SINGLE_STRING_INTERVAL = False
INTERVAL_ALLOWS_PLURAL_FORM = True
LIMIT_FETCH = 'ALL'
LIMIT_ONLY_LITERALS = False
RENAME_TABLE_WITH_DB = True
GROUPINGS_SEP = ','
INDEX_ON = 'ON'
JOIN_HINTS = True
TABLE_HINTS = True
QUERY_HINTS = True
QUERY_HINT_SEP = ', '
IS_BOOL_ALLOWED = True
DUPLICATE_KEY_UPDATE_WITH_SET = True
LIMIT_IS_TOP = False
RETURNING_END = True
EXTRACT_ALLOWS_QUOTES = True
TZ_TO_WITH_TIME_ZONE = False
NVL2_SUPPORTED = True
SELECT_KINDS: Tuple[str, ...] = ('STRUCT', 'VALUE')
VALUES_AS_TABLE = True
ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = True
UNNEST_WITH_ORDINALITY = True
AGGREGATE_FILTER_SUPPORTED = True
SEMI_ANTI_JOIN_WITH_SIDE = True
COMPUTED_COLUMN_WITH_TYPE = True
SUPPORTS_TABLE_COPY = True
TABLESAMPLE_REQUIRES_PARENS = True
TABLESAMPLE_SIZE_IS_ROWS = True
TABLESAMPLE_KEYWORDS = 'TABLESAMPLE'
TABLESAMPLE_WITH_METHOD = True
TABLESAMPLE_SEED_KEYWORD = 'SEED'
COLLATE_IS_FUNC = False
DATA_TYPE_SPECIFIERS_ALLOWED = False
ENSURE_BOOLS = False
CTE_RECURSIVE_KEYWORD_REQUIRED = True
SUPPORTS_SINGLE_ARG_CONCAT = True
LAST_DAY_SUPPORTS_DATE_PART = True
SUPPORTS_TABLE_ALIAS_COLUMNS = True
UNPIVOT_ALIASES_ARE_IDENTIFIERS = True
JSON_KEY_VALUE_PAIR_SEP = ':'
INSERT_OVERWRITE = ' OVERWRITE TABLE'
SUPPORTS_SELECT_INTO = False
SUPPORTS_UNLOGGED_TABLES = False
SUPPORTS_CREATE_TABLE_LIKE = True
LIKE_PROPERTY_INSIDE_SCHEMA = False
MULTI_ARG_DISTINCT = True
JSON_TYPE_REQUIRED_FOR_EXTRACTION = False
JSON_PATH_BRACKETED_KEY_SUPPORTED = True
JSON_PATH_SINGLE_QUOTE_ESCAPE = False
SUPPORTED_JSON_PATH_PARTS = {<class 'sqlglot.expressions.JSONPathRoot'>, <class 'sqlglot.expressions.JSONPathRecursive'>, <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'>}
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'
ALTER_SET_TYPE = 'SET DATA TYPE'
ARRAY_SIZE_DIM_REQUIRED: Optional[bool] = None
TYPE_MAPPING = {<Type.DATETIME2: 'DATETIME2'>: 'TIMESTAMP', <Type.NCHAR: 'NCHAR'>: 'CHAR', <Type.NVARCHAR: 'NVARCHAR'>: 'VARCHAR', <Type.MEDIUMTEXT: 'MEDIUMTEXT'>: 'TEXT', <Type.LONGTEXT: 'LONGTEXT'>: 'TEXT', <Type.TINYTEXT: 'TINYTEXT'>: 'TEXT', <Type.BLOB: 'BLOB'>: 'VARBINARY', <Type.MEDIUMBLOB: 'MEDIUMBLOB'>: 'BLOB', <Type.LONGBLOB: 'LONGBLOB'>: 'BLOB', <Type.TINYBLOB: 'TINYBLOB'>: 'BLOB', <Type.INET: 'INET'>: 'INET', <Type.ROWVERSION: 'ROWVERSION'>: 'VARBINARY', <Type.SMALLDATETIME: 'SMALLDATETIME'>: 'TIMESTAMP'}
TIME_PART_SINGULARS = {'MICROSECONDS': 'MICROSECOND', 'SECONDS': 'SECOND', 'MINUTES': 'MINUTE', 'HOURS': 'HOUR', 'DAYS': 'DAY', 'WEEKS': 'WEEK', 'MONTHS': 'MONTH', 'QUARTERS': 'QUARTER', 'YEARS': 'YEAR'}
AFTER_HAVING_MODIFIER_TRANSFORMS = {'cluster': <function Generator.<lambda>>, 'distribute': <function Generator.<lambda>>, 'sort': <function Generator.<lambda>>, 'windows': <function Generator.<lambda>>, 'qualify': <function Generator.<lambda>>}
TOKEN_MAPPING: Dict[sqlglot.tokens.TokenType, str] = {}
STRUCT_DELIMITER = ('<', '>')
PARAMETER_TOKEN = '@'
NAMED_PLACEHOLDER_TOKEN = ':'
EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: Set[str] = set()
PROPERTIES_LOCATION = {<class 'sqlglot.expressions.AllowedValuesProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.AlgorithmProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.AutoIncrementProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.AutoRefreshProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.BackupProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.BlockCompressionProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CharacterSetProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ChecksumProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CollateProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Cluster'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ClusteredByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistributedByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DuplicateKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DataBlocksizeProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.DataDeletionProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DefinerProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.DictRange'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DictProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DynamicProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.DistKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistStyleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EmptyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EncodeProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.EngineProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExternalProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.FallbackProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.FileFormatProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.FreespaceProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.GlobalProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.HeapProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.InheritsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.IcebergProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.IncludeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.InputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.IsolatedLoadingProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.JournalProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.LanguageProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LikeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LocationProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LockProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LockingProperty'>: <Location.POST_ALIAS: 'POST_ALIAS'>, <class 'sqlglot.expressions.LogProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.MaterializedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.MergeBlockRatioProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.OnProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OnCommitProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.Order'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OutputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PartitionedByProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.PartitionedOfProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PrimaryKey'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Property'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ReturnsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatDelimitedProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatSerdeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SampleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SchemaCommentProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SecureProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.SecurityProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SerdeProperties'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Set'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SettingsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SetProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.SetConfigProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SharingProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.SequenceProperties'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.SortKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlReadWriteProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StabilityProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.StorageHandlerProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.StreamingTableProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StrictProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Tags'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.TemporaryProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.ToTableProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TransientProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.TransformModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.MergeTreeTTL'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.UnloggedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.ViewAttributeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.VolatileProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.WithDataProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.WithProcedureOptions'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.WithSchemaBindingProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.WithSystemVersioningProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ForceProperty'>: <Location.POST_CREATE: 'POST_CREATE'>}
RESERVED_KEYWORDS: Set[str] = set()
WITH_SEPARATED_COMMENTS: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Command'>, <class 'sqlglot.expressions.Create'>, <class 'sqlglot.expressions.Describe'>, <class 'sqlglot.expressions.Delete'>, <class 'sqlglot.expressions.Drop'>, <class 'sqlglot.expressions.From'>, <class 'sqlglot.expressions.Insert'>, <class 'sqlglot.expressions.Join'>, <class 'sqlglot.expressions.MultitableInserts'>, <class 'sqlglot.expressions.Select'>, <class 'sqlglot.expressions.SetOperation'>, <class 'sqlglot.expressions.Update'>, <class 'sqlglot.expressions.Where'>, <class 'sqlglot.expressions.With'>)
EXCLUDE_COMMENTS: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Binary'>, <class 'sqlglot.expressions.SetOperation'>)
UNWRAPPED_INTERVAL_VALUES: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Column'>, <class 'sqlglot.expressions.Literal'>, <class 'sqlglot.expressions.Neg'>, <class 'sqlglot.expressions.Paren'>)
PARAMETERIZABLE_TEXT_TYPES = {<Type.CHAR: 'CHAR'>, <Type.NCHAR: 'NCHAR'>, <Type.VARCHAR: 'VARCHAR'>, <Type.NVARCHAR: 'NVARCHAR'>}
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

    727    def generate(self, expression: exp.Expression, copy: bool = True) -> str:
    728        """
    729        Generates the SQL string corresponding to the given syntax tree.
    730
    731        Args:
    732            expression: The syntax tree.
    733            copy: Whether to copy the expression. The generator performs mutations so
    734                it is safer to copy.
    735
    736        Returns:
    737            The SQL string corresponding to `expression`.
    738        """
    739        if copy:
    740            expression = expression.copy()
    741
    742        expression = self.preprocess(expression)
    743
    744        self.unsupported_messages = []
    745        sql = self.sql(expression).strip()
    746
    747        if self.pretty:
    748            sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n")
    749
    750        if self.unsupported_level == ErrorLevel.IGNORE:
    751            return sql
    752
    753        if self.unsupported_level == ErrorLevel.WARN:
    754            for msg in self.unsupported_messages:
    755                logger.warning(msg)
    756        elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages:
    757            raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported))
    758
    759        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

    761    def preprocess(self, expression: exp.Expression) -> exp.Expression:
    762        """Apply generic preprocessing transformations to a given expression."""
    763        expression = self._move_ctes_to_top_level(expression)
    764
    765        if self.ENSURE_BOOLS:
    766            from sqlglot.transforms import ensure_bools
    767
    768            expression = ensure_bools(expression)
    769
    770        return expression

Apply generic preprocessing transformations to a given expression.

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

    783    def unsupported(self, message: str) -> None:
    784        if self.unsupported_level == ErrorLevel.IMMEDIATE:
    785            raise UnsupportedError(message)
    786        self.unsupported_messages.append(message)

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

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

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

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

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

    794    def pad_comment(self, comment: str) -> str:
    795        comment = " " + comment if comment[0].strip() else comment
    796        comment = comment + " " if comment[-1].strip() else comment
    797        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

    799    def maybe_comment(
    800        self,
    801        sql: str,
    802        expression: t.Optional[exp.Expression] = None,
    803        comments: t.Optional[t.List[str]] = None,
    804        separated: bool = False,
    805    ) -> str:
    806        comments = (
    807            ((expression and expression.comments) if comments is None else comments)  # type: ignore
    808            if self.comments
    809            else None
    810        )
    811
    812        if not comments or isinstance(expression, self.EXCLUDE_COMMENTS):
    813            return sql
    814
    815        comments_sql = " ".join(
    816            f"/*{self.pad_comment(comment)}*/" for comment in comments if comment
    817        )
    818
    819        if not comments_sql:
    820            return sql
    821
    822        comments_sql = self._replace_line_breaks(comments_sql)
    823
    824        if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS):
    825            return (
    826                f"{self.sep()}{comments_sql}{sql}"
    827                if not sql or sql[0].isspace()
    828                else f"{comments_sql}{self.sep()}{sql}"
    829            )
    830
    831        return f"{sql} {comments_sql}"

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

    833    def wrap(self, expression: exp.Expression | str) -> str:
    834        this_sql = (
    835            self.sql(expression)
    836            if isinstance(expression, exp.UNWRAPPED_QUERIES)
    837            else self.sql(expression, "this")
    838        )
    839        if not this_sql:
    840            return "()"
    841
    842        this_sql = self.indent(this_sql, level=1, pad=0)
    843        return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"

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

    845    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
    846        original = self.identify
    847        self.identify = False
    848        result = func(*args, **kwargs)
    849        self.identify = original
    850        return result

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

    852    def normalize_func(self, name: str) -> str:
    853        if self.normalize_functions == "upper" or self.normalize_functions is True:
    854            return name.upper()
    855        if self.normalize_functions == "lower":
    856            return name.lower()
    857        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

    859    def indent(
    860        self,
    861        sql: str,
    862        level: int = 0,
    863        pad: t.Optional[int] = None,
    864        skip_first: bool = False,
    865        skip_last: bool = False,
    866    ) -> str:
    867        if not self.pretty or not sql:
    868            return sql
    869
    870        pad = self.pad if pad is None else pad
    871        lines = sql.split("\n")
    872
    873        return "\n".join(
    874            (
    875                line
    876                if (skip_first and i == 0) or (skip_last and i == len(lines) - 1)
    877                else f"{' ' * (level * self._indent + pad)}{line}"
    878            )
    879            for i, line in enumerate(lines)
    880        )

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

    882    def sql(
    883        self,
    884        expression: t.Optional[str | exp.Expression],
    885        key: t.Optional[str] = None,
    886        comment: bool = True,
    887    ) -> str:
    888        if not expression:
    889            return ""
    890
    891        if isinstance(expression, str):
    892            return expression
    893
    894        if key:
    895            value = expression.args.get(key)
    896            if value:
    897                return self.sql(value)
    898            return ""
    899
    900        transform = self.TRANSFORMS.get(expression.__class__)
    901
    902        if callable(transform):
    903            sql = transform(self, expression)
    904        elif isinstance(expression, exp.Expression):
    905            exp_handler_name = f"{expression.key}_sql"
    906
    907            if hasattr(self, exp_handler_name):
    908                sql = getattr(self, exp_handler_name)(expression)
    909            elif isinstance(expression, exp.Func):
    910                sql = self.function_fallback_sql(expression)
    911            elif isinstance(expression, exp.Property):
    912                sql = self.property_sql(expression)
    913            else:
    914                raise ValueError(f"Unsupported expression type {expression.__class__.__name__}")
    915        else:
    916            raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}")
    917
    918        return self.maybe_comment(sql, expression) if self.comments and comment else sql

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

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

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

    925    def cache_sql(self, expression: exp.Cache) -> str:
    926        lazy = " LAZY" if expression.args.get("lazy") else ""
    927        table = self.sql(expression, "this")
    928        options = expression.args.get("options")
    929        options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else ""
    930        sql = self.sql(expression, "expression")
    931        sql = f" AS{self.sep()}{sql}" if sql else ""
    932        sql = f"CACHE{lazy} TABLE {table}{options}{sql}"
    933        return self.prepend_ctes(expression, sql)

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

    935    def characterset_sql(self, expression: exp.CharacterSet) -> str:
    936        if isinstance(expression.parent, exp.Cast):
    937            return f"CHAR CHARACTER SET {self.sql(expression, 'this')}"
    938        default = "DEFAULT " if expression.args.get("default") else ""
    939        return f"{default}CHARACTER SET={self.sql(expression, 'this')}"

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

    941    def column_parts(self, expression: exp.Column) -> str:
    942        return ".".join(
    943            self.sql(part)
    944            for part in (
    945                expression.args.get("catalog"),
    946                expression.args.get("db"),
    947                expression.args.get("table"),
    948                expression.args.get("this"),
    949            )
    950            if part
    951        )

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

    953    def column_sql(self, expression: exp.Column) -> str:
    954        join_mark = " (+)" if expression.args.get("join_mark") else ""
    955
    956        if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS:
    957            join_mark = ""
    958            self.unsupported("Outer join syntax using the (+) operator is not supported.")
    959
    960        return f"{self.column_parts(expression)}{join_mark}"

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

    962    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
    963        this = self.sql(expression, "this")
    964        this = f" {this}" if this else ""
    965        position = self.sql(expression, "position")
    966        return f"{position}{this}"

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

    968    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
    969        column = self.sql(expression, "this")
    970        kind = self.sql(expression, "kind")
    971        constraints = self.expressions(expression, key="constraints", sep=" ", flat=True)
    972        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
    973        kind = f"{sep}{kind}" if kind else ""
    974        constraints = f" {constraints}" if constraints else ""
    975        position = self.sql(expression, "position")
    976        position = f" {position}" if position else ""
    977
    978        if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE:
    979            kind = ""
    980
    981        return f"{exists}{column}{kind}{constraints}{position}"

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

    983    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
    984        this = self.sql(expression, "this")
    985        kind_sql = self.sql(expression, "kind").strip()
    986        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql

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

    988    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
    989        this = self.sql(expression, "this")
    990        if expression.args.get("not_null"):
    991            persisted = " PERSISTED NOT NULL"
    992        elif expression.args.get("persisted"):
    993            persisted = " PERSISTED"
    994        else:
    995            persisted = ""
    996        return f"AS {this}{persisted}"

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

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

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

    1001    def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str:
    1002        if isinstance(expression.this, list):
    1003            this = self.wrap(self.expressions(expression, key="this", flat=True))
    1004        else:
    1005            this = self.sql(expression, "this")
    1006
    1007        return f"COMPRESS {this}"

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

    1009    def generatedasidentitycolumnconstraint_sql(
    1010        self, expression: exp.GeneratedAsIdentityColumnConstraint
    1011    ) -> str:
    1012        this = ""
    1013        if expression.this is not None:
    1014            on_null = " ON NULL" if expression.args.get("on_null") else ""
    1015            this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}"
    1016
    1017        start = expression.args.get("start")
    1018        start = f"START WITH {start}" if start else ""
    1019        increment = expression.args.get("increment")
    1020        increment = f" INCREMENT BY {increment}" if increment else ""
    1021        minvalue = expression.args.get("minvalue")
    1022        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    1023        maxvalue = expression.args.get("maxvalue")
    1024        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    1025        cycle = expression.args.get("cycle")
    1026        cycle_sql = ""
    1027
    1028        if cycle is not None:
    1029            cycle_sql = f"{' NO' if not cycle else ''} CYCLE"
    1030            cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql
    1031
    1032        sequence_opts = ""
    1033        if start or increment or cycle_sql:
    1034            sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}"
    1035            sequence_opts = f" ({sequence_opts.strip()})"
    1036
    1037        expr = self.sql(expression, "expression")
    1038        expr = f"({expr})" if expr else "IDENTITY"
    1039
    1040        return f"GENERATED{this} AS {expr}{sequence_opts}"

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

    1042    def generatedasrowcolumnconstraint_sql(
    1043        self, expression: exp.GeneratedAsRowColumnConstraint
    1044    ) -> str:
    1045        start = "START" if expression.args.get("start") else "END"
    1046        hidden = " HIDDEN" if expression.args.get("hidden") else ""
    1047        return f"GENERATED ALWAYS AS ROW {start}{hidden}"

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

    1049    def periodforsystemtimeconstraint_sql(
    1050        self, expression: exp.PeriodForSystemTimeConstraint
    1051    ) -> str:
    1052        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

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

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

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

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

    1060    def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str:
    1061        desc = expression.args.get("desc")
    1062        if desc is not None:
    1063            return f"PRIMARY KEY{' DESC' if desc else ' ASC'}"
    1064        return "PRIMARY KEY"

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

    1066    def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str:
    1067        this = self.sql(expression, "this")
    1068        this = f" {this}" if this else ""
    1069        index_type = expression.args.get("index_type")
    1070        index_type = f" USING {index_type}" if index_type else ""
    1071        on_conflict = self.sql(expression, "on_conflict")
    1072        on_conflict = f" {on_conflict}" if on_conflict else ""
    1073        nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else ""
    1074        return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}"

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

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

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

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

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

    1188    def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str:
    1189        start = self.sql(expression, "start")
    1190        start = f"START WITH {start}" if start else ""
    1191        increment = self.sql(expression, "increment")
    1192        increment = f" INCREMENT BY {increment}" if increment else ""
    1193        minvalue = self.sql(expression, "minvalue")
    1194        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    1195        maxvalue = self.sql(expression, "maxvalue")
    1196        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    1197        owned = self.sql(expression, "owned")
    1198        owned = f" OWNED BY {owned}" if owned else ""
    1199
    1200        cache = expression.args.get("cache")
    1201        if cache is None:
    1202            cache_str = ""
    1203        elif cache is True:
    1204            cache_str = " CACHE"
    1205        else:
    1206            cache_str = f" CACHE {cache}"
    1207
    1208        options = self.expressions(expression, key="options", flat=True, sep=" ")
    1209        options = f" {options}" if options else ""
    1210
    1211        return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip()

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

    1213    def clone_sql(self, expression: exp.Clone) -> str:
    1214        this = self.sql(expression, "this")
    1215        shallow = "SHALLOW " if expression.args.get("shallow") else ""
    1216        keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE"
    1217        return f"{shallow}{keyword} {this}"

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

    1219    def describe_sql(self, expression: exp.Describe) -> str:
    1220        style = expression.args.get("style")
    1221        style = f" {style}" if style else ""
    1222        partition = self.sql(expression, "partition")
    1223        partition = f" {partition}" if partition else ""
    1224        format = self.sql(expression, "format")
    1225        format = f" {format}" if format else ""
    1226
    1227        return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}"

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

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

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

    1233    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
    1234        with_ = self.sql(expression, "with")
    1235        if with_:
    1236            sql = f"{with_}{self.sep()}{sql}"
    1237        return sql

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

    1239    def with_sql(self, expression: exp.With) -> str:
    1240        sql = self.expressions(expression, flat=True)
    1241        recursive = (
    1242            "RECURSIVE "
    1243            if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive")
    1244            else ""
    1245        )
    1246        search = self.sql(expression, "search")
    1247        search = f" {search}" if search else ""
    1248
    1249        return f"WITH {recursive}{sql}{search}"

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

    1251    def cte_sql(self, expression: exp.CTE) -> str:
    1252        alias = expression.args.get("alias")
    1253        if alias:
    1254            alias.add_comments(expression.pop_comments())
    1255
    1256        alias_sql = self.sql(expression, "alias")
    1257
    1258        materialized = expression.args.get("materialized")
    1259        if materialized is False:
    1260            materialized = "NOT MATERIALIZED "
    1261        elif materialized:
    1262            materialized = "MATERIALIZED "
    1263
    1264        return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}"

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

    1266    def tablealias_sql(self, expression: exp.TableAlias) -> str:
    1267        alias = self.sql(expression, "this")
    1268        columns = self.expressions(expression, key="columns", flat=True)
    1269        columns = f"({columns})" if columns else ""
    1270
    1271        if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS:
    1272            columns = ""
    1273            self.unsupported("Named columns are not supported in table alias.")
    1274
    1275        if not alias and not self.dialect.UNNEST_COLUMN_ONLY:
    1276            alias = self._next_name()
    1277
    1278        return f"{alias}{columns}"

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

    1280    def bitstring_sql(self, expression: exp.BitString) -> str:
    1281        this = self.sql(expression, "this")
    1282        if self.dialect.BIT_START:
    1283            return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}"
    1284        return f"{int(this, 2)}"

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

    1286    def hexstring_sql(
    1287        self, expression: exp.HexString, binary_function_repr: t.Optional[str] = None
    1288    ) -> str:
    1289        this = self.sql(expression, "this")
    1290        is_integer_type = expression.args.get("is_integer")
    1291
    1292        if (is_integer_type and not self.dialect.HEX_STRING_IS_INTEGER_TYPE) or (
    1293            not self.dialect.HEX_START and not binary_function_repr
    1294        ):
    1295            # Integer representation will be returned if:
    1296            # - The read dialect treats the hex value as integer literal but not the write
    1297            # - The transpilation is not supported (write dialect hasn't set HEX_START or the param flag)
    1298            return f"{int(this, 16)}"
    1299
    1300        if not is_integer_type:
    1301            # Read dialect treats the hex value as BINARY/BLOB
    1302            if binary_function_repr:
    1303                # The write dialect supports the transpilation to its equivalent BINARY/BLOB
    1304                return self.func(binary_function_repr, exp.Literal.string(this))
    1305            if self.dialect.HEX_STRING_IS_INTEGER_TYPE:
    1306                # The write dialect does not support the transpilation, it'll treat the hex value as INTEGER
    1307                self.unsupported("Unsupported transpilation from BINARY/BLOB hex string")
    1308
    1309        return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"

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

    1311    def bytestring_sql(self, expression: exp.ByteString) -> str:
    1312        this = self.sql(expression, "this")
    1313        if self.dialect.BYTE_START:
    1314            return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}"
    1315        return this

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

    1317    def unicodestring_sql(self, expression: exp.UnicodeString) -> str:
    1318        this = self.sql(expression, "this")
    1319        escape = expression.args.get("escape")
    1320
    1321        if self.dialect.UNICODE_START:
    1322            escape_substitute = r"\\\1"
    1323            left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END
    1324        else:
    1325            escape_substitute = r"\\u\1"
    1326            left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END
    1327
    1328        if escape:
    1329            escape_pattern = re.compile(rf"{escape.name}(\d+)")
    1330            escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else ""
    1331        else:
    1332            escape_pattern = ESCAPED_UNICODE_RE
    1333            escape_sql = ""
    1334
    1335        if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE):
    1336            this = escape_pattern.sub(escape_substitute, this)
    1337
    1338        return f"{left_quote}{this}{right_quote}{escape_sql}"

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

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

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

    1344    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
    1345        this = self.sql(expression, "this")
    1346        specifier = self.sql(expression, "expression")
    1347        specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else ""
    1348        return f"{this}{specifier}"

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

    1350    def datatype_sql(self, expression: exp.DataType) -> str:
    1351        nested = ""
    1352        values = ""
    1353        interior = self.expressions(expression, flat=True)
    1354
    1355        type_value = expression.this
    1356        if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"):
    1357            type_sql = self.sql(expression, "kind")
    1358        else:
    1359            type_sql = (
    1360                self.TYPE_MAPPING.get(type_value, type_value.value)
    1361                if isinstance(type_value, exp.DataType.Type)
    1362                else type_value
    1363            )
    1364
    1365        if interior:
    1366            if expression.args.get("nested"):
    1367                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
    1368                if expression.args.get("values") is not None:
    1369                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
    1370                    values = self.expressions(expression, key="values", flat=True)
    1371                    values = f"{delimiters[0]}{values}{delimiters[1]}"
    1372            elif type_value == exp.DataType.Type.INTERVAL:
    1373                nested = f" {interior}"
    1374            else:
    1375                nested = f"({interior})"
    1376
    1377        type_sql = f"{type_sql}{nested}{values}"
    1378        if self.TZ_TO_WITH_TIME_ZONE and type_value in (
    1379            exp.DataType.Type.TIMETZ,
    1380            exp.DataType.Type.TIMESTAMPTZ,
    1381        ):
    1382            type_sql = f"{type_sql} WITH TIME ZONE"
    1383
    1384        return type_sql

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

    1386    def directory_sql(self, expression: exp.Directory) -> str:
    1387        local = "LOCAL " if expression.args.get("local") else ""
    1388        row_format = self.sql(expression, "row_format")
    1389        row_format = f" {row_format}" if row_format else ""
    1390        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"

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

    1392    def delete_sql(self, expression: exp.Delete) -> str:
    1393        this = self.sql(expression, "this")
    1394        this = f" FROM {this}" if this else ""
    1395        using = self.sql(expression, "using")
    1396        using = f" USING {using}" if using else ""
    1397        cluster = self.sql(expression, "cluster")
    1398        cluster = f" {cluster}" if cluster else ""
    1399        where = self.sql(expression, "where")
    1400        returning = self.sql(expression, "returning")
    1401        limit = self.sql(expression, "limit")
    1402        tables = self.expressions(expression, key="tables")
    1403        tables = f" {tables}" if tables else ""
    1404        if self.RETURNING_END:
    1405            expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}"
    1406        else:
    1407            expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}"
    1408        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")

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

    1410    def drop_sql(self, expression: exp.Drop) -> str:
    1411        this = self.sql(expression, "this")
    1412        expressions = self.expressions(expression, flat=True)
    1413        expressions = f" ({expressions})" if expressions else ""
    1414        kind = expression.args["kind"]
    1415        kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind
    1416        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    1417        concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else ""
    1418        on_cluster = self.sql(expression, "cluster")
    1419        on_cluster = f" {on_cluster}" if on_cluster else ""
    1420        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    1421        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    1422        cascade = " CASCADE" if expression.args.get("cascade") else ""
    1423        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
    1424        purge = " PURGE" if expression.args.get("purge") else ""
    1425        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

    1427    def set_operation(self, expression: exp.SetOperation) -> str:
    1428        op_type = type(expression)
    1429        op_name = op_type.key.upper()
    1430
    1431        distinct = expression.args.get("distinct")
    1432        if (
    1433            distinct is False
    1434            and op_type in (exp.Except, exp.Intersect)
    1435            and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE
    1436        ):
    1437            self.unsupported(f"{op_name} ALL is not supported")
    1438
    1439        default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type]
    1440
    1441        if distinct is None:
    1442            distinct = default_distinct
    1443            if distinct is None:
    1444                self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified")
    1445
    1446        if distinct is default_distinct:
    1447            kind = ""
    1448        else:
    1449            kind = " DISTINCT" if distinct else " ALL"
    1450
    1451        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1452        return f"{op_name}{kind}{by_name}"

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

    1454    def set_operations(self, expression: exp.SetOperation) -> str:
    1455        if not self.SET_OP_MODIFIERS:
    1456            limit = expression.args.get("limit")
    1457            order = expression.args.get("order")
    1458
    1459            if limit or order:
    1460                select = self._move_ctes_to_top_level(
    1461                    exp.subquery(expression, "_l_0", copy=False).select("*", copy=False)
    1462                )
    1463
    1464                if limit:
    1465                    select = select.limit(limit.pop(), copy=False)
    1466                if order:
    1467                    select = select.order_by(order.pop(), copy=False)
    1468                return self.sql(select)
    1469
    1470        sqls: t.List[str] = []
    1471        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    1472
    1473        while stack:
    1474            node = stack.pop()
    1475
    1476            if isinstance(node, exp.SetOperation):
    1477                stack.append(node.expression)
    1478                stack.append(
    1479                    self.maybe_comment(
    1480                        self.set_operation(node), comments=node.comments, separated=True
    1481                    )
    1482                )
    1483                stack.append(node.this)
    1484            else:
    1485                sqls.append(self.sql(node))
    1486
    1487        this = self.sep().join(sqls)
    1488        this = self.query_modifiers(expression, this)
    1489        return self.prepend_ctes(expression, this)

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

    1491    def fetch_sql(self, expression: exp.Fetch) -> str:
    1492        direction = expression.args.get("direction")
    1493        direction = f" {direction}" if direction else ""
    1494        count = self.sql(expression, "count")
    1495        count = f" {count}" if count else ""
    1496        limit_options = self.sql(expression, "limit_options")
    1497        limit_options = f"{limit_options}" if limit_options else " ROWS ONLY"
    1498        return f"{self.seg('FETCH')}{direction}{count}{limit_options}"

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

    1500    def limitoptions_sql(self, expression: exp.LimitOptions) -> str:
    1501        percent = " PERCENT" if expression.args.get("percent") else ""
    1502        rows = " ROWS" if expression.args.get("rows") else ""
    1503        with_ties = " WITH TIES" if expression.args.get("with_ties") else ""
    1504        if not with_ties and rows:
    1505            with_ties = " ONLY"
    1506        return f"{percent}{rows}{with_ties}"

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

    1508    def filter_sql(self, expression: exp.Filter) -> str:
    1509        if self.AGGREGATE_FILTER_SUPPORTED:
    1510            this = self.sql(expression, "this")
    1511            where = self.sql(expression, "expression").strip()
    1512            return f"{this} FILTER({where})"
    1513
    1514        agg = expression.this
    1515        agg_arg = agg.this
    1516        cond = expression.expression.this
    1517        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
    1518        return self.sql(agg)

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

    1520    def hint_sql(self, expression: exp.Hint) -> str:
    1521        if not self.QUERY_HINTS:
    1522            self.unsupported("Hints are not supported")
    1523            return ""
    1524
    1525        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"

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

    1527    def indexparameters_sql(self, expression: exp.IndexParameters) -> str:
    1528        using = self.sql(expression, "using")
    1529        using = f" USING {using}" if using else ""
    1530        columns = self.expressions(expression, key="columns", flat=True)
    1531        columns = f"({columns})" if columns else ""
    1532        partition_by = self.expressions(expression, key="partition_by", flat=True)
    1533        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
    1534        where = self.sql(expression, "where")
    1535        include = self.expressions(expression, key="include", flat=True)
    1536        if include:
    1537            include = f" INCLUDE ({include})"
    1538        with_storage = self.expressions(expression, key="with_storage", flat=True)
    1539        with_storage = f" WITH ({with_storage})" if with_storage else ""
    1540        tablespace = self.sql(expression, "tablespace")
    1541        tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else ""
    1542        on = self.sql(expression, "on")
    1543        on = f" ON {on}" if on else ""
    1544
    1545        return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"

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

    1547    def index_sql(self, expression: exp.Index) -> str:
    1548        unique = "UNIQUE " if expression.args.get("unique") else ""
    1549        primary = "PRIMARY " if expression.args.get("primary") else ""
    1550        amp = "AMP " if expression.args.get("amp") else ""
    1551        name = self.sql(expression, "this")
    1552        name = f"{name} " if name else ""
    1553        table = self.sql(expression, "table")
    1554        table = f"{self.INDEX_ON} {table}" if table else ""
    1555
    1556        index = "INDEX " if not table else ""
    1557
    1558        params = self.sql(expression, "params")
    1559        return f"{unique}{primary}{amp}{index}{name}{table}{params}"

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

    1561    def identifier_sql(self, expression: exp.Identifier) -> str:
    1562        text = expression.name
    1563        lower = text.lower()
    1564        text = lower if self.normalize and not expression.quoted else text
    1565        text = text.replace(self._identifier_end, self._escaped_identifier_end)
    1566        if (
    1567            expression.quoted
    1568            or self.dialect.can_identify(text, self.identify)
    1569            or lower in self.RESERVED_KEYWORDS
    1570            or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
    1571        ):
    1572            text = f"{self._identifier_start}{text}{self._identifier_end}"
    1573        return text

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

    1575    def hex_sql(self, expression: exp.Hex) -> str:
    1576        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1577        if self.dialect.HEX_LOWERCASE:
    1578            text = self.func("LOWER", text)
    1579
    1580        return text

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

    1582    def lowerhex_sql(self, expression: exp.LowerHex) -> str:
    1583        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1584        if not self.dialect.HEX_LOWERCASE:
    1585            text = self.func("LOWER", text)
    1586        return text

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

    1588    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    1589        input_format = self.sql(expression, "input_format")
    1590        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    1591        output_format = self.sql(expression, "output_format")
    1592        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    1593        return self.sep().join((input_format, output_format))

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

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

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

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

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

    1603    def properties_sql(self, expression: exp.Properties) -> str:
    1604        root_properties = []
    1605        with_properties = []
    1606
    1607        for p in expression.expressions:
    1608            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1609            if p_loc == exp.Properties.Location.POST_WITH:
    1610                with_properties.append(p)
    1611            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    1612                root_properties.append(p)
    1613
    1614        root_props = self.root_properties(exp.Properties(expressions=root_properties))
    1615        with_props = self.with_properties(exp.Properties(expressions=with_properties))
    1616
    1617        if root_props and with_props and not self.pretty:
    1618            with_props = " " + with_props
    1619
    1620        return root_props + with_props

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

    1622    def root_properties(self, properties: exp.Properties) -> str:
    1623        if properties.expressions:
    1624            return self.expressions(properties, indent=False, sep=" ")
    1625        return ""

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

    1627    def properties(
    1628        self,
    1629        properties: exp.Properties,
    1630        prefix: str = "",
    1631        sep: str = ", ",
    1632        suffix: str = "",
    1633        wrapped: bool = True,
    1634    ) -> str:
    1635        if properties.expressions:
    1636            expressions = self.expressions(properties, sep=sep, indent=False)
    1637            if expressions:
    1638                expressions = self.wrap(expressions) if wrapped else expressions
    1639                return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}"
    1640        return ""

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

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

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

    1645    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
    1646        properties_locs = defaultdict(list)
    1647        for p in properties.expressions:
    1648            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1649            if p_loc != exp.Properties.Location.UNSUPPORTED:
    1650                properties_locs[p_loc].append(p)
    1651            else:
    1652                self.unsupported(f"Unsupported property {p.key}")
    1653
    1654        return properties_locs

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

    1656    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
    1657        if isinstance(expression.this, exp.Dot):
    1658            return self.sql(expression, "this")
    1659        return f"'{expression.name}'" if string_key else expression.name

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

    1661    def property_sql(self, expression: exp.Property) -> str:
    1662        property_cls = expression.__class__
    1663        if property_cls == exp.Property:
    1664            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
    1665
    1666        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    1667        if not property_name:
    1668            self.unsupported(f"Unsupported property {expression.key}")
    1669
    1670        return f"{property_name}={self.sql(expression, 'this')}"

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

    1672    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
    1673        if self.SUPPORTS_CREATE_TABLE_LIKE:
    1674            options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
    1675            options = f" {options}" if options else ""
    1676
    1677            like = f"LIKE {self.sql(expression, 'this')}{options}"
    1678            if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema):
    1679                like = f"({like})"
    1680
    1681            return like
    1682
    1683        if expression.expressions:
    1684            self.unsupported("Transpilation of LIKE property options is unsupported")
    1685
    1686        select = exp.select("*").from_(expression.this).limit(0)
    1687        return f"AS {self.sql(select)}"

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

    1689    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1690        no = "NO " if expression.args.get("no") else ""
    1691        protection = " PROTECTION" if expression.args.get("protection") else ""
    1692        return f"{no}FALLBACK{protection}"

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

    1694    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1695        no = "NO " if expression.args.get("no") else ""
    1696        local = expression.args.get("local")
    1697        local = f"{local} " if local else ""
    1698        dual = "DUAL " if expression.args.get("dual") else ""
    1699        before = "BEFORE " if expression.args.get("before") else ""
    1700        after = "AFTER " if expression.args.get("after") else ""
    1701        return f"{no}{local}{dual}{before}{after}JOURNAL"

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

    1703    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1704        freespace = self.sql(expression, "this")
    1705        percent = " PERCENT" if expression.args.get("percent") else ""
    1706        return f"FREESPACE={freespace}{percent}"

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

    1708    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1709        if expression.args.get("default"):
    1710            property = "DEFAULT"
    1711        elif expression.args.get("on"):
    1712            property = "ON"
    1713        else:
    1714            property = "OFF"
    1715        return f"CHECKSUM={property}"

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

    1717    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1718        if expression.args.get("no"):
    1719            return "NO MERGEBLOCKRATIO"
    1720        if expression.args.get("default"):
    1721            return "DEFAULT MERGEBLOCKRATIO"
    1722
    1723        percent = " PERCENT" if expression.args.get("percent") else ""
    1724        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"

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

    1726    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1727        default = expression.args.get("default")
    1728        minimum = expression.args.get("minimum")
    1729        maximum = expression.args.get("maximum")
    1730        if default or minimum or maximum:
    1731            if default:
    1732                prop = "DEFAULT"
    1733            elif minimum:
    1734                prop = "MINIMUM"
    1735            else:
    1736                prop = "MAXIMUM"
    1737            return f"{prop} DATABLOCKSIZE"
    1738        units = expression.args.get("units")
    1739        units = f" {units}" if units else ""
    1740        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"

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

    1742    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1743        autotemp = expression.args.get("autotemp")
    1744        always = expression.args.get("always")
    1745        default = expression.args.get("default")
    1746        manual = expression.args.get("manual")
    1747        never = expression.args.get("never")
    1748
    1749        if autotemp is not None:
    1750            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1751        elif always:
    1752            prop = "ALWAYS"
    1753        elif default:
    1754            prop = "DEFAULT"
    1755        elif manual:
    1756            prop = "MANUAL"
    1757        elif never:
    1758            prop = "NEVER"
    1759        return f"BLOCKCOMPRESSION={prop}"

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

    1761    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1762        no = expression.args.get("no")
    1763        no = " NO" if no else ""
    1764        concurrent = expression.args.get("concurrent")
    1765        concurrent = " CONCURRENT" if concurrent else ""
    1766        target = self.sql(expression, "target")
    1767        target = f" {target}" if target else ""
    1768        return f"WITH{no}{concurrent} ISOLATED LOADING{target}"

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

    1770    def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str:
    1771        if isinstance(expression.this, list):
    1772            return f"IN ({self.expressions(expression, key='this', flat=True)})"
    1773        if expression.this:
    1774            modulus = self.sql(expression, "this")
    1775            remainder = self.sql(expression, "expression")
    1776            return f"WITH (MODULUS {modulus}, REMAINDER {remainder})"
    1777
    1778        from_expressions = self.expressions(expression, key="from_expressions", flat=True)
    1779        to_expressions = self.expressions(expression, key="to_expressions", flat=True)
    1780        return f"FROM ({from_expressions}) TO ({to_expressions})"

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

    1782    def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str:
    1783        this = self.sql(expression, "this")
    1784
    1785        for_values_or_default = expression.expression
    1786        if isinstance(for_values_or_default, exp.PartitionBoundSpec):
    1787            for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}"
    1788        else:
    1789            for_values_or_default = " DEFAULT"
    1790
    1791        return f"PARTITION OF {this}{for_values_or_default}"

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

    1793    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1794        kind = expression.args.get("kind")
    1795        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1796        for_or_in = expression.args.get("for_or_in")
    1797        for_or_in = f" {for_or_in}" if for_or_in else ""
    1798        lock_type = expression.args.get("lock_type")
    1799        override = " OVERRIDE" if expression.args.get("override") else ""
    1800        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"

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

    1802    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1803        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1804        statistics = expression.args.get("statistics")
    1805        statistics_sql = ""
    1806        if statistics is not None:
    1807            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1808        return f"{data_sql}{statistics_sql}"

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

    1810    def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str:
    1811        this = self.sql(expression, "this")
    1812        this = f"HISTORY_TABLE={this}" if this else ""
    1813        data_consistency: t.Optional[str] = self.sql(expression, "data_consistency")
    1814        data_consistency = (
    1815            f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None
    1816        )
    1817        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    1818        retention_period = (
    1819            f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None
    1820        )
    1821
    1822        if this:
    1823            on_sql = self.func("ON", this, data_consistency, retention_period)
    1824        else:
    1825            on_sql = "ON" if expression.args.get("on") else "OFF"
    1826
    1827        sql = f"SYSTEM_VERSIONING={on_sql}"
    1828
    1829        return f"WITH({sql})" if expression.args.get("with") else sql

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

    1831    def insert_sql(self, expression: exp.Insert) -> str:
    1832        hint = self.sql(expression, "hint")
    1833        overwrite = expression.args.get("overwrite")
    1834
    1835        if isinstance(expression.this, exp.Directory):
    1836            this = " OVERWRITE" if overwrite else " INTO"
    1837        else:
    1838            this = self.INSERT_OVERWRITE if overwrite else " INTO"
    1839
    1840        stored = self.sql(expression, "stored")
    1841        stored = f" {stored}" if stored else ""
    1842        alternative = expression.args.get("alternative")
    1843        alternative = f" OR {alternative}" if alternative else ""
    1844        ignore = " IGNORE" if expression.args.get("ignore") else ""
    1845        is_function = expression.args.get("is_function")
    1846        if is_function:
    1847            this = f"{this} FUNCTION"
    1848        this = f"{this} {self.sql(expression, 'this')}"
    1849
    1850        exists = " IF EXISTS" if expression.args.get("exists") else ""
    1851        where = self.sql(expression, "where")
    1852        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
    1853        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
    1854        on_conflict = self.sql(expression, "conflict")
    1855        on_conflict = f" {on_conflict}" if on_conflict else ""
    1856        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1857        returning = self.sql(expression, "returning")
    1858
    1859        if self.RETURNING_END:
    1860            expression_sql = f"{expression_sql}{on_conflict}{returning}"
    1861        else:
    1862            expression_sql = f"{returning}{expression_sql}{on_conflict}"
    1863
    1864        partition_by = self.sql(expression, "partition")
    1865        partition_by = f" {partition_by}" if partition_by else ""
    1866        settings = self.sql(expression, "settings")
    1867        settings = f" {settings}" if settings else ""
    1868
    1869        source = self.sql(expression, "source")
    1870        source = f"TABLE {source}" if source else ""
    1871
    1872        sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}"
    1873        return self.prepend_ctes(expression, sql)

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

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

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

    1878    def kill_sql(self, expression: exp.Kill) -> str:
    1879        kind = self.sql(expression, "kind")
    1880        kind = f" {kind}" if kind else ""
    1881        this = self.sql(expression, "this")
    1882        this = f" {this}" if this else ""
    1883        return f"KILL{kind}{this}"

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

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

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

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

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

    1891    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1892        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1893
    1894        constraint = self.sql(expression, "constraint")
    1895        constraint = f" ON CONSTRAINT {constraint}" if constraint else ""
    1896
    1897        conflict_keys = self.expressions(expression, key="conflict_keys", flat=True)
    1898        conflict_keys = f"({conflict_keys}) " if conflict_keys else " "
    1899        action = self.sql(expression, "action")
    1900
    1901        expressions = self.expressions(expression, flat=True)
    1902        if expressions:
    1903            set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
    1904            expressions = f" {set_keyword}{expressions}"
    1905
    1906        where = self.sql(expression, "where")
    1907        return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}"

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

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

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

    1912    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1913        fields = self.sql(expression, "fields")
    1914        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1915        escaped = self.sql(expression, "escaped")
    1916        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1917        items = self.sql(expression, "collection_items")
    1918        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1919        keys = self.sql(expression, "map_keys")
    1920        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1921        lines = self.sql(expression, "lines")
    1922        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1923        null = self.sql(expression, "null")
    1924        null = f" NULL DEFINED AS {null}" if null else ""
    1925        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"

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

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

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

    1930    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1931        this = f"{self.sql(expression, 'this')} INDEX"
    1932        target = self.sql(expression, "target")
    1933        target = f" FOR {target}" if target else ""
    1934        return f"{this}{target} ({self.expressions(expression, flat=True)})"

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

    1936    def historicaldata_sql(self, expression: exp.HistoricalData) -> str:
    1937        this = self.sql(expression, "this")
    1938        kind = self.sql(expression, "kind")
    1939        expr = self.sql(expression, "expression")
    1940        return f"{this} ({kind} => {expr})"

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

    1942    def table_parts(self, expression: exp.Table) -> str:
    1943        return ".".join(
    1944            self.sql(part)
    1945            for part in (
    1946                expression.args.get("catalog"),
    1947                expression.args.get("db"),
    1948                expression.args.get("this"),
    1949            )
    1950            if part is not None
    1951        )

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

    1953    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1954        table = self.table_parts(expression)
    1955        only = "ONLY " if expression.args.get("only") else ""
    1956        partition = self.sql(expression, "partition")
    1957        partition = f" {partition}" if partition else ""
    1958        version = self.sql(expression, "version")
    1959        version = f" {version}" if version else ""
    1960        alias = self.sql(expression, "alias")
    1961        alias = f"{sep}{alias}" if alias else ""
    1962
    1963        sample = self.sql(expression, "sample")
    1964        if self.dialect.ALIAS_POST_TABLESAMPLE:
    1965            sample_pre_alias = sample
    1966            sample_post_alias = ""
    1967        else:
    1968            sample_pre_alias = ""
    1969            sample_post_alias = sample
    1970
    1971        hints = self.expressions(expression, key="hints", sep=" ")
    1972        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
    1973        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    1974        joins = self.indent(
    1975            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
    1976        )
    1977        laterals = self.expressions(expression, key="laterals", sep="")
    1978
    1979        file_format = self.sql(expression, "format")
    1980        if file_format:
    1981            pattern = self.sql(expression, "pattern")
    1982            pattern = f", PATTERN => {pattern}" if pattern else ""
    1983            file_format = f" (FILE_FORMAT => {file_format}{pattern})"
    1984
    1985        ordinality = expression.args.get("ordinality") or ""
    1986        if ordinality:
    1987            ordinality = f" WITH ORDINALITY{alias}"
    1988            alias = ""
    1989
    1990        when = self.sql(expression, "when")
    1991        if when:
    1992            table = f"{table} {when}"
    1993
    1994        changes = self.sql(expression, "changes")
    1995        changes = f" {changes}" if changes else ""
    1996
    1997        rows_from = self.expressions(expression, key="rows_from")
    1998        if rows_from:
    1999            table = f"ROWS FROM {self.wrap(rows_from)}"
    2000
    2001        return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}"

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

    2003    def tablefromrows_sql(self, expression: exp.TableFromRows) -> str:
    2004        table = self.func("TABLE", expression.this)
    2005        alias = self.sql(expression, "alias")
    2006        alias = f" AS {alias}" if alias else ""
    2007        sample = self.sql(expression, "sample")
    2008        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    2009        joins = self.indent(
    2010            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
    2011        )
    2012        return f"{table}{alias}{pivots}{sample}{joins}"

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

    2014    def tablesample_sql(
    2015        self,
    2016        expression: exp.TableSample,
    2017        tablesample_keyword: t.Optional[str] = None,
    2018    ) -> str:
    2019        method = self.sql(expression, "method")
    2020        method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    2021        numerator = self.sql(expression, "bucket_numerator")
    2022        denominator = self.sql(expression, "bucket_denominator")
    2023        field = self.sql(expression, "bucket_field")
    2024        field = f" ON {field}" if field else ""
    2025        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    2026        seed = self.sql(expression, "seed")
    2027        seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else ""
    2028
    2029        size = self.sql(expression, "size")
    2030        if size and self.TABLESAMPLE_SIZE_IS_ROWS:
    2031            size = f"{size} ROWS"
    2032
    2033        percent = self.sql(expression, "percent")
    2034        if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT:
    2035            percent = f"{percent} PERCENT"
    2036
    2037        expr = f"{bucket}{percent}{size}"
    2038        if self.TABLESAMPLE_REQUIRES_PARENS:
    2039            expr = f"({expr})"
    2040
    2041        return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}"

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

    2043    def pivot_sql(self, expression: exp.Pivot) -> str:
    2044        expressions = self.expressions(expression, flat=True)
    2045        direction = "UNPIVOT" if expression.unpivot else "PIVOT"
    2046
    2047        if expression.this:
    2048            this = self.sql(expression, "this")
    2049            if not expressions:
    2050                return f"UNPIVOT {this}"
    2051
    2052            on = f"{self.seg('ON')} {expressions}"
    2053            into = self.sql(expression, "into")
    2054            into = f"{self.seg('INTO')} {into}" if into else ""
    2055            using = self.expressions(expression, key="using", flat=True)
    2056            using = f"{self.seg('USING')} {using}" if using else ""
    2057            group = self.sql(expression, "group")
    2058            return f"{direction} {this}{on}{into}{using}{group}"
    2059
    2060        alias = self.sql(expression, "alias")
    2061        alias = f" AS {alias}" if alias else ""
    2062
    2063        field = self.sql(expression, "field")
    2064
    2065        include_nulls = expression.args.get("include_nulls")
    2066        if include_nulls is not None:
    2067            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
    2068        else:
    2069            nulls = ""
    2070
    2071        default_on_null = self.sql(expression, "default_on_null")
    2072        default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else ""
    2073        return f"{self.seg(direction)}{nulls}({expressions} FOR {field}{default_on_null}){alias}"

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

    2075    def version_sql(self, expression: exp.Version) -> str:
    2076        this = f"FOR {expression.name}"
    2077        kind = expression.text("kind")
    2078        expr = self.sql(expression, "expression")
    2079        return f"{this} {kind} {expr}"

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

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

    2084    def update_sql(self, expression: exp.Update) -> str:
    2085        this = self.sql(expression, "this")
    2086        set_sql = self.expressions(expression, flat=True)
    2087        from_sql = self.sql(expression, "from")
    2088        where_sql = self.sql(expression, "where")
    2089        returning = self.sql(expression, "returning")
    2090        order = self.sql(expression, "order")
    2091        limit = self.sql(expression, "limit")
    2092        if self.RETURNING_END:
    2093            expression_sql = f"{from_sql}{where_sql}{returning}"
    2094        else:
    2095            expression_sql = f"{returning}{from_sql}{where_sql}"
    2096        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
    2097        return self.prepend_ctes(expression, sql)

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

    2099    def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str:
    2100        values_as_table = values_as_table and self.VALUES_AS_TABLE
    2101
    2102        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
    2103        if values_as_table or not expression.find_ancestor(exp.From, exp.Join):
    2104            args = self.expressions(expression)
    2105            alias = self.sql(expression, "alias")
    2106            values = f"VALUES{self.seg('')}{args}"
    2107            values = (
    2108                f"({values})"
    2109                if self.WRAP_DERIVED_VALUES
    2110                and (alias or isinstance(expression.parent, (exp.From, exp.Table)))
    2111                else values
    2112            )
    2113            return f"{values} AS {alias}" if alias else values
    2114
    2115        # Converts `VALUES...` expression into a series of select unions.
    2116        alias_node = expression.args.get("alias")
    2117        column_names = alias_node and alias_node.columns
    2118
    2119        selects: t.List[exp.Query] = []
    2120
    2121        for i, tup in enumerate(expression.expressions):
    2122            row = tup.expressions
    2123
    2124            if i == 0 and column_names:
    2125                row = [
    2126                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
    2127                ]
    2128
    2129            selects.append(exp.Select(expressions=row))
    2130
    2131        if self.pretty:
    2132            # This may result in poor performance for large-cardinality `VALUES` tables, due to
    2133            # the deep nesting of the resulting exp.Unions. If this is a problem, either increase
    2134            # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`.
    2135            query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects)
    2136            return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False))
    2137
    2138        alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else ""
    2139        unions = " UNION ALL ".join(self.sql(select) for select in selects)
    2140        return f"({unions}){alias}"

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

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

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

    2145    @unsupported_args("expressions")
    2146    def into_sql(self, expression: exp.Into) -> str:
    2147        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    2148        unlogged = " UNLOGGED" if expression.args.get("unlogged") else ""
    2149        return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"

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

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

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

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

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

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

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

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

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

    2166    def group_sql(self, expression: exp.Group) -> str:
    2167        group_by_all = expression.args.get("all")
    2168        if group_by_all is True:
    2169            modifier = " ALL"
    2170        elif group_by_all is False:
    2171            modifier = " DISTINCT"
    2172        else:
    2173            modifier = ""
    2174
    2175        group_by = self.op_expressions(f"GROUP BY{modifier}", expression)
    2176
    2177        grouping_sets = self.expressions(expression, key="grouping_sets")
    2178        cube = self.expressions(expression, key="cube")
    2179        rollup = self.expressions(expression, key="rollup")
    2180
    2181        groupings = csv(
    2182            self.seg(grouping_sets) if grouping_sets else "",
    2183            self.seg(cube) if cube else "",
    2184            self.seg(rollup) if rollup else "",
    2185            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    2186            sep=self.GROUPINGS_SEP,
    2187        )
    2188
    2189        if (
    2190            expression.expressions
    2191            and groupings
    2192            and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP")
    2193        ):
    2194            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    2195
    2196        return f"{group_by}{groupings}"

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

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

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

    2202    def connect_sql(self, expression: exp.Connect) -> str:
    2203        start = self.sql(expression, "start")
    2204        start = self.seg(f"START WITH {start}") if start else ""
    2205        nocycle = " NOCYCLE" if expression.args.get("nocycle") else ""
    2206        connect = self.sql(expression, "connect")
    2207        connect = self.seg(f"CONNECT BY{nocycle} {connect}")
    2208        return start + connect

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

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

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

    2213    def join_sql(self, expression: exp.Join) -> str:
    2214        if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"):
    2215            side = None
    2216        else:
    2217            side = expression.side
    2218
    2219        op_sql = " ".join(
    2220            op
    2221            for op in (
    2222                expression.method,
    2223                "GLOBAL" if expression.args.get("global") else None,
    2224                side,
    2225                expression.kind,
    2226                expression.hint if self.JOIN_HINTS else None,
    2227            )
    2228            if op
    2229        )
    2230        match_cond = self.sql(expression, "match_condition")
    2231        match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else ""
    2232        on_sql = self.sql(expression, "on")
    2233        using = expression.args.get("using")
    2234
    2235        if not on_sql and using:
    2236            on_sql = csv(*(self.sql(column) for column in using))
    2237
    2238        this = expression.this
    2239        this_sql = self.sql(this)
    2240
    2241        exprs = self.expressions(expression)
    2242        if exprs:
    2243            this_sql = f"{this_sql},{self.seg(exprs)}"
    2244
    2245        if on_sql:
    2246            on_sql = self.indent(on_sql, skip_first=True)
    2247            space = self.seg(" " * self.pad) if self.pretty else " "
    2248            if using:
    2249                on_sql = f"{space}USING ({on_sql})"
    2250            else:
    2251                on_sql = f"{space}ON {on_sql}"
    2252        elif not op_sql:
    2253            if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None:
    2254                return f" {this_sql}"
    2255
    2256            return f", {this_sql}"
    2257
    2258        if op_sql != "STRAIGHT_JOIN":
    2259            op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    2260
    2261        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

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

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

    2268    def lateral_op(self, expression: exp.Lateral) -> str:
    2269        cross_apply = expression.args.get("cross_apply")
    2270
    2271        # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/
    2272        if cross_apply is True:
    2273            op = "INNER JOIN "
    2274        elif cross_apply is False:
    2275            op = "LEFT JOIN "
    2276        else:
    2277            op = ""
    2278
    2279        return f"{op}LATERAL"

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

    2281    def lateral_sql(self, expression: exp.Lateral) -> str:
    2282        this = self.sql(expression, "this")
    2283
    2284        if expression.args.get("view"):
    2285            alias = expression.args["alias"]
    2286            columns = self.expressions(alias, key="columns", flat=True)
    2287            table = f" {alias.name}" if alias.name else ""
    2288            columns = f" AS {columns}" if columns else ""
    2289            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    2290            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    2291
    2292        alias = self.sql(expression, "alias")
    2293        alias = f" AS {alias}" if alias else ""
    2294        return f"{self.lateral_op(expression)} {this}{alias}"

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

    2296    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    2297        this = self.sql(expression, "this")
    2298
    2299        args = [
    2300            self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e
    2301            for e in (expression.args.get(k) for k in ("offset", "expression"))
    2302            if e
    2303        ]
    2304
    2305        args_sql = ", ".join(self.sql(e) for e in args)
    2306        args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql
    2307        expressions = self.expressions(expression, flat=True)
    2308        limit_options = self.sql(expression, "limit_options")
    2309        expressions = f" BY {expressions}" if expressions else ""
    2310
    2311        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{limit_options}{expressions}"

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

    2313    def offset_sql(self, expression: exp.Offset) -> str:
    2314        this = self.sql(expression, "this")
    2315        value = expression.expression
    2316        value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value
    2317        expressions = self.expressions(expression, flat=True)
    2318        expressions = f" BY {expressions}" if expressions else ""
    2319        return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"

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

    2321    def setitem_sql(self, expression: exp.SetItem) -> str:
    2322        kind = self.sql(expression, "kind")
    2323        kind = f"{kind} " if kind else ""
    2324        this = self.sql(expression, "this")
    2325        expressions = self.expressions(expression)
    2326        collate = self.sql(expression, "collate")
    2327        collate = f" COLLATE {collate}" if collate else ""
    2328        global_ = "GLOBAL " if expression.args.get("global") else ""
    2329        return f"{global_}{kind}{this}{expressions}{collate}"

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

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

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

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

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

    2339    def lock_sql(self, expression: exp.Lock) -> str:
    2340        if not self.LOCKING_READS_SUPPORTED:
    2341            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    2342            return ""
    2343
    2344        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    2345        expressions = self.expressions(expression, flat=True)
    2346        expressions = f" OF {expressions}" if expressions else ""
    2347        wait = expression.args.get("wait")
    2348
    2349        if wait is not None:
    2350            if isinstance(wait, exp.Literal):
    2351                wait = f" WAIT {self.sql(wait)}"
    2352            else:
    2353                wait = " NOWAIT" if wait else " SKIP LOCKED"
    2354
    2355        return f"{lock_type}{expressions}{wait or ''}"

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

    2357    def literal_sql(self, expression: exp.Literal) -> str:
    2358        text = expression.this or ""
    2359        if expression.is_string:
    2360            text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}"
    2361        return text

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

    2363    def escape_str(self, text: str, escape_backslash: bool = True) -> str:
    2364        if self.dialect.ESCAPED_SEQUENCES:
    2365            to_escaped = self.dialect.ESCAPED_SEQUENCES
    2366            text = "".join(
    2367                to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text
    2368            )
    2369
    2370        return self._replace_line_breaks(text).replace(
    2371            self.dialect.QUOTE_END, self._escaped_quote_end
    2372        )

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

    2374    def loaddata_sql(self, expression: exp.LoadData) -> str:
    2375        local = " LOCAL" if expression.args.get("local") else ""
    2376        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    2377        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    2378        this = f" INTO TABLE {self.sql(expression, 'this')}"
    2379        partition = self.sql(expression, "partition")
    2380        partition = f" {partition}" if partition else ""
    2381        input_format = self.sql(expression, "input_format")
    2382        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    2383        serde = self.sql(expression, "serde")
    2384        serde = f" SERDE {serde}" if serde else ""
    2385        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"

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

    2387    def null_sql(self, *_) -> str:
    2388        return "NULL"

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

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

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

    2393    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    2394        this = self.sql(expression, "this")
    2395        this = f"{this} " if this else this
    2396        siblings = "SIBLINGS " if expression.args.get("siblings") else ""
    2397        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

    2399    def withfill_sql(self, expression: exp.WithFill) -> str:
    2400        from_sql = self.sql(expression, "from")
    2401        from_sql = f" FROM {from_sql}" if from_sql else ""
    2402        to_sql = self.sql(expression, "to")
    2403        to_sql = f" TO {to_sql}" if to_sql else ""
    2404        step_sql = self.sql(expression, "step")
    2405        step_sql = f" STEP {step_sql}" if step_sql else ""
    2406        interpolated_values = [
    2407            f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}"
    2408            if isinstance(e, exp.Alias)
    2409            else self.sql(e, "this")
    2410            for e in expression.args.get("interpolate") or []
    2411        ]
    2412        interpolate = (
    2413            f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else ""
    2414        )
    2415        return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}"

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

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

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

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

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

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

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

    2426    def ordered_sql(self, expression: exp.Ordered) -> str:
    2427        desc = expression.args.get("desc")
    2428        asc = not desc
    2429
    2430        nulls_first = expression.args.get("nulls_first")
    2431        nulls_last = not nulls_first
    2432        nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large"
    2433        nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small"
    2434        nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last"
    2435
    2436        this = self.sql(expression, "this")
    2437
    2438        sort_order = " DESC" if desc else (" ASC" if desc is False else "")
    2439        nulls_sort_change = ""
    2440        if nulls_first and (
    2441            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
    2442        ):
    2443            nulls_sort_change = " NULLS FIRST"
    2444        elif (
    2445            nulls_last
    2446            and ((asc and nulls_are_small) or (desc and nulls_are_large))
    2447            and not nulls_are_last
    2448        ):
    2449            nulls_sort_change = " NULLS LAST"
    2450
    2451        # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it
    2452        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
    2453            window = expression.find_ancestor(exp.Window, exp.Select)
    2454            if isinstance(window, exp.Window) and window.args.get("spec"):
    2455                self.unsupported(
    2456                    f"'{nulls_sort_change.strip()}' translation not supported in window functions"
    2457                )
    2458                nulls_sort_change = ""
    2459            elif self.NULL_ORDERING_SUPPORTED is False and (
    2460                (asc and nulls_sort_change == " NULLS LAST")
    2461                or (desc and nulls_sort_change == " NULLS FIRST")
    2462            ):
    2463                # BigQuery does not allow these ordering/nulls combinations when used under
    2464                # an aggregation func or under a window containing one
    2465                ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select)
    2466
    2467                if isinstance(ancestor, exp.Window):
    2468                    ancestor = ancestor.this
    2469                if isinstance(ancestor, exp.AggFunc):
    2470                    self.unsupported(
    2471                        f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order"
    2472                    )
    2473                    nulls_sort_change = ""
    2474            elif self.NULL_ORDERING_SUPPORTED is None:
    2475                if expression.this.is_int:
    2476                    self.unsupported(
    2477                        f"'{nulls_sort_change.strip()}' translation not supported with positional ordering"
    2478                    )
    2479                elif not isinstance(expression.this, exp.Rand):
    2480                    null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else ""
    2481                    this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}"
    2482                nulls_sort_change = ""
    2483
    2484        with_fill = self.sql(expression, "with_fill")
    2485        with_fill = f" {with_fill}" if with_fill else ""
    2486
    2487        return f"{this}{sort_order}{nulls_sort_change}{with_fill}"

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

    2489    def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str:
    2490        window_frame = self.sql(expression, "window_frame")
    2491        window_frame = f"{window_frame} " if window_frame else ""
    2492
    2493        this = self.sql(expression, "this")
    2494
    2495        return f"{window_frame}{this}"

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

    2497    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    2498        partition = self.partition_by_sql(expression)
    2499        order = self.sql(expression, "order")
    2500        measures = self.expressions(expression, key="measures")
    2501        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    2502        rows = self.sql(expression, "rows")
    2503        rows = self.seg(rows) if rows else ""
    2504        after = self.sql(expression, "after")
    2505        after = self.seg(after) if after else ""
    2506        pattern = self.sql(expression, "pattern")
    2507        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    2508        definition_sqls = [
    2509            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    2510            for definition in expression.args.get("define", [])
    2511        ]
    2512        definitions = self.expressions(sqls=definition_sqls)
    2513        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    2514        body = "".join(
    2515            (
    2516                partition,
    2517                order,
    2518                measures,
    2519                rows,
    2520                after,
    2521                pattern,
    2522                define,
    2523            )
    2524        )
    2525        alias = self.sql(expression, "alias")
    2526        alias = f" {alias}" if alias else ""
    2527        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"

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

    2529    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    2530        limit = expression.args.get("limit")
    2531
    2532        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    2533            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
    2534        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    2535            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
    2536
    2537        return csv(
    2538            *sqls,
    2539            *[self.sql(join) for join in expression.args.get("joins") or []],
    2540            self.sql(expression, "match"),
    2541            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    2542            self.sql(expression, "prewhere"),
    2543            self.sql(expression, "where"),
    2544            self.sql(expression, "connect"),
    2545            self.sql(expression, "group"),
    2546            self.sql(expression, "having"),
    2547            *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()],
    2548            self.sql(expression, "order"),
    2549            *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit),
    2550            *self.after_limit_modifiers(expression),
    2551            self.options_modifier(expression),
    2552            sep="",
    2553        )

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

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

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

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

    2562    def offset_limit_modifiers(
    2563        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    2564    ) -> t.List[str]:
    2565        return [
    2566            self.sql(expression, "offset") if fetch else self.sql(limit),
    2567            self.sql(limit) if fetch else self.sql(expression, "offset"),
    2568        ]

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

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

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

    2575    def select_sql(self, expression: exp.Select) -> str:
    2576        into = expression.args.get("into")
    2577        if not self.SUPPORTS_SELECT_INTO and into:
    2578            into.pop()
    2579
    2580        hint = self.sql(expression, "hint")
    2581        distinct = self.sql(expression, "distinct")
    2582        distinct = f" {distinct}" if distinct else ""
    2583        kind = self.sql(expression, "kind")
    2584
    2585        limit = expression.args.get("limit")
    2586        if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP:
    2587            top = self.limit_sql(limit, top=True)
    2588            limit.pop()
    2589        else:
    2590            top = ""
    2591
    2592        expressions = self.expressions(expression)
    2593
    2594        if kind:
    2595            if kind in self.SELECT_KINDS:
    2596                kind = f" AS {kind}"
    2597            else:
    2598                if kind == "STRUCT":
    2599                    expressions = self.expressions(
    2600                        sqls=[
    2601                            self.sql(
    2602                                exp.Struct(
    2603                                    expressions=[
    2604                                        exp.PropertyEQ(this=e.args.get("alias"), expression=e.this)
    2605                                        if isinstance(e, exp.Alias)
    2606                                        else e
    2607                                        for e in expression.expressions
    2608                                    ]
    2609                                )
    2610                            )
    2611                        ]
    2612                    )
    2613                kind = ""
    2614
    2615        operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ")
    2616        operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else ""
    2617
    2618        # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata
    2619        # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first.
    2620        top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}"
    2621        expressions = f"{self.sep()}{expressions}" if expressions else expressions
    2622        sql = self.query_modifiers(
    2623            expression,
    2624            f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}",
    2625            self.sql(expression, "into", comment=False),
    2626            self.sql(expression, "from", comment=False),
    2627        )
    2628
    2629        # If both the CTE and SELECT clauses have comments, generate the latter earlier
    2630        if expression.args.get("with"):
    2631            sql = self.maybe_comment(sql, expression)
    2632            expression.pop_comments()
    2633
    2634        sql = self.prepend_ctes(expression, sql)
    2635
    2636        if not self.SUPPORTS_SELECT_INTO and into:
    2637            if into.args.get("temporary"):
    2638                table_kind = " TEMPORARY"
    2639            elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"):
    2640                table_kind = " UNLOGGED"
    2641            else:
    2642                table_kind = ""
    2643            sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}"
    2644
    2645        return sql

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

    2647    def schema_sql(self, expression: exp.Schema) -> str:
    2648        this = self.sql(expression, "this")
    2649        sql = self.schema_columns_sql(expression)
    2650        return f"{this} {sql}" if this and sql else this or sql

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

    2652    def schema_columns_sql(self, expression: exp.Schema) -> str:
    2653        if expression.expressions:
    2654            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
    2655        return ""

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

    2657    def star_sql(self, expression: exp.Star) -> str:
    2658        except_ = self.expressions(expression, key="except", flat=True)
    2659        except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else ""
    2660        replace = self.expressions(expression, key="replace", flat=True)
    2661        replace = f"{self.seg('REPLACE')} ({replace})" if replace else ""
    2662        rename = self.expressions(expression, key="rename", flat=True)
    2663        rename = f"{self.seg('RENAME')} ({rename})" if rename else ""
    2664        return f"*{except_}{replace}{rename}"

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

    2666    def parameter_sql(self, expression: exp.Parameter) -> str:
    2667        this = self.sql(expression, "this")
    2668        return f"{self.PARAMETER_TOKEN}{this}"

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

    2670    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    2671        this = self.sql(expression, "this")
    2672        kind = expression.text("kind")
    2673        if kind:
    2674            kind = f"{kind}."
    2675        return f"@@{kind}{this}"

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

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

    2680    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    2681        alias = self.sql(expression, "alias")
    2682        alias = f"{sep}{alias}" if alias else ""
    2683        sample = self.sql(expression, "sample")
    2684        if self.dialect.ALIAS_POST_TABLESAMPLE and sample:
    2685            alias = f"{sample}{alias}"
    2686
    2687            # Set to None so it's not generated again by self.query_modifiers()
    2688            expression.set("sample", None)
    2689
    2690        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    2691        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    2692        return self.prepend_ctes(expression, sql)

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

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

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

    2698    def unnest_sql(self, expression: exp.Unnest) -> str:
    2699        args = self.expressions(expression, flat=True)
    2700
    2701        alias = expression.args.get("alias")
    2702        offset = expression.args.get("offset")
    2703
    2704        if self.UNNEST_WITH_ORDINALITY:
    2705            if alias and isinstance(offset, exp.Expression):
    2706                alias.append("columns", offset)
    2707
    2708        if alias and self.dialect.UNNEST_COLUMN_ONLY:
    2709            columns = alias.columns
    2710            alias = self.sql(columns[0]) if columns else ""
    2711        else:
    2712            alias = self.sql(alias)
    2713
    2714        alias = f" AS {alias}" if alias else alias
    2715        if self.UNNEST_WITH_ORDINALITY:
    2716            suffix = f" WITH ORDINALITY{alias}" if offset else alias
    2717        else:
    2718            if isinstance(offset, exp.Expression):
    2719                suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}"
    2720            elif offset:
    2721                suffix = f"{alias} WITH OFFSET"
    2722            else:
    2723                suffix = alias
    2724
    2725        return f"UNNEST({args}){suffix}"

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

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

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

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

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

    2734    def window_sql(self, expression: exp.Window) -> str:
    2735        this = self.sql(expression, "this")
    2736        partition = self.partition_by_sql(expression)
    2737        order = expression.args.get("order")
    2738        order = self.order_sql(order, flat=True) if order else ""
    2739        spec = self.sql(expression, "spec")
    2740        alias = self.sql(expression, "alias")
    2741        over = self.sql(expression, "over") or "OVER"
    2742
    2743        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    2744
    2745        first = expression.args.get("first")
    2746        if first is None:
    2747            first = ""
    2748        else:
    2749            first = "FIRST" if first else "LAST"
    2750
    2751        if not partition and not order and not spec and alias:
    2752            return f"{this} {alias}"
    2753
    2754        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
    2755        return f"{this} ({args})"

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

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

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

    2761    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    2762        kind = self.sql(expression, "kind")
    2763        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    2764        end = (
    2765            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    2766            or "CURRENT ROW"
    2767        )
    2768        return f"{kind} BETWEEN {start} AND {end}"

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

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

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

    2775    def between_sql(self, expression: exp.Between) -> str:
    2776        this = self.sql(expression, "this")
    2777        low = self.sql(expression, "low")
    2778        high = self.sql(expression, "high")
    2779        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

    2781    def bracket_offset_expressions(
    2782        self, expression: exp.Bracket, index_offset: t.Optional[int] = None
    2783    ) -> t.List[exp.Expression]:
    2784        return apply_index_offset(
    2785            expression.this,
    2786            expression.expressions,
    2787            (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0),
    2788        )

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

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

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

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

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

    2798    def any_sql(self, expression: exp.Any) -> str:
    2799        this = self.sql(expression, "this")
    2800        if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)):
    2801            if isinstance(expression.this, exp.UNWRAPPED_QUERIES):
    2802                this = self.wrap(this)
    2803            return f"ANY{this}"
    2804        return f"ANY {this}"

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

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

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

    2809    def case_sql(self, expression: exp.Case) -> str:
    2810        this = self.sql(expression, "this")
    2811        statements = [f"CASE {this}" if this else "CASE"]
    2812
    2813        for e in expression.args["ifs"]:
    2814            statements.append(f"WHEN {self.sql(e, 'this')}")
    2815            statements.append(f"THEN {self.sql(e, 'true')}")
    2816
    2817        default = self.sql(expression, "default")
    2818
    2819        if default:
    2820            statements.append(f"ELSE {default}")
    2821
    2822        statements.append("END")
    2823
    2824        if self.pretty and self.too_wide(statements):
    2825            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    2826
    2827        return " ".join(statements)

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

    2829    def constraint_sql(self, expression: exp.Constraint) -> str:
    2830        this = self.sql(expression, "this")
    2831        expressions = self.expressions(expression, flat=True)
    2832        return f"CONSTRAINT {this} {expressions}"

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

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

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

    2839    def extract_sql(self, expression: exp.Extract) -> str:
    2840        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
    2841        expression_sql = self.sql(expression, "expression")
    2842        return f"EXTRACT({this} FROM {expression_sql})"

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

    2844    def trim_sql(self, expression: exp.Trim) -> str:
    2845        trim_type = self.sql(expression, "position")
    2846
    2847        if trim_type == "LEADING":
    2848            func_name = "LTRIM"
    2849        elif trim_type == "TRAILING":
    2850            func_name = "RTRIM"
    2851        else:
    2852            func_name = "TRIM"
    2853
    2854        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

    2856    def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]:
    2857        args = expression.expressions
    2858        if isinstance(expression, exp.ConcatWs):
    2859            args = args[1:]  # Skip the delimiter
    2860
    2861        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    2862            args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args]
    2863
    2864        if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"):
    2865            args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args]
    2866
    2867        return args

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

    2869    def concat_sql(self, expression: exp.Concat) -> str:
    2870        expressions = self.convert_concat_args(expression)
    2871
    2872        # Some dialects don't allow a single-argument CONCAT call
    2873        if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1:
    2874            return self.sql(expressions[0])
    2875
    2876        return self.func("CONCAT", *expressions)

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

    2878    def concatws_sql(self, expression: exp.ConcatWs) -> str:
    2879        return self.func(
    2880            "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression)
    2881        )

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

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

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

    2887    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    2888        expressions = self.expressions(expression, flat=True)
    2889        expressions = f" ({expressions})" if expressions else ""
    2890        reference = self.sql(expression, "reference")
    2891        reference = f" {reference}" if reference else ""
    2892        delete = self.sql(expression, "delete")
    2893        delete = f" ON DELETE {delete}" if delete else ""
    2894        update = self.sql(expression, "update")
    2895        update = f" ON UPDATE {update}" if update else ""
    2896        return f"FOREIGN KEY{expressions}{reference}{delete}{update}"

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

    2898    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    2899        expressions = self.expressions(expression, flat=True)
    2900        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2901        options = f" {options}" if options else ""
    2902        return f"PRIMARY KEY ({expressions}){options}"

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

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

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

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

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

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

    2915    def jsonpath_sql(self, expression: exp.JSONPath) -> str:
    2916        path = self.expressions(expression, sep="", flat=True).lstrip(".")
    2917
    2918        if expression.args.get("escape"):
    2919            path = self.escape_str(path)
    2920
    2921        if self.QUOTE_JSON_PATH:
    2922            path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"
    2923
    2924        return path

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

    2926    def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str:
    2927        if isinstance(expression, exp.JSONPathPart):
    2928            transform = self.TRANSFORMS.get(expression.__class__)
    2929            if not callable(transform):
    2930                self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}")
    2931                return ""
    2932
    2933            return transform(self, expression)
    2934
    2935        if isinstance(expression, int):
    2936            return str(expression)
    2937
    2938        if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE:
    2939            escaped = expression.replace("'", "\\'")
    2940            escaped = f"\\'{expression}\\'"
    2941        else:
    2942            escaped = expression.replace('"', '\\"')
    2943            escaped = f'"{escaped}"'
    2944
    2945        return escaped

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

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

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

    2950    def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str:
    2951        null_handling = expression.args.get("null_handling")
    2952        null_handling = f" {null_handling}" if null_handling else ""
    2953
    2954        unique_keys = expression.args.get("unique_keys")
    2955        if unique_keys is not None:
    2956            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    2957        else:
    2958            unique_keys = ""
    2959
    2960        return_type = self.sql(expression, "return_type")
    2961        return_type = f" RETURNING {return_type}" if return_type else ""
    2962        encoding = self.sql(expression, "encoding")
    2963        encoding = f" ENCODING {encoding}" if encoding else ""
    2964
    2965        return self.func(
    2966            "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG",
    2967            *expression.expressions,
    2968            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
    2969        )

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

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

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

    2974    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
    2975        null_handling = expression.args.get("null_handling")
    2976        null_handling = f" {null_handling}" if null_handling else ""
    2977        return_type = self.sql(expression, "return_type")
    2978        return_type = f" RETURNING {return_type}" if return_type else ""
    2979        strict = " STRICT" if expression.args.get("strict") else ""
    2980        return self.func(
    2981            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
    2982        )

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

    2984    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
    2985        this = self.sql(expression, "this")
    2986        order = self.sql(expression, "order")
    2987        null_handling = expression.args.get("null_handling")
    2988        null_handling = f" {null_handling}" if null_handling else ""
    2989        return_type = self.sql(expression, "return_type")
    2990        return_type = f" RETURNING {return_type}" if return_type else ""
    2991        strict = " STRICT" if expression.args.get("strict") else ""
    2992        return self.func(
    2993            "JSON_ARRAYAGG",
    2994            this,
    2995            suffix=f"{order}{null_handling}{return_type}{strict})",
    2996        )

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

    2998    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
    2999        path = self.sql(expression, "path")
    3000        path = f" PATH {path}" if path else ""
    3001        nested_schema = self.sql(expression, "nested_schema")
    3002
    3003        if nested_schema:
    3004            return f"NESTED{path} {nested_schema}"
    3005
    3006        this = self.sql(expression, "this")
    3007        kind = self.sql(expression, "kind")
    3008        kind = f" {kind}" if kind else ""
    3009        return f"{this}{kind}{path}"

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

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

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

    3014    def jsontable_sql(self, expression: exp.JSONTable) -> str:
    3015        this = self.sql(expression, "this")
    3016        path = self.sql(expression, "path")
    3017        path = f", {path}" if path else ""
    3018        error_handling = expression.args.get("error_handling")
    3019        error_handling = f" {error_handling}" if error_handling else ""
    3020        empty_handling = expression.args.get("empty_handling")
    3021        empty_handling = f" {empty_handling}" if empty_handling else ""
    3022        schema = self.sql(expression, "schema")
    3023        return self.func(
    3024            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
    3025        )

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

    3027    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    3028        this = self.sql(expression, "this")
    3029        kind = self.sql(expression, "kind")
    3030        path = self.sql(expression, "path")
    3031        path = f" {path}" if path else ""
    3032        as_json = " AS JSON" if expression.args.get("as_json") else ""
    3033        return f"{this} {kind}{path}{as_json}"

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

    3035    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    3036        this = self.sql(expression, "this")
    3037        path = self.sql(expression, "path")
    3038        path = f", {path}" if path else ""
    3039        expressions = self.expressions(expression)
    3040        with_ = (
    3041            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    3042            if expressions
    3043            else ""
    3044        )
    3045        return f"OPENJSON({this}{path}){with_}"

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

    3047    def in_sql(self, expression: exp.In) -> str:
    3048        query = expression.args.get("query")
    3049        unnest = expression.args.get("unnest")
    3050        field = expression.args.get("field")
    3051        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    3052
    3053        if query:
    3054            in_sql = self.sql(query)
    3055        elif unnest:
    3056            in_sql = self.in_unnest_op(unnest)
    3057        elif field:
    3058            in_sql = self.sql(field)
    3059        else:
    3060            in_sql = f"({self.expressions(expression, flat=True)})"
    3061
    3062        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"

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

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

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

    3067    def interval_sql(self, expression: exp.Interval) -> str:
    3068        unit = self.sql(expression, "unit")
    3069        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    3070            unit = self.TIME_PART_SINGULARS.get(unit, unit)
    3071        unit = f" {unit}" if unit else ""
    3072
    3073        if self.SINGLE_STRING_INTERVAL:
    3074            this = expression.this.name if expression.this else ""
    3075            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    3076
    3077        this = self.sql(expression, "this")
    3078        if this:
    3079            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    3080            this = f" {this}" if unwrapped else f" ({this})"
    3081
    3082        return f"INTERVAL{this}{unit}"

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

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

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

    3087    def reference_sql(self, expression: exp.Reference) -> str:
    3088        this = self.sql(expression, "this")
    3089        expressions = self.expressions(expression, flat=True)
    3090        expressions = f"({expressions})" if expressions else ""
    3091        options = self.expressions(expression, key="options", flat=True, sep=" ")
    3092        options = f" {options}" if options else ""
    3093        return f"REFERENCES {this}{expressions}{options}"

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

    3095    def anonymous_sql(self, expression: exp.Anonymous) -> str:
    3096        # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive
    3097        parent = expression.parent
    3098        is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression
    3099        return self.func(
    3100            self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified
    3101        )

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

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

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

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

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

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

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

    3116    def alias_sql(self, expression: exp.Alias) -> str:
    3117        alias = self.sql(expression, "alias")
    3118        alias = f" AS {alias}" if alias else ""
    3119        return f"{self.sql(expression, 'this')}{alias}"

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

    3121    def pivotalias_sql(self, expression: exp.PivotAlias) -> str:
    3122        alias = expression.args["alias"]
    3123
    3124        identifier_alias = isinstance(alias, exp.Identifier)
    3125        literal_alias = isinstance(alias, exp.Literal)
    3126
    3127        if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    3128            alias.replace(exp.Literal.string(alias.output_name))
    3129        elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    3130            alias.replace(exp.to_identifier(alias.output_name))
    3131
    3132        return self.alias_sql(expression)

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

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

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

    3137    def atindex_sql(self, expression: exp.AtTimeZone) -> str:
    3138        this = self.sql(expression, "this")
    3139        index = self.sql(expression, "expression")
    3140        return f"{this} AT {index}"

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

    3142    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    3143        this = self.sql(expression, "this")
    3144        zone = self.sql(expression, "zone")
    3145        return f"{this} AT TIME ZONE {zone}"

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

    3147    def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str:
    3148        this = self.sql(expression, "this")
    3149        zone = self.sql(expression, "zone")
    3150        return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'"

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

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

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

    3155    def and_sql(
    3156        self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None
    3157    ) -> str:
    3158        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

    3160    def or_sql(
    3161        self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None
    3162    ) -> str:
    3163        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

    3165    def xor_sql(
    3166        self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None
    3167    ) -> str:
    3168        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

    3170    def connector_sql(
    3171        self,
    3172        expression: exp.Connector,
    3173        op: str,
    3174        stack: t.Optional[t.List[str | exp.Expression]] = None,
    3175    ) -> str:
    3176        if stack is not None:
    3177            if expression.expressions:
    3178                stack.append(self.expressions(expression, sep=f" {op} "))
    3179            else:
    3180                stack.append(expression.right)
    3181                if expression.comments and self.comments:
    3182                    for comment in expression.comments:
    3183                        if comment:
    3184                            op += f" /*{self.pad_comment(comment)}*/"
    3185                stack.extend((op, expression.left))
    3186            return op
    3187
    3188        stack = [expression]
    3189        sqls: t.List[str] = []
    3190        ops = set()
    3191
    3192        while stack:
    3193            node = stack.pop()
    3194            if isinstance(node, exp.Connector):
    3195                ops.add(getattr(self, f"{node.key}_sql")(node, stack))
    3196            else:
    3197                sql = self.sql(node)
    3198                if sqls and sqls[-1] in ops:
    3199                    sqls[-1] += f" {sql}"
    3200                else:
    3201                    sqls.append(sql)
    3202
    3203        sep = "\n" if self.pretty and self.too_wide(sqls) else " "
    3204        return sep.join(sqls)

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

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

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

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

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

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

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

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

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

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

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

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

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

    3224    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    3225        format_sql = self.sql(expression, "format")
    3226        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    3227        to_sql = self.sql(expression, "to")
    3228        to_sql = f" {to_sql}" if to_sql else ""
    3229        action = self.sql(expression, "action")
    3230        action = f" {action}" if action else ""
    3231        default = self.sql(expression, "default")
    3232        default = f" DEFAULT {default} ON CONVERSION ERROR" if default else ""
    3233        return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{default}{format_sql}{action})"

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

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

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

    3239    def collate_sql(self, expression: exp.Collate) -> str:
    3240        if self.COLLATE_IS_FUNC:
    3241            return self.function_fallback_sql(expression)
    3242        return self.binary(expression, "COLLATE")

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

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

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

    3247    def comment_sql(self, expression: exp.Comment) -> str:
    3248        this = self.sql(expression, "this")
    3249        kind = expression.args["kind"]
    3250        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    3251        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    3252        expression_sql = self.sql(expression, "expression")
    3253        return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"

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

    3255    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    3256        this = self.sql(expression, "this")
    3257        delete = " DELETE" if expression.args.get("delete") else ""
    3258        recompress = self.sql(expression, "recompress")
    3259        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    3260        to_disk = self.sql(expression, "to_disk")
    3261        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    3262        to_volume = self.sql(expression, "to_volume")
    3263        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    3264        return f"{this}{delete}{recompress}{to_disk}{to_volume}"

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

    3266    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    3267        where = self.sql(expression, "where")
    3268        group = self.sql(expression, "group")
    3269        aggregates = self.expressions(expression, key="aggregates")
    3270        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    3271
    3272        if not (where or group or aggregates) and len(expression.expressions) == 1:
    3273            return f"TTL {self.expressions(expression, flat=True)}"
    3274
    3275        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"

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

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

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

    3280    def commit_sql(self, expression: exp.Commit) -> str:
    3281        chain = expression.args.get("chain")
    3282        if chain is not None:
    3283            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    3284
    3285        return f"COMMIT{chain or ''}"

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

    3287    def rollback_sql(self, expression: exp.Rollback) -> str:
    3288        savepoint = expression.args.get("savepoint")
    3289        savepoint = f" TO {savepoint}" if savepoint else ""
    3290        return f"ROLLBACK{savepoint}"

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

    3292    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    3293        this = self.sql(expression, "this")
    3294
    3295        dtype = self.sql(expression, "dtype")
    3296        if dtype:
    3297            collate = self.sql(expression, "collate")
    3298            collate = f" COLLATE {collate}" if collate else ""
    3299            using = self.sql(expression, "using")
    3300            using = f" USING {using}" if using else ""
    3301            return f"ALTER COLUMN {this} {self.ALTER_SET_TYPE} {dtype}{collate}{using}"
    3302
    3303        default = self.sql(expression, "default")
    3304        if default:
    3305            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    3306
    3307        comment = self.sql(expression, "comment")
    3308        if comment:
    3309            return f"ALTER COLUMN {this} COMMENT {comment}"
    3310
    3311        visible = expression.args.get("visible")
    3312        if visible:
    3313            return f"ALTER COLUMN {this} SET {visible}"
    3314
    3315        allow_null = expression.args.get("allow_null")
    3316        drop = expression.args.get("drop")
    3317
    3318        if not drop and not allow_null:
    3319            self.unsupported("Unsupported ALTER COLUMN syntax")
    3320
    3321        if allow_null is not None:
    3322            keyword = "DROP" if drop else "SET"
    3323            return f"ALTER COLUMN {this} {keyword} NOT NULL"
    3324
    3325        return f"ALTER COLUMN {this} DROP DEFAULT"

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

    3327    def alterindex_sql(self, expression: exp.AlterIndex) -> str:
    3328        this = self.sql(expression, "this")
    3329
    3330        visible = expression.args.get("visible")
    3331        visible_sql = "VISIBLE" if visible else "INVISIBLE"
    3332
    3333        return f"ALTER INDEX {this} {visible_sql}"

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

    3335    def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str:
    3336        this = self.sql(expression, "this")
    3337        if not isinstance(expression.this, exp.Var):
    3338            this = f"KEY DISTKEY {this}"
    3339        return f"ALTER DISTSTYLE {this}"

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

    3341    def altersortkey_sql(self, expression: exp.AlterSortKey) -> str:
    3342        compound = " COMPOUND" if expression.args.get("compound") else ""
    3343        this = self.sql(expression, "this")
    3344        expressions = self.expressions(expression, flat=True)
    3345        expressions = f"({expressions})" if expressions else ""
    3346        return f"ALTER{compound} SORTKEY {this or expressions}"

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

    3348    def alterrename_sql(self, expression: exp.AlterRename) -> str:
    3349        if not self.RENAME_TABLE_WITH_DB:
    3350            # Remove db from tables
    3351            expression = expression.transform(
    3352                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    3353            ).assert_is(exp.AlterRename)
    3354        this = self.sql(expression, "this")
    3355        return f"RENAME TO {this}"

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

    3357    def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
    3358        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3359        old_column = self.sql(expression, "this")
    3360        new_column = self.sql(expression, "to")
    3361        return f"RENAME COLUMN{exists} {old_column} TO {new_column}"

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

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

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

    3367    def alter_sql(self, expression: exp.Alter) -> str:
    3368        actions = expression.args["actions"]
    3369
    3370        if isinstance(actions[0], exp.ColumnDef):
    3371            actions = self.add_column_sql(expression)
    3372        elif isinstance(actions[0], exp.Schema):
    3373            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    3374        elif isinstance(actions[0], exp.Delete):
    3375            actions = self.expressions(expression, key="actions", flat=True)
    3376        elif isinstance(actions[0], exp.Query):
    3377            actions = "AS " + self.expressions(expression, key="actions")
    3378        else:
    3379            actions = self.expressions(expression, key="actions", flat=True)
    3380
    3381        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3382        on_cluster = self.sql(expression, "cluster")
    3383        on_cluster = f" {on_cluster}" if on_cluster else ""
    3384        only = " ONLY" if expression.args.get("only") else ""
    3385        options = self.expressions(expression, key="options")
    3386        options = f", {options}" if options else ""
    3387        kind = self.sql(expression, "kind")
    3388        not_valid = " NOT VALID" if expression.args.get("not_valid") else ""
    3389
    3390        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

    3392    def add_column_sql(self, expression: exp.Alter) -> str:
    3393        if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD:
    3394            return self.expressions(
    3395                expression,
    3396                key="actions",
    3397                prefix="ADD COLUMN ",
    3398                skip_first=True,
    3399            )
    3400        return f"ADD {self.expressions(expression, key='actions', flat=True)}"

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

    3402    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    3403        expressions = self.expressions(expression)
    3404        exists = " IF EXISTS " if expression.args.get("exists") else " "
    3405        return f"DROP{exists}{expressions}"

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

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

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

    3410    def distinct_sql(self, expression: exp.Distinct) -> str:
    3411        this = self.expressions(expression, flat=True)
    3412
    3413        if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1:
    3414            case = exp.case()
    3415            for arg in expression.expressions:
    3416                case = case.when(arg.is_(exp.null()), exp.null())
    3417            this = self.sql(case.else_(f"({this})"))
    3418
    3419        this = f" {this}" if this else ""
    3420
    3421        on = self.sql(expression, "on")
    3422        on = f" ON {on}" if on else ""
    3423        return f"DISTINCT{this}{on}"

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

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

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

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

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

    3431    def havingmax_sql(self, expression: exp.HavingMax) -> str:
    3432        this_sql = self.sql(expression, "this")
    3433        expression_sql = self.sql(expression, "expression")
    3434        kind = "MAX" if expression.args.get("max") else "MIN"
    3435        return f"{this_sql} HAVING {kind} {expression_sql}"

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

    3437    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    3438        return self.sql(
    3439            exp.Cast(
    3440                this=exp.Div(this=expression.this, expression=expression.expression),
    3441                to=exp.DataType(this=exp.DataType.Type.INT),
    3442            )
    3443        )

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

    3445    def dpipe_sql(self, expression: exp.DPipe) -> str:
    3446        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    3447            return self.func(
    3448                "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten())
    3449            )
    3450        return self.binary(expression, "||")

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

    3452    def div_sql(self, expression: exp.Div) -> str:
    3453        l, r = expression.left, expression.right
    3454
    3455        if not self.dialect.SAFE_DIVISION and expression.args.get("safe"):
    3456            r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0)))
    3457
    3458        if self.dialect.TYPED_DIVISION and not expression.args.get("typed"):
    3459            if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES):
    3460                l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE))
    3461
    3462        elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"):
    3463            if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES):
    3464                return self.sql(
    3465                    exp.cast(
    3466                        l / r,
    3467                        to=exp.DataType.Type.BIGINT,
    3468                    )
    3469                )
    3470
    3471        return self.binary(expression, "/")

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

    3473    def safedivide_sql(self, expression: exp.SafeDivide) -> str:
    3474        n = exp._wrap(expression.this, exp.Binary)
    3475        d = exp._wrap(expression.expression, exp.Binary)
    3476        return self.sql(exp.If(this=d.neq(0), true=n / d, false=exp.Null()))

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3511    def is_sql(self, expression: exp.Is) -> str:
    3512        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    3513            return self.sql(
    3514                expression.this if expression.expression.this else exp.not_(expression.this)
    3515            )
    3516        return self.binary(expression, "IS")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3560    def try_sql(self, expression: exp.Try) -> str:
    3561        if not self.TRY_SUPPORTED:
    3562            self.unsupported("Unsupported TRY function")
    3563            return self.sql(expression, "this")
    3564
    3565        return self.func("TRY", expression.this)

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

    3567    def log_sql(self, expression: exp.Log) -> str:
    3568        this = expression.this
    3569        expr = expression.expression
    3570
    3571        if self.dialect.LOG_BASE_FIRST is False:
    3572            this, expr = expr, this
    3573        elif self.dialect.LOG_BASE_FIRST is None and expr:
    3574            if this.name in ("2", "10"):
    3575                return self.func(f"LOG{this.name}", expr)
    3576
    3577            self.unsupported(f"Unsupported logarithm with base {self.sql(this)}")
    3578
    3579        return self.func("LOG", this, expr)

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

    3581    def use_sql(self, expression: exp.Use) -> str:
    3582        kind = self.sql(expression, "kind")
    3583        kind = f" {kind}" if kind else ""
    3584        this = self.sql(expression, "this") or self.expressions(expression, flat=True)
    3585        this = f" {this}" if this else ""
    3586        return f"USE{kind}{this}"

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

    3588    def binary(self, expression: exp.Binary, op: str) -> str:
    3589        sqls: t.List[str] = []
    3590        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    3591        binary_type = type(expression)
    3592
    3593        while stack:
    3594            node = stack.pop()
    3595
    3596            if type(node) is binary_type:
    3597                op_func = node.args.get("operator")
    3598                if op_func:
    3599                    op = f"OPERATOR({self.sql(op_func)})"
    3600
    3601                stack.append(node.right)
    3602                stack.append(f" {self.maybe_comment(op, comments=node.comments)} ")
    3603                stack.append(node.left)
    3604            else:
    3605                sqls.append(self.sql(node))
    3606
    3607        return "".join(sqls)

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

    3609    def ceil_floor(self, expression: exp.Ceil | exp.Floor) -> str:
    3610        to_clause = self.sql(expression, "to")
    3611        if to_clause:
    3612            return f"{expression.sql_name()}({self.sql(expression, 'this')} TO {to_clause})"
    3613
    3614        return self.function_fallback_sql(expression)

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

    3616    def function_fallback_sql(self, expression: exp.Func) -> str:
    3617        args = []
    3618
    3619        for key in expression.arg_types:
    3620            arg_value = expression.args.get(key)
    3621
    3622            if isinstance(arg_value, list):
    3623                for value in arg_value:
    3624                    args.append(value)
    3625            elif arg_value is not None:
    3626                args.append(arg_value)
    3627
    3628        if self.dialect.PRESERVE_ORIGINAL_NAMES:
    3629            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
    3630        else:
    3631            name = expression.sql_name()
    3632
    3633        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

    3635    def func(
    3636        self,
    3637        name: str,
    3638        *args: t.Optional[exp.Expression | str],
    3639        prefix: str = "(",
    3640        suffix: str = ")",
    3641        normalize: bool = True,
    3642    ) -> str:
    3643        name = self.normalize_func(name) if normalize else name
    3644        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

    3646    def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str:
    3647        arg_sqls = tuple(
    3648            self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool)
    3649        )
    3650        if self.pretty and self.too_wide(arg_sqls):
    3651            return self.indent(
    3652                "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True
    3653            )
    3654        return sep.join(arg_sqls)

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

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

    3659    def format_time(
    3660        self,
    3661        expression: exp.Expression,
    3662        inverse_time_mapping: t.Optional[t.Dict[str, str]] = None,
    3663        inverse_time_trie: t.Optional[t.Dict] = None,
    3664    ) -> t.Optional[str]:
    3665        return format_time(
    3666            self.sql(expression, "format"),
    3667            inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING,
    3668            inverse_time_trie or self.dialect.INVERSE_TIME_TRIE,
    3669        )

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

    3671    def expressions(
    3672        self,
    3673        expression: t.Optional[exp.Expression] = None,
    3674        key: t.Optional[str] = None,
    3675        sqls: t.Optional[t.Collection[str | exp.Expression]] = None,
    3676        flat: bool = False,
    3677        indent: bool = True,
    3678        skip_first: bool = False,
    3679        skip_last: bool = False,
    3680        sep: str = ", ",
    3681        prefix: str = "",
    3682        dynamic: bool = False,
    3683        new_line: bool = False,
    3684    ) -> str:
    3685        expressions = expression.args.get(key or "expressions") if expression else sqls
    3686
    3687        if not expressions:
    3688            return ""
    3689
    3690        if flat:
    3691            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
    3692
    3693        num_sqls = len(expressions)
    3694        result_sqls = []
    3695
    3696        for i, e in enumerate(expressions):
    3697            sql = self.sql(e, comment=False)
    3698            if not sql:
    3699                continue
    3700
    3701            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    3702
    3703            if self.pretty:
    3704                if self.leading_comma:
    3705                    result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}")
    3706                else:
    3707                    result_sqls.append(
    3708                        f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}"
    3709                    )
    3710            else:
    3711                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    3712
    3713        if self.pretty and (not dynamic or self.too_wide(result_sqls)):
    3714            if new_line:
    3715                result_sqls.insert(0, "")
    3716                result_sqls.append("")
    3717            result_sql = "\n".join(s.rstrip() for s in result_sqls)
    3718        else:
    3719            result_sql = "".join(result_sqls)
    3720
    3721        return (
    3722            self.indent(result_sql, skip_first=skip_first, skip_last=skip_last)
    3723            if indent
    3724            else result_sql
    3725        )

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

    3727    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    3728        flat = flat or isinstance(expression.parent, exp.Properties)
    3729        expressions_sql = self.expressions(expression, flat=flat)
    3730        if flat:
    3731            return f"{op} {expressions_sql}"
    3732        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"

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

    3734    def naked_property(self, expression: exp.Property) -> str:
    3735        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    3736        if not property_name:
    3737            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    3738        return f"{property_name} {self.sql(expression, 'this')}"

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

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

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

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

    3746    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    3747        this = self.sql(expression, "this")
    3748        expressions = self.no_identify(self.expressions, expression)
    3749        expressions = (
    3750            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    3751        )
    3752        return f"{this}{expressions}" if expressions.strip() != "" else this

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

    3754    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    3755        this = self.sql(expression, "this")
    3756        expressions = self.expressions(expression, flat=True)
    3757        return f"{this}({expressions})"

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

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

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

    3762    def when_sql(self, expression: exp.When) -> str:
    3763        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    3764        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    3765        condition = self.sql(expression, "condition")
    3766        condition = f" AND {condition}" if condition else ""
    3767
    3768        then_expression = expression.args.get("then")
    3769        if isinstance(then_expression, exp.Insert):
    3770            this = self.sql(then_expression, "this")
    3771            this = f"INSERT {this}" if this else "INSERT"
    3772            then = self.sql(then_expression, "expression")
    3773            then = f"{this} VALUES {then}" if then else this
    3774        elif isinstance(then_expression, exp.Update):
    3775            if isinstance(then_expression.args.get("expressions"), exp.Star):
    3776                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    3777            else:
    3778                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    3779        else:
    3780            then = self.sql(then_expression)
    3781        return f"WHEN {matched}{source}{condition} THEN {then}"

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

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

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

    3786    def merge_sql(self, expression: exp.Merge) -> str:
    3787        table = expression.this
    3788        table_alias = ""
    3789
    3790        hints = table.args.get("hints")
    3791        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
    3792            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
    3793            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
    3794
    3795        this = self.sql(table)
    3796        using = f"USING {self.sql(expression, 'using')}"
    3797        on = f"ON {self.sql(expression, 'on')}"
    3798        whens = self.sql(expression, "whens")
    3799
    3800        returning = self.sql(expression, "returning")
    3801        if returning:
    3802            whens = f"{whens}{returning}"
    3803
    3804        sep = self.sep()
    3805
    3806        return self.prepend_ctes(
    3807            expression,
    3808            f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}",
    3809        )

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

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

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

    3815    def tonumber_sql(self, expression: exp.ToNumber) -> str:
    3816        if not self.SUPPORTS_TO_NUMBER:
    3817            self.unsupported("Unsupported TO_NUMBER function")
    3818            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3819
    3820        fmt = expression.args.get("format")
    3821        if not fmt:
    3822            self.unsupported("Conversion format is required for TO_NUMBER")
    3823            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3824
    3825        return self.func("TO_NUMBER", expression.this, fmt)

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

    3827    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    3828        this = self.sql(expression, "this")
    3829        kind = self.sql(expression, "kind")
    3830        settings_sql = self.expressions(expression, key="settings", sep=" ")
    3831        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    3832        return f"{this}({kind}{args})"

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

    3834    def dictrange_sql(self, expression: exp.DictRange) -> str:
    3835        this = self.sql(expression, "this")
    3836        max = self.sql(expression, "max")
    3837        min = self.sql(expression, "min")
    3838        return f"{this}(MIN {min} MAX {max})"

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

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

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

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

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

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

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

    3851    def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str:
    3852        expressions = self.expressions(expression, flat=True)
    3853        expressions = f" {self.wrap(expressions)}" if expressions else ""
    3854        buckets = self.sql(expression, "buckets")
    3855        kind = self.sql(expression, "kind")
    3856        buckets = f" BUCKETS {buckets}" if buckets else ""
    3857        order = self.sql(expression, "order")
    3858        return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}"

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

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

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

    3863    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    3864        expressions = self.expressions(expression, key="expressions", flat=True)
    3865        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    3866        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    3867        buckets = self.sql(expression, "buckets")
    3868        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"

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

    3870    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    3871        this = self.sql(expression, "this")
    3872        having = self.sql(expression, "having")
    3873
    3874        if having:
    3875            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    3876
    3877        return self.func("ANY_VALUE", this)

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

    3879    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
    3880        transform = self.func("TRANSFORM", *expression.expressions)
    3881        row_format_before = self.sql(expression, "row_format_before")
    3882        row_format_before = f" {row_format_before}" if row_format_before else ""
    3883        record_writer = self.sql(expression, "record_writer")
    3884        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
    3885        using = f" USING {self.sql(expression, 'command_script')}"
    3886        schema = self.sql(expression, "schema")
    3887        schema = f" AS {schema}" if schema else ""
    3888        row_format_after = self.sql(expression, "row_format_after")
    3889        row_format_after = f" {row_format_after}" if row_format_after else ""
    3890        record_reader = self.sql(expression, "record_reader")
    3891        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
    3892        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

    3894    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
    3895        key_block_size = self.sql(expression, "key_block_size")
    3896        if key_block_size:
    3897            return f"KEY_BLOCK_SIZE = {key_block_size}"
    3898
    3899        using = self.sql(expression, "using")
    3900        if using:
    3901            return f"USING {using}"
    3902
    3903        parser = self.sql(expression, "parser")
    3904        if parser:
    3905            return f"WITH PARSER {parser}"
    3906
    3907        comment = self.sql(expression, "comment")
    3908        if comment:
    3909            return f"COMMENT {comment}"
    3910
    3911        visible = expression.args.get("visible")
    3912        if visible is not None:
    3913            return "VISIBLE" if visible else "INVISIBLE"
    3914
    3915        engine_attr = self.sql(expression, "engine_attr")
    3916        if engine_attr:
    3917            return f"ENGINE_ATTRIBUTE = {engine_attr}"
    3918
    3919        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
    3920        if secondary_engine_attr:
    3921            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
    3922
    3923        self.unsupported("Unsupported index constraint option.")
    3924        return ""

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

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

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

    3930    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
    3931        kind = self.sql(expression, "kind")
    3932        kind = f"{kind} INDEX" if kind else "INDEX"
    3933        this = self.sql(expression, "this")
    3934        this = f" {this}" if this else ""
    3935        index_type = self.sql(expression, "index_type")
    3936        index_type = f" USING {index_type}" if index_type else ""
    3937        expressions = self.expressions(expression, flat=True)
    3938        expressions = f" ({expressions})" if expressions else ""
    3939        options = self.expressions(expression, key="options", sep=" ")
    3940        options = f" {options}" if options else ""
    3941        return f"{kind}{this}{index_type}{expressions}{options}"

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

    3943    def nvl2_sql(self, expression: exp.Nvl2) -> str:
    3944        if self.NVL2_SUPPORTED:
    3945            return self.function_fallback_sql(expression)
    3946
    3947        case = exp.Case().when(
    3948            expression.this.is_(exp.null()).not_(copy=False),
    3949            expression.args["true"],
    3950            copy=False,
    3951        )
    3952        else_cond = expression.args.get("false")
    3953        if else_cond:
    3954            case.else_(else_cond, copy=False)
    3955
    3956        return self.sql(case)

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

    3958    def comprehension_sql(self, expression: exp.Comprehension) -> str:
    3959        this = self.sql(expression, "this")
    3960        expr = self.sql(expression, "expression")
    3961        iterator = self.sql(expression, "iterator")
    3962        condition = self.sql(expression, "condition")
    3963        condition = f" IF {condition}" if condition else ""
    3964        return f"{this} FOR {expr} IN {iterator}{condition}"

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

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

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

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

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

    3972    def predict_sql(self, expression: exp.Predict) -> str:
    3973        model = self.sql(expression, "this")
    3974        model = f"MODEL {model}"
    3975        table = self.sql(expression, "expression")
    3976        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
    3977        parameters = self.sql(expression, "params_struct")
    3978        return self.func("PREDICT", model, table, parameters or None)

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

    3980    def forin_sql(self, expression: exp.ForIn) -> str:
    3981        this = self.sql(expression, "this")
    3982        expression_sql = self.sql(expression, "expression")
    3983        return f"FOR {this} DO {expression_sql}"

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

    3985    def refresh_sql(self, expression: exp.Refresh) -> str:
    3986        this = self.sql(expression, "this")
    3987        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
    3988        return f"REFRESH {table}{this}"

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

    3990    def toarray_sql(self, expression: exp.ToArray) -> str:
    3991        arg = expression.this
    3992        if not arg.type:
    3993            from sqlglot.optimizer.annotate_types import annotate_types
    3994
    3995            arg = annotate_types(arg)
    3996
    3997        if arg.is_type(exp.DataType.Type.ARRAY):
    3998            return self.sql(arg)
    3999
    4000        cond_for_null = arg.is_(exp.null())
    4001        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

    4003    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
    4004        this = expression.this
    4005        time_format = self.format_time(expression)
    4006
    4007        if time_format:
    4008            return self.sql(
    4009                exp.cast(
    4010                    exp.StrToTime(this=this, format=expression.args["format"]),
    4011                    exp.DataType.Type.TIME,
    4012                )
    4013            )
    4014
    4015        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
    4016            return self.sql(this)
    4017
    4018        return self.sql(exp.cast(this, exp.DataType.Type.TIME))

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

    4020    def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str:
    4021        this = expression.this
    4022        if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP):
    4023            return self.sql(this)
    4024
    4025        return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect))

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

    4027    def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str:
    4028        this = expression.this
    4029        if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME):
    4030            return self.sql(this)
    4031
    4032        return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect))

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

    4034    def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:
    4035        this = expression.this
    4036        time_format = self.format_time(expression)
    4037
    4038        if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT):
    4039            return self.sql(
    4040                exp.cast(
    4041                    exp.StrToTime(this=this, format=expression.args["format"]),
    4042                    exp.DataType.Type.DATE,
    4043                )
    4044            )
    4045
    4046        if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE):
    4047            return self.sql(this)
    4048
    4049        return self.sql(exp.cast(this, exp.DataType.Type.DATE))

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

    4051    def unixdate_sql(self, expression: exp.UnixDate) -> str:
    4052        return self.sql(
    4053            exp.func(
    4054                "DATEDIFF",
    4055                expression.this,
    4056                exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE),
    4057                "day",
    4058            )
    4059        )

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

    4061    def lastday_sql(self, expression: exp.LastDay) -> str:
    4062        if self.LAST_DAY_SUPPORTS_DATE_PART:
    4063            return self.function_fallback_sql(expression)
    4064
    4065        unit = expression.text("unit")
    4066        if unit and unit != "MONTH":
    4067            self.unsupported("Date parts are not supported in LAST_DAY.")
    4068
    4069        return self.func("LAST_DAY", expression.this)

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

    4071    def dateadd_sql(self, expression: exp.DateAdd) -> str:
    4072        from sqlglot.dialects.dialect import unit_to_str
    4073
    4074        return self.func(
    4075            "DATE_ADD", expression.this, expression.expression, unit_to_str(expression)
    4076        )

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

    4078    def arrayany_sql(self, expression: exp.ArrayAny) -> str:
    4079        if self.CAN_IMPLEMENT_ARRAY_ANY:
    4080            filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression)
    4081            filtered_not_empty = exp.ArraySize(this=filtered).neq(0)
    4082            original_is_empty = exp.ArraySize(this=expression.this).eq(0)
    4083            return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty)))
    4084
    4085        from sqlglot.dialects import Dialect
    4086
    4087        # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect
    4088        if self.dialect.__class__ != Dialect:
    4089            self.unsupported("ARRAY_ANY is unsupported")
    4090
    4091        return self.function_fallback_sql(expression)

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

    4093    def struct_sql(self, expression: exp.Struct) -> str:
    4094        expression.set(
    4095            "expressions",
    4096            [
    4097                exp.alias_(e.expression, e.name if e.this.is_string else e.this)
    4098                if isinstance(e, exp.PropertyEQ)
    4099                else e
    4100                for e in expression.expressions
    4101            ],
    4102        )
    4103
    4104        return self.function_fallback_sql(expression)

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

    4106    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
    4107        low = self.sql(expression, "this")
    4108        high = self.sql(expression, "expression")
    4109
    4110        return f"{low} TO {high}"

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

    4112    def truncatetable_sql(self, expression: exp.TruncateTable) -> str:
    4113        target = "DATABASE" if expression.args.get("is_database") else "TABLE"
    4114        tables = f" {self.expressions(expression)}"
    4115
    4116        exists = " IF EXISTS" if expression.args.get("exists") else ""
    4117
    4118        on_cluster = self.sql(expression, "cluster")
    4119        on_cluster = f" {on_cluster}" if on_cluster else ""
    4120
    4121        identity = self.sql(expression, "identity")
    4122        identity = f" {identity} IDENTITY" if identity else ""
    4123
    4124        option = self.sql(expression, "option")
    4125        option = f" {option}" if option else ""
    4126
    4127        partition = self.sql(expression, "partition")
    4128        partition = f" {partition}" if partition else ""
    4129
    4130        return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"

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

    4134    def convert_sql(self, expression: exp.Convert) -> str:
    4135        to = expression.this
    4136        value = expression.expression
    4137        style = expression.args.get("style")
    4138        safe = expression.args.get("safe")
    4139        strict = expression.args.get("strict")
    4140
    4141        if not to or not value:
    4142            return ""
    4143
    4144        # Retrieve length of datatype and override to default if not specified
    4145        if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    4146            to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
    4147
    4148        transformed: t.Optional[exp.Expression] = None
    4149        cast = exp.Cast if strict else exp.TryCast
    4150
    4151        # Check whether a conversion with format (T-SQL calls this 'style') is applicable
    4152        if isinstance(style, exp.Literal) and style.is_int:
    4153            from sqlglot.dialects.tsql import TSQL
    4154
    4155            style_value = style.name
    4156            converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value)
    4157            if not converted_style:
    4158                self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}")
    4159
    4160            fmt = exp.Literal.string(converted_style)
    4161
    4162            if to.this == exp.DataType.Type.DATE:
    4163                transformed = exp.StrToDate(this=value, format=fmt)
    4164            elif to.this in (exp.DataType.Type.DATETIME, exp.DataType.Type.DATETIME2):
    4165                transformed = exp.StrToTime(this=value, format=fmt)
    4166            elif to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    4167                transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe)
    4168            elif to.this == exp.DataType.Type.TEXT:
    4169                transformed = exp.TimeToStr(this=value, format=fmt)
    4170
    4171        if not transformed:
    4172            transformed = cast(this=value, to=to, safe=safe)
    4173
    4174        return self.sql(transformed)

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

    4234    def copyparameter_sql(self, expression: exp.CopyParameter) -> str:
    4235        option = self.sql(expression, "this")
    4236
    4237        if expression.expressions:
    4238            upper = option.upper()
    4239
    4240            # Snowflake FILE_FORMAT options are separated by whitespace
    4241            sep = " " if upper == "FILE_FORMAT" else ", "
    4242
    4243            # Databricks copy/format options do not set their list of values with EQ
    4244            op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = "
    4245            values = self.expressions(expression, flat=True, sep=sep)
    4246            return f"{option}{op}({values})"
    4247
    4248        value = self.sql(expression, "expression")
    4249
    4250        if not value:
    4251            return option
    4252
    4253        op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " "
    4254
    4255        return f"{option}{op}{value}"

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

    4257    def credentials_sql(self, expression: exp.Credentials) -> str:
    4258        cred_expr = expression.args.get("credentials")
    4259        if isinstance(cred_expr, exp.Literal):
    4260            # Redshift case: CREDENTIALS <string>
    4261            credentials = self.sql(expression, "credentials")
    4262            credentials = f"CREDENTIALS {credentials}" if credentials else ""
    4263        else:
    4264            # Snowflake case: CREDENTIALS = (...)
    4265            credentials = self.expressions(expression, key="credentials", flat=True, sep=" ")
    4266            credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else ""
    4267
    4268        storage = self.sql(expression, "storage")
    4269        storage = f"STORAGE_INTEGRATION = {storage}" if storage else ""
    4270
    4271        encryption = self.expressions(expression, key="encryption", flat=True, sep=" ")
    4272        encryption = f" ENCRYPTION = ({encryption})" if encryption else ""
    4273
    4274        iam_role = self.sql(expression, "iam_role")
    4275        iam_role = f"IAM_ROLE {iam_role}" if iam_role else ""
    4276
    4277        region = self.sql(expression, "region")
    4278        region = f" REGION {region}" if region else ""
    4279
    4280        return f"{credentials}{storage}{encryption}{iam_role}{region}"

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

    4282    def copy_sql(self, expression: exp.Copy) -> str:
    4283        this = self.sql(expression, "this")
    4284        this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}"
    4285
    4286        credentials = self.sql(expression, "credentials")
    4287        credentials = self.seg(credentials) if credentials else ""
    4288        kind = self.seg("FROM" if expression.args.get("kind") else "TO")
    4289        files = self.expressions(expression, key="files", flat=True)
    4290
    4291        sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " "
    4292        params = self.expressions(
    4293            expression,
    4294            key="params",
    4295            sep=sep,
    4296            new_line=True,
    4297            skip_last=True,
    4298            skip_first=True,
    4299            indent=self.COPY_PARAMS_ARE_WRAPPED,
    4300        )
    4301
    4302        if params:
    4303            if self.COPY_PARAMS_ARE_WRAPPED:
    4304                params = f" WITH ({params})"
    4305            elif not self.pretty:
    4306                params = f" {params}"
    4307
    4308        return f"COPY{this}{kind} {files}{credentials}{params}"

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

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

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

    4313    def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str:
    4314        on_sql = "ON" if expression.args.get("on") else "OFF"
    4315        filter_col: t.Optional[str] = self.sql(expression, "filter_column")
    4316        filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None
    4317        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    4318        retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None
    4319
    4320        if filter_col or retention_period:
    4321            on_sql = self.func("ON", filter_col, retention_period)
    4322
    4323        return f"DATA_DELETION={on_sql}"

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

    4325    def maskingpolicycolumnconstraint_sql(
    4326        self, expression: exp.MaskingPolicyColumnConstraint
    4327    ) -> str:
    4328        this = self.sql(expression, "this")
    4329        expressions = self.expressions(expression, flat=True)
    4330        expressions = f" USING ({expressions})" if expressions else ""
    4331        return f"MASKING POLICY {this}{expressions}"

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

    4333    def gapfill_sql(self, expression: exp.GapFill) -> str:
    4334        this = self.sql(expression, "this")
    4335        this = f"TABLE {this}"
    4336        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

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

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

    4341    def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str:
    4342        this = self.sql(expression, "this")
    4343        expr = expression.expression
    4344
    4345        if isinstance(expr, exp.Func):
    4346            # T-SQL's CLR functions are case sensitive
    4347            expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})"
    4348        else:
    4349            expr = self.sql(expression, "expression")
    4350
    4351        return self.scope_resolution(expr, this)

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

    4353    def parsejson_sql(self, expression: exp.ParseJSON) -> str:
    4354        if self.PARSE_JSON_NAME is None:
    4355            return self.sql(expression.this)
    4356
    4357        return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression)

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

    4359    def rand_sql(self, expression: exp.Rand) -> str:
    4360        lower = self.sql(expression, "lower")
    4361        upper = self.sql(expression, "upper")
    4362
    4363        if lower and upper:
    4364            return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}"
    4365        return self.func("RAND", expression.this)

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

    4367    def changes_sql(self, expression: exp.Changes) -> str:
    4368        information = self.sql(expression, "information")
    4369        information = f"INFORMATION => {information}"
    4370        at_before = self.sql(expression, "at_before")
    4371        at_before = f"{self.seg('')}{at_before}" if at_before else ""
    4372        end = self.sql(expression, "end")
    4373        end = f"{self.seg('')}{end}" if end else ""
    4374
    4375        return f"CHANGES ({information}){at_before}{end}"

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

    4377    def pad_sql(self, expression: exp.Pad) -> str:
    4378        prefix = "L" if expression.args.get("is_left") else "R"
    4379
    4380        fill_pattern = self.sql(expression, "fill_pattern") or None
    4381        if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED:
    4382            fill_pattern = "' '"
    4383
    4384        return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)

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

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

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

    4390    def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str:
    4391        generate_series = exp.GenerateSeries(**expression.args)
    4392
    4393        parent = expression.parent
    4394        if isinstance(parent, (exp.Alias, exp.TableAlias)):
    4395            parent = parent.parent
    4396
    4397        if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)):
    4398            return self.sql(exp.Unnest(expressions=[generate_series]))
    4399
    4400        if isinstance(parent, exp.Select):
    4401            self.unsupported("GenerateSeries projection unnesting is not supported.")
    4402
    4403        return self.sql(generate_series)

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

    4405    def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str:
    4406        exprs = expression.expressions
    4407        if not self.ARRAY_CONCAT_IS_VAR_LEN:
    4408            rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs)
    4409        else:
    4410            rhs = self.expressions(expression)
    4411
    4412        return self.func(name, expression.this, rhs or None)

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

    4414    def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str:
    4415        if self.SUPPORTS_CONVERT_TIMEZONE:
    4416            return self.function_fallback_sql(expression)
    4417
    4418        source_tz = expression.args.get("source_tz")
    4419        target_tz = expression.args.get("target_tz")
    4420        timestamp = expression.args.get("timestamp")
    4421
    4422        if source_tz and timestamp:
    4423            timestamp = exp.AtTimeZone(
    4424                this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz
    4425            )
    4426
    4427        expr = exp.AtTimeZone(this=timestamp, zone=target_tz)
    4428
    4429        return self.sql(expr)

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

    4431    def json_sql(self, expression: exp.JSON) -> str:
    4432        this = self.sql(expression, "this")
    4433        this = f" {this}" if this else ""
    4434
    4435        _with = expression.args.get("with")
    4436
    4437        if _with is None:
    4438            with_sql = ""
    4439        elif not _with:
    4440            with_sql = " WITHOUT"
    4441        else:
    4442            with_sql = " WITH"
    4443
    4444        unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else ""
    4445
    4446        return f"JSON{this}{with_sql}{unique_sql}"

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

    4448    def jsonvalue_sql(self, expression: exp.JSONValue) -> str:
    4449        def _generate_on_options(arg: t.Any) -> str:
    4450            return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}"
    4451
    4452        path = self.sql(expression, "path")
    4453        returning = self.sql(expression, "returning")
    4454        returning = f" RETURNING {returning}" if returning else ""
    4455
    4456        on_condition = self.sql(expression, "on_condition")
    4457        on_condition = f" {on_condition}" if on_condition else ""
    4458
    4459        return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}")

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

    4461    def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str:
    4462        else_ = "ELSE " if expression.args.get("else_") else ""
    4463        condition = self.sql(expression, "expression")
    4464        condition = f"WHEN {condition} THEN " if condition else else_
    4465        insert = self.sql(expression, "this")[len("INSERT") :].strip()
    4466        return f"{condition}{insert}"

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

    4468    def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str:
    4469        kind = self.sql(expression, "kind")
    4470        expressions = self.seg(self.expressions(expression, sep=" "))
    4471        res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}"
    4472        return res

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

    4474    def oncondition_sql(self, expression: exp.OnCondition) -> str:
    4475        # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR"
    4476        empty = expression.args.get("empty")
    4477        empty = (
    4478            f"DEFAULT {empty} ON EMPTY"
    4479            if isinstance(empty, exp.Expression)
    4480            else self.sql(expression, "empty")
    4481        )
    4482
    4483        error = expression.args.get("error")
    4484        error = (
    4485            f"DEFAULT {error} ON ERROR"
    4486            if isinstance(error, exp.Expression)
    4487            else self.sql(expression, "error")
    4488        )
    4489
    4490        if error and empty:
    4491            error = (
    4492                f"{empty} {error}"
    4493                if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR
    4494                else f"{error} {empty}"
    4495            )
    4496            empty = ""
    4497
    4498        null = self.sql(expression, "null")
    4499
    4500        return f"{empty}{error}{null}"

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

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

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

    4506    def jsonexists_sql(self, expression: exp.JSONExists) -> str:
    4507        this = self.sql(expression, "this")
    4508        path = self.sql(expression, "path")
    4509
    4510        passing = self.expressions(expression, "passing")
    4511        passing = f" PASSING {passing}" if passing else ""
    4512
    4513        on_condition = self.sql(expression, "on_condition")
    4514        on_condition = f" {on_condition}" if on_condition else ""
    4515
    4516        path = f"{path}{passing}{on_condition}"
    4517
    4518        return self.func("JSON_EXISTS", this, path)

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

    4520    def arrayagg_sql(self, expression: exp.ArrayAgg) -> str:
    4521        array_agg = self.function_fallback_sql(expression)
    4522
    4523        # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls
    4524        # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB)
    4525        if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"):
    4526            parent = expression.parent
    4527            if isinstance(parent, exp.Filter):
    4528                parent_cond = parent.expression.this
    4529                parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_()))
    4530            else:
    4531                this = expression.this
    4532                # Do not add the filter if the input is not a column (e.g. literal, struct etc)
    4533                if this.find(exp.Column):
    4534                    # DISTINCT is already present in the agg function, do not propagate it to FILTER as well
    4535                    this_sql = (
    4536                        self.expressions(this)
    4537                        if isinstance(this, exp.Distinct)
    4538                        else self.sql(expression, "this")
    4539                    )
    4540
    4541                    array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)"
    4542
    4543        return array_agg

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

    4545    def apply_sql(self, expression: exp.Apply) -> str:
    4546        this = self.sql(expression, "this")
    4547        expr = self.sql(expression, "expression")
    4548
    4549        return f"{this} APPLY({expr})"

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

    4551    def grant_sql(self, expression: exp.Grant) -> str:
    4552        privileges_sql = self.expressions(expression, key="privileges", flat=True)
    4553
    4554        kind = self.sql(expression, "kind")
    4555        kind = f" {kind}" if kind else ""
    4556
    4557        securable = self.sql(expression, "securable")
    4558        securable = f" {securable}" if securable else ""
    4559
    4560        principals = self.expressions(expression, key="principals", flat=True)
    4561
    4562        grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else ""
    4563
    4564        return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}"

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

    4566    def grantprivilege_sql(self, expression: exp.GrantPrivilege):
    4567        this = self.sql(expression, "this")
    4568        columns = self.expressions(expression, flat=True)
    4569        columns = f"({columns})" if columns else ""
    4570
    4571        return f"{this}{columns}"

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

    4573    def grantprincipal_sql(self, expression: exp.GrantPrincipal):
    4574        this = self.sql(expression, "this")
    4575
    4576        kind = self.sql(expression, "kind")
    4577        kind = f"{kind} " if kind else ""
    4578
    4579        return f"{kind}{this}"

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

    4581    def columns_sql(self, expression: exp.Columns):
    4582        func = self.function_fallback_sql(expression)
    4583        if expression.args.get("unpack"):
    4584            func = f"*{func}"
    4585
    4586        return func

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

    4588    def overlay_sql(self, expression: exp.Overlay):
    4589        this = self.sql(expression, "this")
    4590        expr = self.sql(expression, "expression")
    4591        from_sql = self.sql(expression, "from")
    4592        for_sql = self.sql(expression, "for")
    4593        for_sql = f" FOR {for_sql}" if for_sql else ""
    4594
    4595        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

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

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

    4601    def string_sql(self, expression: exp.String) -> str:
    4602        this = expression.this
    4603        zone = expression.args.get("zone")
    4604
    4605        if zone:
    4606            # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>)
    4607            # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC
    4608            # set for source_tz to transpile the time conversion before the STRING cast
    4609            this = exp.ConvertTimezone(
    4610                source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this
    4611            )
    4612
    4613        return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR))

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

    4615    def median_sql(self, expression: exp.Median):
    4616        if not self.SUPPORTS_MEDIAN:
    4617            return self.sql(
    4618                exp.PercentileCont(this=expression.this, expression=exp.Literal.number(0.5))
    4619            )
    4620
    4621        return self.function_fallback_sql(expression)

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

    4623    def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str:
    4624        filler = self.sql(expression, "this")
    4625        filler = f" {filler}" if filler else ""
    4626        with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT"
    4627        return f"TRUNCATE{filler} {with_count}"

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

    4629    def unixseconds_sql(self, expression: exp.UnixSeconds) -> str:
    4630        if self.SUPPORTS_UNIX_SECONDS:
    4631            return self.function_fallback_sql(expression)
    4632
    4633        start_ts = exp.cast(
    4634            exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ
    4635        )
    4636
    4637        return self.sql(
    4638            exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS"))
    4639        )

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

    4641    def arraysize_sql(self, expression: exp.ArraySize) -> str:
    4642        dim = expression.expression
    4643
    4644        # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension)
    4645        if dim and self.ARRAY_SIZE_DIM_REQUIRED is None:
    4646            if not (dim.is_int and dim.name == "1"):
    4647                self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH")
    4648            dim = None
    4649
    4650        # If dimension is required but not specified, default initialize it
    4651        if self.ARRAY_SIZE_DIM_REQUIRED and not dim:
    4652            dim = exp.Literal.number(1)
    4653
    4654        return self.func(self.ARRAY_SIZE_NAME, expression.this, dim)

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

    4656    def attach_sql(self, expression: exp.Attach) -> str:
    4657        this = self.sql(expression, "this")
    4658        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
    4659        expressions = self.expressions(expression)
    4660        expressions = f" ({expressions})" if expressions else ""
    4661
    4662        return f"ATTACH{exists_sql} {this}{expressions}"

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

    4664    def detach_sql(self, expression: exp.Detach) -> str:
    4665        this = self.sql(expression, "this")
    4666        exists_sql = " IF EXISTS" if expression.args.get("exists") else ""
    4667
    4668        return f"DETACH{exists_sql} {this}"

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

    4670    def attachoption_sql(self, expression: exp.AttachOption) -> str:
    4671        this = self.sql(expression, "this")
    4672        value = self.sql(expression, "expression")
    4673        value = f" {value}" if value else ""
    4674        return f"{this}{value}"

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

    4676    def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str:
    4677        this_sql = self.sql(expression, "this")
    4678        if isinstance(expression.this, exp.Table):
    4679            this_sql = f"TABLE {this_sql}"
    4680
    4681        return self.func(
    4682            "FEATURES_AT_TIME",
    4683            this_sql,
    4684            expression.args.get("time"),
    4685            expression.args.get("num_rows"),
    4686            expression.args.get("ignore_feature_nulls"),
    4687        )

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

    4689    def watermarkcolumnconstraint_sql(self, expression: exp.WatermarkColumnConstraint) -> str:
    4690        return (
    4691            f"WATERMARK FOR {self.sql(expression, 'this')} AS {self.sql(expression, 'expression')}"
    4692        )

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

    4694    def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str:
    4695        encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE"
    4696        encode = f"{encode} {self.sql(expression, 'this')}"
    4697
    4698        properties = expression.args.get("properties")
    4699        if properties:
    4700            encode = f"{encode} {self.properties(properties)}"
    4701
    4702        return encode

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

    4704    def includeproperty_sql(self, expression: exp.IncludeProperty) -> str:
    4705        this = self.sql(expression, "this")
    4706        include = f"INCLUDE {this}"
    4707
    4708        column_def = self.sql(expression, "column_def")
    4709        if column_def:
    4710            include = f"{include} {column_def}"
    4711
    4712        alias = self.sql(expression, "alias")
    4713        if alias:
    4714            include = f"{include} AS {alias}"
    4715
    4716        return include

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

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

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

    4722    def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str:
    4723        partitions = self.expressions(expression, "partition_expressions")
    4724        create = self.expressions(expression, "create_expressions")
    4725        return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}"

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

    4727    def partitionbyrangepropertydynamic_sql(
    4728        self, expression: exp.PartitionByRangePropertyDynamic
    4729    ) -> str:
    4730        start = self.sql(expression, "start")
    4731        end = self.sql(expression, "end")
    4732
    4733        every = expression.args["every"]
    4734        if isinstance(every, exp.Interval) and every.this.is_string:
    4735            every.this.replace(exp.Literal.number(every.name))
    4736
    4737        return f"START {self.wrap(start)} END {self.wrap(end)} EVERY {self.wrap(self.sql(every))}"

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

    4739    def unpivotcolumns_sql(self, expression: exp.UnpivotColumns) -> str:
    4740        name = self.sql(expression, "this")
    4741        values = self.expressions(expression, flat=True)
    4742
    4743        return f"NAME {name} VALUE {values}"

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

    4745    def analyzesample_sql(self, expression: exp.AnalyzeSample) -> str:
    4746        kind = self.sql(expression, "kind")
    4747        sample = self.sql(expression, "sample")
    4748        return f"SAMPLE {sample} {kind}"

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

    4750    def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str:
    4751        kind = self.sql(expression, "kind")
    4752        option = self.sql(expression, "option")
    4753        option = f" {option}" if option else ""
    4754        this = self.sql(expression, "this")
    4755        this = f" {this}" if this else ""
    4756        columns = self.expressions(expression)
    4757        columns = f" {columns}" if columns else ""
    4758        return f"{kind}{option} STATISTICS{this}{columns}"

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

    4760    def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str:
    4761        this = self.sql(expression, "this")
    4762        columns = self.expressions(expression)
    4763        inner_expression = self.sql(expression, "expression")
    4764        inner_expression = f" {inner_expression}" if inner_expression else ""
    4765        update_options = self.sql(expression, "update_options")
    4766        update_options = f" {update_options} UPDATE" if update_options else ""
    4767        return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}"

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

    4769    def analyzedelete_sql(self, expression: exp.AnalyzeDelete) -> str:
    4770        kind = self.sql(expression, "kind")
    4771        kind = f" {kind}" if kind else ""
    4772        return f"DELETE{kind} STATISTICS"

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

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

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

    4778    def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str:
    4779        kind = self.sql(expression, "kind")
    4780        this = self.sql(expression, "this")
    4781        this = f" {this}" if this else ""
    4782        inner_expression = self.sql(expression, "expression")
    4783        return f"VALIDATE {kind}{this}{inner_expression}"

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

    4785    def analyze_sql(self, expression: exp.Analyze) -> str:
    4786        options = self.expressions(expression, key="options", sep=" ")
    4787        options = f" {options}" if options else ""
    4788        kind = self.sql(expression, "kind")
    4789        kind = f" {kind}" if kind else ""
    4790        this = self.sql(expression, "this")
    4791        this = f" {this}" if this else ""
    4792        mode = self.sql(expression, "mode")
    4793        mode = f" {mode}" if mode else ""
    4794        properties = self.sql(expression, "properties")
    4795        properties = f" {properties}" if properties else ""
    4796        partition = self.sql(expression, "partition")
    4797        partition = f" {partition}" if partition else ""
    4798        inner_expression = self.sql(expression, "expression")
    4799        inner_expression = f" {inner_expression}" if inner_expression else ""
    4800        return f"ANALYZE{options}{kind}{this}{partition}{mode}{inner_expression}{properties}"

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

    4802    def xmltable_sql(self, expression: exp.XMLTable) -> str:
    4803        this = self.sql(expression, "this")
    4804        namespaces = self.expressions(expression, key="namespaces")
    4805        namespaces = f"XMLNAMESPACES({namespaces}), " if namespaces else ""
    4806        passing = self.expressions(expression, key="passing")
    4807        passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else ""
    4808        columns = self.expressions(expression, key="columns")
    4809        columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else ""
    4810        by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else ""
    4811        return f"XMLTABLE({self.sep('')}{self.indent(namespaces + this + passing + by_ref + columns)}{self.seg(')', sep='')}"

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

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

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

    4817    def export_sql(self, expression: exp.Export) -> str:
    4818        this = self.sql(expression, "this")
    4819        connection = self.sql(expression, "connection")
    4820        connection = f"WITH CONNECTION {connection} " if connection else ""
    4821        options = self.sql(expression, "options")
    4822        return f"EXPORT DATA {connection}{options} AS {this}"

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

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

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

    4827    def declareitem_sql(self, expression: exp.DeclareItem) -> str:
    4828        variable = self.sql(expression, "this")
    4829        default = self.sql(expression, "default")
    4830        default = f" = {default}" if default else ""
    4831
    4832        kind = self.sql(expression, "kind")
    4833        if isinstance(expression.args.get("kind"), exp.Schema):
    4834            kind = f"TABLE {kind}"
    4835
    4836        return f"{variable} AS {kind}{default}"

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

    4838    def recursivewithsearch_sql(self, expression: exp.RecursiveWithSearch) -> str:
    4839        kind = self.sql(expression, "kind")
    4840        this = self.sql(expression, "this")
    4841        set = self.sql(expression, "expression")
    4842        using = self.sql(expression, "using")
    4843        using = f" USING {using}" if using else ""
    4844
    4845        kind_sql = kind if kind == "CYCLE" else f"SEARCH {kind} FIRST BY"
    4846
    4847        return f"{kind_sql} {this} SET {set}{using}"

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

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

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

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

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

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

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

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

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

    4862    def show_sql(self, expression: exp.Show) -> str:
    4863        self.unsupported("Unsupported SHOW statement")
    4864        return ""

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

    4866    def put_sql(self, expression: exp.Put) -> str:
    4867        props = expression.args.get("properties")
    4868        props_sql = self.properties(props, prefix=" ", sep=" ", wrapped=False) if props else ""
    4869        this = self.sql(expression, "this")
    4870        target = self.sql(expression, "target")
    4871        return f"PUT {this} {target}{props_sql}"