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.CredentialsProperty: lambda self,
     136        e: f"CREDENTIALS=({self.expressions(e, 'expressions', sep=' ')})",
     137        exp.DateFormatColumnConstraint: lambda self, e: f"FORMAT {self.sql(e, 'this')}",
     138        exp.DefaultColumnConstraint: lambda self, e: f"DEFAULT {self.sql(e, 'this')}",
     139        exp.DynamicProperty: lambda *_: "DYNAMIC",
     140        exp.EmptyProperty: lambda *_: "EMPTY",
     141        exp.EncodeColumnConstraint: lambda self, e: f"ENCODE {self.sql(e, 'this')}",
     142        exp.EphemeralColumnConstraint: lambda self,
     143        e: f"EPHEMERAL{(' ' + self.sql(e, 'this')) if e.this else ''}",
     144        exp.ExcludeColumnConstraint: lambda self, e: f"EXCLUDE {self.sql(e, 'this').lstrip()}",
     145        exp.ExecuteAsProperty: lambda self, e: self.naked_property(e),
     146        exp.Except: lambda self, e: self.set_operations(e),
     147        exp.ExternalProperty: lambda *_: "EXTERNAL",
     148        exp.Floor: lambda self, e: self.ceil_floor(e),
     149        exp.GlobalProperty: lambda *_: "GLOBAL",
     150        exp.HeapProperty: lambda *_: "HEAP",
     151        exp.IcebergProperty: lambda *_: "ICEBERG",
     152        exp.InheritsProperty: lambda self, e: f"INHERITS ({self.expressions(e, flat=True)})",
     153        exp.InlineLengthColumnConstraint: lambda self, e: f"INLINE LENGTH {self.sql(e, 'this')}",
     154        exp.InputModelProperty: lambda self, e: f"INPUT{self.sql(e, 'this')}",
     155        exp.Intersect: lambda self, e: self.set_operations(e),
     156        exp.IntervalSpan: lambda self, e: f"{self.sql(e, 'this')} TO {self.sql(e, 'expression')}",
     157        exp.Int64: lambda self, e: self.sql(exp.cast(e.this, exp.DataType.Type.BIGINT)),
     158        exp.LanguageProperty: lambda self, e: self.naked_property(e),
     159        exp.LocationProperty: lambda self, e: self.naked_property(e),
     160        exp.LogProperty: lambda _, e: f"{'NO ' if e.args.get('no') else ''}LOG",
     161        exp.MaterializedProperty: lambda *_: "MATERIALIZED",
     162        exp.NonClusteredColumnConstraint: lambda self,
     163        e: f"NONCLUSTERED ({self.expressions(e, 'this', indent=False)})",
     164        exp.NoPrimaryIndexProperty: lambda *_: "NO PRIMARY INDEX",
     165        exp.NotForReplicationColumnConstraint: lambda *_: "NOT FOR REPLICATION",
     166        exp.OnCommitProperty: lambda _,
     167        e: f"ON COMMIT {'DELETE' if e.args.get('delete') else 'PRESERVE'} ROWS",
     168        exp.OnProperty: lambda self, e: f"ON {self.sql(e, 'this')}",
     169        exp.OnUpdateColumnConstraint: lambda self, e: f"ON UPDATE {self.sql(e, 'this')}",
     170        exp.Operator: lambda self, e: self.binary(e, ""),  # The operator is produced in `binary`
     171        exp.OutputModelProperty: lambda self, e: f"OUTPUT{self.sql(e, 'this')}",
     172        exp.PathColumnConstraint: lambda self, e: f"PATH {self.sql(e, 'this')}",
     173        exp.PivotAny: lambda self, e: f"ANY{self.sql(e, 'this')}",
     174        exp.ProjectionPolicyColumnConstraint: lambda self,
     175        e: f"PROJECTION POLICY {self.sql(e, 'this')}",
     176        exp.RemoteWithConnectionModelProperty: lambda self,
     177        e: f"REMOTE WITH CONNECTION {self.sql(e, 'this')}",
     178        exp.ReturnsProperty: lambda self, e: (
     179            "RETURNS NULL ON NULL INPUT" if e.args.get("null") else self.naked_property(e)
     180        ),
     181        exp.SampleProperty: lambda self, e: f"SAMPLE BY {self.sql(e, 'this')}",
     182        exp.SecureProperty: lambda *_: "SECURE",
     183        exp.SecurityProperty: lambda self, e: f"SECURITY {self.sql(e, 'this')}",
     184        exp.SetConfigProperty: lambda self, e: self.sql(e, "this"),
     185        exp.SetProperty: lambda _, e: f"{'MULTI' if e.args.get('multi') else ''}SET",
     186        exp.SettingsProperty: lambda self, e: f"SETTINGS{self.seg('')}{(self.expressions(e))}",
     187        exp.SharingProperty: lambda self, e: f"SHARING={self.sql(e, 'this')}",
     188        exp.SqlReadWriteProperty: lambda _, e: e.name,
     189        exp.SqlSecurityProperty: lambda _,
     190        e: f"SQL SECURITY {'DEFINER' if e.args.get('definer') else 'INVOKER'}",
     191        exp.StabilityProperty: lambda _, e: e.name,
     192        exp.Stream: lambda self, e: f"STREAM {self.sql(e, 'this')}",
     193        exp.StreamingTableProperty: lambda *_: "STREAMING",
     194        exp.StrictProperty: lambda *_: "STRICT",
     195        exp.SwapTable: lambda self, e: f"SWAP WITH {self.sql(e, 'this')}",
     196        exp.Tags: lambda self, e: f"TAG ({self.expressions(e, flat=True)})",
     197        exp.TemporaryProperty: lambda *_: "TEMPORARY",
     198        exp.TitleColumnConstraint: lambda self, e: f"TITLE {self.sql(e, 'this')}",
     199        exp.ToMap: lambda self, e: f"MAP {self.sql(e, 'this')}",
     200        exp.ToTableProperty: lambda self, e: f"TO {self.sql(e.this)}",
     201        exp.TransformModelProperty: lambda self, e: self.func("TRANSFORM", *e.expressions),
     202        exp.TransientProperty: lambda *_: "TRANSIENT",
     203        exp.Union: lambda self, e: self.set_operations(e),
     204        exp.UnloggedProperty: lambda *_: "UNLOGGED",
     205        exp.UsingTemplateProperty: lambda self, e: f"USING TEMPLATE {self.sql(e, 'this')}",
     206        exp.UsingData: lambda self, e: f"USING DATA {self.sql(e, 'this')}",
     207        exp.Uuid: lambda *_: "UUID()",
     208        exp.UppercaseColumnConstraint: lambda *_: "UPPERCASE",
     209        exp.VarMap: lambda self, e: self.func("MAP", e.args["keys"], e.args["values"]),
     210        exp.ViewAttributeProperty: lambda self, e: f"WITH {self.sql(e, 'this')}",
     211        exp.VolatileProperty: lambda *_: "VOLATILE",
     212        exp.WithJournalTableProperty: lambda self, e: f"WITH JOURNAL TABLE={self.sql(e, 'this')}",
     213        exp.WithProcedureOptions: lambda self, e: f"WITH {self.expressions(e, flat=True)}",
     214        exp.WithSchemaBindingProperty: lambda self, e: f"WITH SCHEMA {self.sql(e, 'this')}",
     215        exp.WithOperator: lambda self, e: f"{self.sql(e, 'this')} WITH {self.sql(e, 'op')}",
     216        exp.ForceProperty: lambda *_: "FORCE",
     217    }
     218
     219    # Whether null ordering is supported in order by
     220    # True: Full Support, None: No support, False: No support for certain cases
     221    # such as window specifications, aggregate functions etc
     222    NULL_ORDERING_SUPPORTED: t.Optional[bool] = True
     223
     224    # Whether ignore nulls is inside the agg or outside.
     225    # FIRST(x IGNORE NULLS) OVER vs FIRST (x) IGNORE NULLS OVER
     226    IGNORE_NULLS_IN_FUNC = False
     227
     228    # Whether locking reads (i.e. SELECT ... FOR UPDATE/SHARE) are supported
     229    LOCKING_READS_SUPPORTED = False
     230
     231    # Whether the EXCEPT and INTERSECT operations can return duplicates
     232    EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = True
     233
     234    # Wrap derived values in parens, usually standard but spark doesn't support it
     235    WRAP_DERIVED_VALUES = True
     236
     237    # Whether create function uses an AS before the RETURN
     238    CREATE_FUNCTION_RETURN_AS = True
     239
     240    # Whether MERGE ... WHEN MATCHED BY SOURCE is allowed
     241    MATCHED_BY_SOURCE = True
     242
     243    # Whether the INTERVAL expression works only with values like '1 day'
     244    SINGLE_STRING_INTERVAL = False
     245
     246    # Whether the plural form of date parts like day (i.e. "days") is supported in INTERVALs
     247    INTERVAL_ALLOWS_PLURAL_FORM = True
     248
     249    # Whether limit and fetch are supported (possible values: "ALL", "LIMIT", "FETCH")
     250    LIMIT_FETCH = "ALL"
     251
     252    # Whether limit and fetch allows expresions or just limits
     253    LIMIT_ONLY_LITERALS = False
     254
     255    # Whether a table is allowed to be renamed with a db
     256    RENAME_TABLE_WITH_DB = True
     257
     258    # The separator for grouping sets and rollups
     259    GROUPINGS_SEP = ","
     260
     261    # The string used for creating an index on a table
     262    INDEX_ON = "ON"
     263
     264    # Whether join hints should be generated
     265    JOIN_HINTS = True
     266
     267    # Whether table hints should be generated
     268    TABLE_HINTS = True
     269
     270    # Whether query hints should be generated
     271    QUERY_HINTS = True
     272
     273    # What kind of separator to use for query hints
     274    QUERY_HINT_SEP = ", "
     275
     276    # Whether comparing against booleans (e.g. x IS TRUE) is supported
     277    IS_BOOL_ALLOWED = True
     278
     279    # Whether to include the "SET" keyword in the "INSERT ... ON DUPLICATE KEY UPDATE" statement
     280    DUPLICATE_KEY_UPDATE_WITH_SET = True
     281
     282    # Whether to generate the limit as TOP <value> instead of LIMIT <value>
     283    LIMIT_IS_TOP = False
     284
     285    # Whether to generate INSERT INTO ... RETURNING or INSERT INTO RETURNING ...
     286    RETURNING_END = True
     287
     288    # Whether to generate an unquoted value for EXTRACT's date part argument
     289    EXTRACT_ALLOWS_QUOTES = True
     290
     291    # Whether TIMETZ / TIMESTAMPTZ will be generated using the "WITH TIME ZONE" syntax
     292    TZ_TO_WITH_TIME_ZONE = False
     293
     294    # Whether the NVL2 function is supported
     295    NVL2_SUPPORTED = True
     296
     297    # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax
     298    SELECT_KINDS: t.Tuple[str, ...] = ("STRUCT", "VALUE")
     299
     300    # Whether VALUES statements can be used as derived tables.
     301    # MySQL 5 and Redshift do not allow this, so when False, it will convert
     302    # SELECT * VALUES into SELECT UNION
     303    VALUES_AS_TABLE = True
     304
     305    # Whether the word COLUMN is included when adding a column with ALTER TABLE
     306    ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = True
     307
     308    # UNNEST WITH ORDINALITY (presto) instead of UNNEST WITH OFFSET (bigquery)
     309    UNNEST_WITH_ORDINALITY = True
     310
     311    # Whether FILTER (WHERE cond) can be used for conditional aggregation
     312    AGGREGATE_FILTER_SUPPORTED = True
     313
     314    # Whether JOIN sides (LEFT, RIGHT) are supported in conjunction with SEMI/ANTI join kinds
     315    SEMI_ANTI_JOIN_WITH_SIDE = True
     316
     317    # Whether to include the type of a computed column in the CREATE DDL
     318    COMPUTED_COLUMN_WITH_TYPE = True
     319
     320    # Whether CREATE TABLE .. COPY .. is supported. False means we'll generate CLONE instead of COPY
     321    SUPPORTS_TABLE_COPY = True
     322
     323    # Whether parentheses are required around the table sample's expression
     324    TABLESAMPLE_REQUIRES_PARENS = True
     325
     326    # Whether a table sample clause's size needs to be followed by the ROWS keyword
     327    TABLESAMPLE_SIZE_IS_ROWS = True
     328
     329    # The keyword(s) to use when generating a sample clause
     330    TABLESAMPLE_KEYWORDS = "TABLESAMPLE"
     331
     332    # Whether the TABLESAMPLE clause supports a method name, like BERNOULLI
     333    TABLESAMPLE_WITH_METHOD = True
     334
     335    # The keyword to use when specifying the seed of a sample clause
     336    TABLESAMPLE_SEED_KEYWORD = "SEED"
     337
     338    # Whether COLLATE is a function instead of a binary operator
     339    COLLATE_IS_FUNC = False
     340
     341    # Whether data types support additional specifiers like e.g. CHAR or BYTE (oracle)
     342    DATA_TYPE_SPECIFIERS_ALLOWED = False
     343
     344    # Whether conditions require booleans WHERE x = 0 vs WHERE x
     345    ENSURE_BOOLS = False
     346
     347    # Whether the "RECURSIVE" keyword is required when defining recursive CTEs
     348    CTE_RECURSIVE_KEYWORD_REQUIRED = True
     349
     350    # Whether CONCAT requires >1 arguments
     351    SUPPORTS_SINGLE_ARG_CONCAT = True
     352
     353    # Whether LAST_DAY function supports a date part argument
     354    LAST_DAY_SUPPORTS_DATE_PART = True
     355
     356    # Whether named columns are allowed in table aliases
     357    SUPPORTS_TABLE_ALIAS_COLUMNS = True
     358
     359    # Whether UNPIVOT aliases are Identifiers (False means they're Literals)
     360    UNPIVOT_ALIASES_ARE_IDENTIFIERS = True
     361
     362    # What delimiter to use for separating JSON key/value pairs
     363    JSON_KEY_VALUE_PAIR_SEP = ":"
     364
     365    # INSERT OVERWRITE TABLE x override
     366    INSERT_OVERWRITE = " OVERWRITE TABLE"
     367
     368    # Whether the SELECT .. INTO syntax is used instead of CTAS
     369    SUPPORTS_SELECT_INTO = False
     370
     371    # Whether UNLOGGED tables can be created
     372    SUPPORTS_UNLOGGED_TABLES = False
     373
     374    # Whether the CREATE TABLE LIKE statement is supported
     375    SUPPORTS_CREATE_TABLE_LIKE = True
     376
     377    # Whether the LikeProperty needs to be specified inside of the schema clause
     378    LIKE_PROPERTY_INSIDE_SCHEMA = False
     379
     380    # Whether DISTINCT can be followed by multiple args in an AggFunc. If not, it will be
     381    # transpiled into a series of CASE-WHEN-ELSE, ultimately using a tuple conseisting of the args
     382    MULTI_ARG_DISTINCT = True
     383
     384    # Whether the JSON extraction operators expect a value of type JSON
     385    JSON_TYPE_REQUIRED_FOR_EXTRACTION = False
     386
     387    # Whether bracketed keys like ["foo"] are supported in JSON paths
     388    JSON_PATH_BRACKETED_KEY_SUPPORTED = True
     389
     390    # Whether to escape keys using single quotes in JSON paths
     391    JSON_PATH_SINGLE_QUOTE_ESCAPE = False
     392
     393    # The JSONPathPart expressions supported by this dialect
     394    SUPPORTED_JSON_PATH_PARTS = ALL_JSON_PATH_PARTS.copy()
     395
     396    # Whether any(f(x) for x in array) can be implemented by this dialect
     397    CAN_IMPLEMENT_ARRAY_ANY = False
     398
     399    # Whether the function TO_NUMBER is supported
     400    SUPPORTS_TO_NUMBER = True
     401
     402    # Whether or not set op modifiers apply to the outer set op or select.
     403    # SELECT * FROM x UNION SELECT * FROM y LIMIT 1
     404    # True means limit 1 happens after the set op, False means it it happens on y.
     405    SET_OP_MODIFIERS = True
     406
     407    # Whether parameters from COPY statement are wrapped in parentheses
     408    COPY_PARAMS_ARE_WRAPPED = True
     409
     410    # Whether values of params are set with "=" token or empty space
     411    COPY_PARAMS_EQ_REQUIRED = False
     412
     413    # Whether COPY statement has INTO keyword
     414    COPY_HAS_INTO_KEYWORD = True
     415
     416    # Whether the conditional TRY(expression) function is supported
     417    TRY_SUPPORTED = True
     418
     419    # Whether the UESCAPE syntax in unicode strings is supported
     420    SUPPORTS_UESCAPE = True
     421
     422    # The keyword to use when generating a star projection with excluded columns
     423    STAR_EXCEPT = "EXCEPT"
     424
     425    # The HEX function name
     426    HEX_FUNC = "HEX"
     427
     428    # The keywords to use when prefixing & separating WITH based properties
     429    WITH_PROPERTIES_PREFIX = "WITH"
     430
     431    # Whether to quote the generated expression of exp.JsonPath
     432    QUOTE_JSON_PATH = True
     433
     434    # Whether the text pattern/fill (3rd) parameter of RPAD()/LPAD() is optional (defaults to space)
     435    PAD_FILL_PATTERN_IS_REQUIRED = False
     436
     437    # Whether a projection can explode into multiple rows, e.g. by unnesting an array.
     438    SUPPORTS_EXPLODING_PROJECTIONS = True
     439
     440    # Whether ARRAY_CONCAT can be generated with varlen args or if it should be reduced to 2-arg version
     441    ARRAY_CONCAT_IS_VAR_LEN = True
     442
     443    # Whether CONVERT_TIMEZONE() is supported; if not, it will be generated as exp.AtTimeZone
     444    SUPPORTS_CONVERT_TIMEZONE = False
     445
     446    # Whether MEDIAN(expr) is supported; if not, it will be generated as PERCENTILE_CONT(expr, 0.5)
     447    SUPPORTS_MEDIAN = True
     448
     449    # Whether UNIX_SECONDS(timestamp) is supported
     450    SUPPORTS_UNIX_SECONDS = False
     451
     452    # The name to generate for the JSONPath expression. If `None`, only `this` will be generated
     453    PARSE_JSON_NAME: t.Optional[str] = "PARSE_JSON"
     454
     455    # The function name of the exp.ArraySize expression
     456    ARRAY_SIZE_NAME: str = "ARRAY_LENGTH"
     457
     458    # The syntax to use when altering the type of a column
     459    ALTER_SET_TYPE = "SET DATA TYPE"
     460
     461    # Whether exp.ArraySize should generate the dimension arg too (valid for Postgres & DuckDB)
     462    # None -> Doesn't support it at all
     463    # False (DuckDB) -> Has backwards-compatible support, but preferably generated without
     464    # True (Postgres) -> Explicitly requires it
     465    ARRAY_SIZE_DIM_REQUIRED: t.Optional[bool] = None
     466
     467    TYPE_MAPPING = {
     468        exp.DataType.Type.DATETIME2: "TIMESTAMP",
     469        exp.DataType.Type.NCHAR: "CHAR",
     470        exp.DataType.Type.NVARCHAR: "VARCHAR",
     471        exp.DataType.Type.MEDIUMTEXT: "TEXT",
     472        exp.DataType.Type.LONGTEXT: "TEXT",
     473        exp.DataType.Type.TINYTEXT: "TEXT",
     474        exp.DataType.Type.BLOB: "VARBINARY",
     475        exp.DataType.Type.MEDIUMBLOB: "BLOB",
     476        exp.DataType.Type.LONGBLOB: "BLOB",
     477        exp.DataType.Type.TINYBLOB: "BLOB",
     478        exp.DataType.Type.INET: "INET",
     479        exp.DataType.Type.ROWVERSION: "VARBINARY",
     480        exp.DataType.Type.SMALLDATETIME: "TIMESTAMP",
     481    }
     482
     483    TIME_PART_SINGULARS = {
     484        "MICROSECONDS": "MICROSECOND",
     485        "SECONDS": "SECOND",
     486        "MINUTES": "MINUTE",
     487        "HOURS": "HOUR",
     488        "DAYS": "DAY",
     489        "WEEKS": "WEEK",
     490        "MONTHS": "MONTH",
     491        "QUARTERS": "QUARTER",
     492        "YEARS": "YEAR",
     493    }
     494
     495    AFTER_HAVING_MODIFIER_TRANSFORMS = {
     496        "cluster": lambda self, e: self.sql(e, "cluster"),
     497        "distribute": lambda self, e: self.sql(e, "distribute"),
     498        "sort": lambda self, e: self.sql(e, "sort"),
     499        "windows": lambda self, e: (
     500            self.seg("WINDOW ") + self.expressions(e, key="windows", flat=True)
     501            if e.args.get("windows")
     502            else ""
     503        ),
     504        "qualify": lambda self, e: self.sql(e, "qualify"),
     505    }
     506
     507    TOKEN_MAPPING: t.Dict[TokenType, str] = {}
     508
     509    STRUCT_DELIMITER = ("<", ">")
     510
     511    PARAMETER_TOKEN = "@"
     512    NAMED_PLACEHOLDER_TOKEN = ":"
     513
     514    EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: t.Set[str] = set()
     515
     516    PROPERTIES_LOCATION = {
     517        exp.AllowedValuesProperty: exp.Properties.Location.POST_SCHEMA,
     518        exp.AlgorithmProperty: exp.Properties.Location.POST_CREATE,
     519        exp.AutoIncrementProperty: exp.Properties.Location.POST_SCHEMA,
     520        exp.AutoRefreshProperty: exp.Properties.Location.POST_SCHEMA,
     521        exp.BackupProperty: exp.Properties.Location.POST_SCHEMA,
     522        exp.BlockCompressionProperty: exp.Properties.Location.POST_NAME,
     523        exp.CharacterSetProperty: exp.Properties.Location.POST_SCHEMA,
     524        exp.ChecksumProperty: exp.Properties.Location.POST_NAME,
     525        exp.CollateProperty: exp.Properties.Location.POST_SCHEMA,
     526        exp.CopyGrantsProperty: exp.Properties.Location.POST_SCHEMA,
     527        exp.Cluster: exp.Properties.Location.POST_SCHEMA,
     528        exp.ClusteredByProperty: exp.Properties.Location.POST_SCHEMA,
     529        exp.DistributedByProperty: exp.Properties.Location.POST_SCHEMA,
     530        exp.DuplicateKeyProperty: exp.Properties.Location.POST_SCHEMA,
     531        exp.DataBlocksizeProperty: exp.Properties.Location.POST_NAME,
     532        exp.DataDeletionProperty: exp.Properties.Location.POST_SCHEMA,
     533        exp.DefinerProperty: exp.Properties.Location.POST_CREATE,
     534        exp.DictRange: exp.Properties.Location.POST_SCHEMA,
     535        exp.DictProperty: exp.Properties.Location.POST_SCHEMA,
     536        exp.DynamicProperty: exp.Properties.Location.POST_CREATE,
     537        exp.DistKeyProperty: exp.Properties.Location.POST_SCHEMA,
     538        exp.DistStyleProperty: exp.Properties.Location.POST_SCHEMA,
     539        exp.EmptyProperty: exp.Properties.Location.POST_SCHEMA,
     540        exp.EncodeProperty: exp.Properties.Location.POST_EXPRESSION,
     541        exp.EngineProperty: exp.Properties.Location.POST_SCHEMA,
     542        exp.ExecuteAsProperty: exp.Properties.Location.POST_SCHEMA,
     543        exp.ExternalProperty: exp.Properties.Location.POST_CREATE,
     544        exp.FallbackProperty: exp.Properties.Location.POST_NAME,
     545        exp.FileFormatProperty: exp.Properties.Location.POST_WITH,
     546        exp.FreespaceProperty: exp.Properties.Location.POST_NAME,
     547        exp.GlobalProperty: exp.Properties.Location.POST_CREATE,
     548        exp.HeapProperty: exp.Properties.Location.POST_WITH,
     549        exp.InheritsProperty: exp.Properties.Location.POST_SCHEMA,
     550        exp.IcebergProperty: exp.Properties.Location.POST_CREATE,
     551        exp.IncludeProperty: exp.Properties.Location.POST_SCHEMA,
     552        exp.InputModelProperty: exp.Properties.Location.POST_SCHEMA,
     553        exp.IsolatedLoadingProperty: exp.Properties.Location.POST_NAME,
     554        exp.JournalProperty: exp.Properties.Location.POST_NAME,
     555        exp.LanguageProperty: exp.Properties.Location.POST_SCHEMA,
     556        exp.LikeProperty: exp.Properties.Location.POST_SCHEMA,
     557        exp.LocationProperty: exp.Properties.Location.POST_SCHEMA,
     558        exp.LockProperty: exp.Properties.Location.POST_SCHEMA,
     559        exp.LockingProperty: exp.Properties.Location.POST_ALIAS,
     560        exp.LogProperty: exp.Properties.Location.POST_NAME,
     561        exp.MaterializedProperty: exp.Properties.Location.POST_CREATE,
     562        exp.MergeBlockRatioProperty: exp.Properties.Location.POST_NAME,
     563        exp.NoPrimaryIndexProperty: exp.Properties.Location.POST_EXPRESSION,
     564        exp.OnProperty: exp.Properties.Location.POST_SCHEMA,
     565        exp.OnCommitProperty: exp.Properties.Location.POST_EXPRESSION,
     566        exp.Order: exp.Properties.Location.POST_SCHEMA,
     567        exp.OutputModelProperty: exp.Properties.Location.POST_SCHEMA,
     568        exp.PartitionedByProperty: exp.Properties.Location.POST_WITH,
     569        exp.PartitionedOfProperty: exp.Properties.Location.POST_SCHEMA,
     570        exp.PrimaryKey: exp.Properties.Location.POST_SCHEMA,
     571        exp.Property: exp.Properties.Location.POST_WITH,
     572        exp.RemoteWithConnectionModelProperty: exp.Properties.Location.POST_SCHEMA,
     573        exp.ReturnsProperty: exp.Properties.Location.POST_SCHEMA,
     574        exp.RowFormatProperty: exp.Properties.Location.POST_SCHEMA,
     575        exp.RowFormatDelimitedProperty: exp.Properties.Location.POST_SCHEMA,
     576        exp.RowFormatSerdeProperty: exp.Properties.Location.POST_SCHEMA,
     577        exp.SampleProperty: exp.Properties.Location.POST_SCHEMA,
     578        exp.SchemaCommentProperty: exp.Properties.Location.POST_SCHEMA,
     579        exp.SecureProperty: exp.Properties.Location.POST_CREATE,
     580        exp.SecurityProperty: exp.Properties.Location.POST_SCHEMA,
     581        exp.SerdeProperties: exp.Properties.Location.POST_SCHEMA,
     582        exp.Set: exp.Properties.Location.POST_SCHEMA,
     583        exp.SettingsProperty: exp.Properties.Location.POST_SCHEMA,
     584        exp.SetProperty: exp.Properties.Location.POST_CREATE,
     585        exp.SetConfigProperty: exp.Properties.Location.POST_SCHEMA,
     586        exp.SharingProperty: exp.Properties.Location.POST_EXPRESSION,
     587        exp.SequenceProperties: exp.Properties.Location.POST_EXPRESSION,
     588        exp.SortKeyProperty: exp.Properties.Location.POST_SCHEMA,
     589        exp.SqlReadWriteProperty: exp.Properties.Location.POST_SCHEMA,
     590        exp.SqlSecurityProperty: exp.Properties.Location.POST_CREATE,
     591        exp.StabilityProperty: exp.Properties.Location.POST_SCHEMA,
     592        exp.StorageHandlerProperty: exp.Properties.Location.POST_SCHEMA,
     593        exp.StreamingTableProperty: exp.Properties.Location.POST_CREATE,
     594        exp.StrictProperty: exp.Properties.Location.POST_SCHEMA,
     595        exp.Tags: exp.Properties.Location.POST_WITH,
     596        exp.TemporaryProperty: exp.Properties.Location.POST_CREATE,
     597        exp.ToTableProperty: exp.Properties.Location.POST_SCHEMA,
     598        exp.TransientProperty: exp.Properties.Location.POST_CREATE,
     599        exp.TransformModelProperty: exp.Properties.Location.POST_SCHEMA,
     600        exp.MergeTreeTTL: exp.Properties.Location.POST_SCHEMA,
     601        exp.UnloggedProperty: exp.Properties.Location.POST_CREATE,
     602        exp.UsingTemplateProperty: exp.Properties.Location.POST_SCHEMA,
     603        exp.ViewAttributeProperty: exp.Properties.Location.POST_SCHEMA,
     604        exp.VolatileProperty: exp.Properties.Location.POST_CREATE,
     605        exp.WithDataProperty: exp.Properties.Location.POST_EXPRESSION,
     606        exp.WithJournalTableProperty: exp.Properties.Location.POST_NAME,
     607        exp.WithProcedureOptions: exp.Properties.Location.POST_SCHEMA,
     608        exp.WithSchemaBindingProperty: exp.Properties.Location.POST_SCHEMA,
     609        exp.WithSystemVersioningProperty: exp.Properties.Location.POST_SCHEMA,
     610        exp.ForceProperty: exp.Properties.Location.POST_CREATE,
     611    }
     612
     613    # Keywords that can't be used as unquoted identifier names
     614    RESERVED_KEYWORDS: t.Set[str] = set()
     615
     616    # Expressions whose comments are separated from them for better formatting
     617    WITH_SEPARATED_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = (
     618        exp.Command,
     619        exp.Create,
     620        exp.Describe,
     621        exp.Delete,
     622        exp.Drop,
     623        exp.From,
     624        exp.Insert,
     625        exp.Join,
     626        exp.MultitableInserts,
     627        exp.Select,
     628        exp.SetOperation,
     629        exp.Update,
     630        exp.Where,
     631        exp.With,
     632    )
     633
     634    # Expressions that should not have their comments generated in maybe_comment
     635    EXCLUDE_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = (
     636        exp.Binary,
     637        exp.SetOperation,
     638    )
     639
     640    # Expressions that can remain unwrapped when appearing in the context of an INTERVAL
     641    UNWRAPPED_INTERVAL_VALUES: t.Tuple[t.Type[exp.Expression], ...] = (
     642        exp.Column,
     643        exp.Literal,
     644        exp.Neg,
     645        exp.Paren,
     646    )
     647
     648    PARAMETERIZABLE_TEXT_TYPES = {
     649        exp.DataType.Type.NVARCHAR,
     650        exp.DataType.Type.VARCHAR,
     651        exp.DataType.Type.CHAR,
     652        exp.DataType.Type.NCHAR,
     653    }
     654
     655    # Expressions that need to have all CTEs under them bubbled up to them
     656    EXPRESSIONS_WITHOUT_NESTED_CTES: t.Set[t.Type[exp.Expression]] = set()
     657
     658    SENTINEL_LINE_BREAK = "__SQLGLOT__LB__"
     659
     660    __slots__ = (
     661        "pretty",
     662        "identify",
     663        "normalize",
     664        "pad",
     665        "_indent",
     666        "normalize_functions",
     667        "unsupported_level",
     668        "max_unsupported",
     669        "leading_comma",
     670        "max_text_width",
     671        "comments",
     672        "dialect",
     673        "unsupported_messages",
     674        "_escaped_quote_end",
     675        "_escaped_identifier_end",
     676        "_next_name",
     677        "_identifier_start",
     678        "_identifier_end",
     679        "_quote_json_path_key_using_brackets",
     680    )
     681
     682    def __init__(
     683        self,
     684        pretty: t.Optional[bool] = None,
     685        identify: str | bool = False,
     686        normalize: bool = False,
     687        pad: int = 2,
     688        indent: int = 2,
     689        normalize_functions: t.Optional[str | bool] = None,
     690        unsupported_level: ErrorLevel = ErrorLevel.WARN,
     691        max_unsupported: int = 3,
     692        leading_comma: bool = False,
     693        max_text_width: int = 80,
     694        comments: bool = True,
     695        dialect: DialectType = None,
     696    ):
     697        import sqlglot
     698        from sqlglot.dialects import Dialect
     699
     700        self.pretty = pretty if pretty is not None else sqlglot.pretty
     701        self.identify = identify
     702        self.normalize = normalize
     703        self.pad = pad
     704        self._indent = indent
     705        self.unsupported_level = unsupported_level
     706        self.max_unsupported = max_unsupported
     707        self.leading_comma = leading_comma
     708        self.max_text_width = max_text_width
     709        self.comments = comments
     710        self.dialect = Dialect.get_or_raise(dialect)
     711
     712        # This is both a Dialect property and a Generator argument, so we prioritize the latter
     713        self.normalize_functions = (
     714            self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions
     715        )
     716
     717        self.unsupported_messages: t.List[str] = []
     718        self._escaped_quote_end: str = (
     719            self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END
     720        )
     721        self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2
     722
     723        self._next_name = name_sequence("_t")
     724
     725        self._identifier_start = self.dialect.IDENTIFIER_START
     726        self._identifier_end = self.dialect.IDENTIFIER_END
     727
     728        self._quote_json_path_key_using_brackets = True
     729
     730    def generate(self, expression: exp.Expression, copy: bool = True) -> str:
     731        """
     732        Generates the SQL string corresponding to the given syntax tree.
     733
     734        Args:
     735            expression: The syntax tree.
     736            copy: Whether to copy the expression. The generator performs mutations so
     737                it is safer to copy.
     738
     739        Returns:
     740            The SQL string corresponding to `expression`.
     741        """
     742        if copy:
     743            expression = expression.copy()
     744
     745        expression = self.preprocess(expression)
     746
     747        self.unsupported_messages = []
     748        sql = self.sql(expression).strip()
     749
     750        if self.pretty:
     751            sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n")
     752
     753        if self.unsupported_level == ErrorLevel.IGNORE:
     754            return sql
     755
     756        if self.unsupported_level == ErrorLevel.WARN:
     757            for msg in self.unsupported_messages:
     758                logger.warning(msg)
     759        elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages:
     760            raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported))
     761
     762        return sql
     763
     764    def preprocess(self, expression: exp.Expression) -> exp.Expression:
     765        """Apply generic preprocessing transformations to a given expression."""
     766        expression = self._move_ctes_to_top_level(expression)
     767
     768        if self.ENSURE_BOOLS:
     769            from sqlglot.transforms import ensure_bools
     770
     771            expression = ensure_bools(expression)
     772
     773        return expression
     774
     775    def _move_ctes_to_top_level(self, expression: E) -> E:
     776        if (
     777            not expression.parent
     778            and type(expression) in self.EXPRESSIONS_WITHOUT_NESTED_CTES
     779            and any(node.parent is not expression for node in expression.find_all(exp.With))
     780        ):
     781            from sqlglot.transforms import move_ctes_to_top_level
     782
     783            expression = move_ctes_to_top_level(expression)
     784        return expression
     785
     786    def unsupported(self, message: str) -> None:
     787        if self.unsupported_level == ErrorLevel.IMMEDIATE:
     788            raise UnsupportedError(message)
     789        self.unsupported_messages.append(message)
     790
     791    def sep(self, sep: str = " ") -> str:
     792        return f"{sep.strip()}\n" if self.pretty else sep
     793
     794    def seg(self, sql: str, sep: str = " ") -> str:
     795        return f"{self.sep(sep)}{sql}"
     796
     797    def pad_comment(self, comment: str) -> str:
     798        comment = " " + comment if comment[0].strip() else comment
     799        comment = comment + " " if comment[-1].strip() else comment
     800        return comment
     801
     802    def maybe_comment(
     803        self,
     804        sql: str,
     805        expression: t.Optional[exp.Expression] = None,
     806        comments: t.Optional[t.List[str]] = None,
     807        separated: bool = False,
     808    ) -> str:
     809        comments = (
     810            ((expression and expression.comments) if comments is None else comments)  # type: ignore
     811            if self.comments
     812            else None
     813        )
     814
     815        if not comments or isinstance(expression, self.EXCLUDE_COMMENTS):
     816            return sql
     817
     818        comments_sql = " ".join(
     819            f"/*{self.pad_comment(comment)}*/" for comment in comments if comment
     820        )
     821
     822        if not comments_sql:
     823            return sql
     824
     825        comments_sql = self._replace_line_breaks(comments_sql)
     826
     827        if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS):
     828            return (
     829                f"{self.sep()}{comments_sql}{sql}"
     830                if not sql or sql[0].isspace()
     831                else f"{comments_sql}{self.sep()}{sql}"
     832            )
     833
     834        return f"{sql} {comments_sql}"
     835
     836    def wrap(self, expression: exp.Expression | str) -> str:
     837        this_sql = (
     838            self.sql(expression)
     839            if isinstance(expression, exp.UNWRAPPED_QUERIES)
     840            else self.sql(expression, "this")
     841        )
     842        if not this_sql:
     843            return "()"
     844
     845        this_sql = self.indent(this_sql, level=1, pad=0)
     846        return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"
     847
     848    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
     849        original = self.identify
     850        self.identify = False
     851        result = func(*args, **kwargs)
     852        self.identify = original
     853        return result
     854
     855    def normalize_func(self, name: str) -> str:
     856        if self.normalize_functions == "upper" or self.normalize_functions is True:
     857            return name.upper()
     858        if self.normalize_functions == "lower":
     859            return name.lower()
     860        return name
     861
     862    def indent(
     863        self,
     864        sql: str,
     865        level: int = 0,
     866        pad: t.Optional[int] = None,
     867        skip_first: bool = False,
     868        skip_last: bool = False,
     869    ) -> str:
     870        if not self.pretty or not sql:
     871            return sql
     872
     873        pad = self.pad if pad is None else pad
     874        lines = sql.split("\n")
     875
     876        return "\n".join(
     877            (
     878                line
     879                if (skip_first and i == 0) or (skip_last and i == len(lines) - 1)
     880                else f"{' ' * (level * self._indent + pad)}{line}"
     881            )
     882            for i, line in enumerate(lines)
     883        )
     884
     885    def sql(
     886        self,
     887        expression: t.Optional[str | exp.Expression],
     888        key: t.Optional[str] = None,
     889        comment: bool = True,
     890    ) -> str:
     891        if not expression:
     892            return ""
     893
     894        if isinstance(expression, str):
     895            return expression
     896
     897        if key:
     898            value = expression.args.get(key)
     899            if value:
     900                return self.sql(value)
     901            return ""
     902
     903        transform = self.TRANSFORMS.get(expression.__class__)
     904
     905        if callable(transform):
     906            sql = transform(self, expression)
     907        elif isinstance(expression, exp.Expression):
     908            exp_handler_name = f"{expression.key}_sql"
     909
     910            if hasattr(self, exp_handler_name):
     911                sql = getattr(self, exp_handler_name)(expression)
     912            elif isinstance(expression, exp.Func):
     913                sql = self.function_fallback_sql(expression)
     914            elif isinstance(expression, exp.Property):
     915                sql = self.property_sql(expression)
     916            else:
     917                raise ValueError(f"Unsupported expression type {expression.__class__.__name__}")
     918        else:
     919            raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}")
     920
     921        return self.maybe_comment(sql, expression) if self.comments and comment else sql
     922
     923    def uncache_sql(self, expression: exp.Uncache) -> str:
     924        table = self.sql(expression, "this")
     925        exists_sql = " IF EXISTS" if expression.args.get("exists") else ""
     926        return f"UNCACHE TABLE{exists_sql} {table}"
     927
     928    def cache_sql(self, expression: exp.Cache) -> str:
     929        lazy = " LAZY" if expression.args.get("lazy") else ""
     930        table = self.sql(expression, "this")
     931        options = expression.args.get("options")
     932        options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else ""
     933        sql = self.sql(expression, "expression")
     934        sql = f" AS{self.sep()}{sql}" if sql else ""
     935        sql = f"CACHE{lazy} TABLE {table}{options}{sql}"
     936        return self.prepend_ctes(expression, sql)
     937
     938    def characterset_sql(self, expression: exp.CharacterSet) -> str:
     939        if isinstance(expression.parent, exp.Cast):
     940            return f"CHAR CHARACTER SET {self.sql(expression, 'this')}"
     941        default = "DEFAULT " if expression.args.get("default") else ""
     942        return f"{default}CHARACTER SET={self.sql(expression, 'this')}"
     943
     944    def column_parts(self, expression: exp.Column) -> str:
     945        return ".".join(
     946            self.sql(part)
     947            for part in (
     948                expression.args.get("catalog"),
     949                expression.args.get("db"),
     950                expression.args.get("table"),
     951                expression.args.get("this"),
     952            )
     953            if part
     954        )
     955
     956    def column_sql(self, expression: exp.Column) -> str:
     957        join_mark = " (+)" if expression.args.get("join_mark") else ""
     958
     959        if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS:
     960            join_mark = ""
     961            self.unsupported("Outer join syntax using the (+) operator is not supported.")
     962
     963        return f"{self.column_parts(expression)}{join_mark}"
     964
     965    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
     966        this = self.sql(expression, "this")
     967        this = f" {this}" if this else ""
     968        position = self.sql(expression, "position")
     969        return f"{position}{this}"
     970
     971    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
     972        column = self.sql(expression, "this")
     973        kind = self.sql(expression, "kind")
     974        constraints = self.expressions(expression, key="constraints", sep=" ", flat=True)
     975        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
     976        kind = f"{sep}{kind}" if kind else ""
     977        constraints = f" {constraints}" if constraints else ""
     978        position = self.sql(expression, "position")
     979        position = f" {position}" if position else ""
     980
     981        if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE:
     982            kind = ""
     983
     984        return f"{exists}{column}{kind}{constraints}{position}"
     985
     986    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
     987        this = self.sql(expression, "this")
     988        kind_sql = self.sql(expression, "kind").strip()
     989        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql
     990
     991    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
     992        this = self.sql(expression, "this")
     993        if expression.args.get("not_null"):
     994            persisted = " PERSISTED NOT NULL"
     995        elif expression.args.get("persisted"):
     996            persisted = " PERSISTED"
     997        else:
     998            persisted = ""
     999        return f"AS {this}{persisted}"
    1000
    1001    def autoincrementcolumnconstraint_sql(self, _) -> str:
    1002        return self.token_sql(TokenType.AUTO_INCREMENT)
    1003
    1004    def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str:
    1005        if isinstance(expression.this, list):
    1006            this = self.wrap(self.expressions(expression, key="this", flat=True))
    1007        else:
    1008            this = self.sql(expression, "this")
    1009
    1010        return f"COMPRESS {this}"
    1011
    1012    def generatedasidentitycolumnconstraint_sql(
    1013        self, expression: exp.GeneratedAsIdentityColumnConstraint
    1014    ) -> str:
    1015        this = ""
    1016        if expression.this is not None:
    1017            on_null = " ON NULL" if expression.args.get("on_null") else ""
    1018            this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}"
    1019
    1020        start = expression.args.get("start")
    1021        start = f"START WITH {start}" if start else ""
    1022        increment = expression.args.get("increment")
    1023        increment = f" INCREMENT BY {increment}" if increment else ""
    1024        minvalue = expression.args.get("minvalue")
    1025        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    1026        maxvalue = expression.args.get("maxvalue")
    1027        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    1028        cycle = expression.args.get("cycle")
    1029        cycle_sql = ""
    1030
    1031        if cycle is not None:
    1032            cycle_sql = f"{' NO' if not cycle else ''} CYCLE"
    1033            cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql
    1034
    1035        sequence_opts = ""
    1036        if start or increment or cycle_sql:
    1037            sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}"
    1038            sequence_opts = f" ({sequence_opts.strip()})"
    1039
    1040        expr = self.sql(expression, "expression")
    1041        expr = f"({expr})" if expr else "IDENTITY"
    1042
    1043        return f"GENERATED{this} AS {expr}{sequence_opts}"
    1044
    1045    def generatedasrowcolumnconstraint_sql(
    1046        self, expression: exp.GeneratedAsRowColumnConstraint
    1047    ) -> str:
    1048        start = "START" if expression.args.get("start") else "END"
    1049        hidden = " HIDDEN" if expression.args.get("hidden") else ""
    1050        return f"GENERATED ALWAYS AS ROW {start}{hidden}"
    1051
    1052    def periodforsystemtimeconstraint_sql(
    1053        self, expression: exp.PeriodForSystemTimeConstraint
    1054    ) -> str:
    1055        return f"PERIOD FOR SYSTEM_TIME ({self.sql(expression, 'this')}, {self.sql(expression, 'expression')})"
    1056
    1057    def notnullcolumnconstraint_sql(self, expression: exp.NotNullColumnConstraint) -> str:
    1058        return f"{'' if expression.args.get('allow_null') else 'NOT '}NULL"
    1059
    1060    def transformcolumnconstraint_sql(self, expression: exp.TransformColumnConstraint) -> str:
    1061        return f"AS {self.sql(expression, 'this')}"
    1062
    1063    def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str:
    1064        desc = expression.args.get("desc")
    1065        if desc is not None:
    1066            return f"PRIMARY KEY{' DESC' if desc else ' ASC'}"
    1067        return "PRIMARY KEY"
    1068
    1069    def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str:
    1070        this = self.sql(expression, "this")
    1071        this = f" {this}" if this else ""
    1072        index_type = expression.args.get("index_type")
    1073        index_type = f" USING {index_type}" if index_type else ""
    1074        on_conflict = self.sql(expression, "on_conflict")
    1075        on_conflict = f" {on_conflict}" if on_conflict else ""
    1076        nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else ""
    1077        return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}"
    1078
    1079    def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
    1080        return self.sql(expression, "this")
    1081
    1082    def create_sql(self, expression: exp.Create) -> str:
    1083        kind = self.sql(expression, "kind")
    1084        kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind
    1085        properties = expression.args.get("properties")
    1086        properties_locs = self.locate_properties(properties) if properties else defaultdict()
    1087
    1088        this = self.createable_sql(expression, properties_locs)
    1089
    1090        properties_sql = ""
    1091        if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get(
    1092            exp.Properties.Location.POST_WITH
    1093        ):
    1094            properties_sql = self.sql(
    1095                exp.Properties(
    1096                    expressions=[
    1097                        *properties_locs[exp.Properties.Location.POST_SCHEMA],
    1098                        *properties_locs[exp.Properties.Location.POST_WITH],
    1099                    ]
    1100                )
    1101            )
    1102
    1103            if properties_locs.get(exp.Properties.Location.POST_SCHEMA):
    1104                properties_sql = self.sep() + properties_sql
    1105            elif not self.pretty:
    1106                # Standalone POST_WITH properties need a leading whitespace in non-pretty mode
    1107                properties_sql = f" {properties_sql}"
    1108
    1109        begin = " BEGIN" if expression.args.get("begin") else ""
    1110        end = " END" if expression.args.get("end") else ""
    1111
    1112        expression_sql = self.sql(expression, "expression")
    1113        if expression_sql:
    1114            expression_sql = f"{begin}{self.sep()}{expression_sql}{end}"
    1115
    1116            if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return):
    1117                postalias_props_sql = ""
    1118                if properties_locs.get(exp.Properties.Location.POST_ALIAS):
    1119                    postalias_props_sql = self.properties(
    1120                        exp.Properties(
    1121                            expressions=properties_locs[exp.Properties.Location.POST_ALIAS]
    1122                        ),
    1123                        wrapped=False,
    1124                    )
    1125                postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else ""
    1126                expression_sql = f" AS{postalias_props_sql}{expression_sql}"
    1127
    1128        postindex_props_sql = ""
    1129        if properties_locs.get(exp.Properties.Location.POST_INDEX):
    1130            postindex_props_sql = self.properties(
    1131                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]),
    1132                wrapped=False,
    1133                prefix=" ",
    1134            )
    1135
    1136        indexes = self.expressions(expression, key="indexes", indent=False, sep=" ")
    1137        indexes = f" {indexes}" if indexes else ""
    1138        index_sql = indexes + postindex_props_sql
    1139
    1140        replace = " OR REPLACE" if expression.args.get("replace") else ""
    1141        refresh = " OR REFRESH" if expression.args.get("refresh") else ""
    1142        unique = " UNIQUE" if expression.args.get("unique") else ""
    1143
    1144        clustered = expression.args.get("clustered")
    1145        if clustered is None:
    1146            clustered_sql = ""
    1147        elif clustered:
    1148            clustered_sql = " CLUSTERED COLUMNSTORE"
    1149        else:
    1150            clustered_sql = " NONCLUSTERED COLUMNSTORE"
    1151
    1152        postcreate_props_sql = ""
    1153        if properties_locs.get(exp.Properties.Location.POST_CREATE):
    1154            postcreate_props_sql = self.properties(
    1155                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]),
    1156                sep=" ",
    1157                prefix=" ",
    1158                wrapped=False,
    1159            )
    1160
    1161        modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql))
    1162
    1163        postexpression_props_sql = ""
    1164        if properties_locs.get(exp.Properties.Location.POST_EXPRESSION):
    1165            postexpression_props_sql = self.properties(
    1166                exp.Properties(
    1167                    expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION]
    1168                ),
    1169                sep=" ",
    1170                prefix=" ",
    1171                wrapped=False,
    1172            )
    1173
    1174        concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else ""
    1175        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
    1176        no_schema_binding = (
    1177            " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else ""
    1178        )
    1179
    1180        clone = self.sql(expression, "clone")
    1181        clone = f" {clone}" if clone else ""
    1182
    1183        if kind in self.EXPRESSION_PRECEDES_PROPERTIES_CREATABLES:
    1184            properties_expression = f"{expression_sql}{properties_sql}"
    1185        else:
    1186            properties_expression = f"{properties_sql}{expression_sql}"
    1187
    1188        expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_expression}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}"
    1189        return self.prepend_ctes(expression, expression_sql)
    1190
    1191    def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str:
    1192        start = self.sql(expression, "start")
    1193        start = f"START WITH {start}" if start else ""
    1194        increment = self.sql(expression, "increment")
    1195        increment = f" INCREMENT BY {increment}" if increment else ""
    1196        minvalue = self.sql(expression, "minvalue")
    1197        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    1198        maxvalue = self.sql(expression, "maxvalue")
    1199        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    1200        owned = self.sql(expression, "owned")
    1201        owned = f" OWNED BY {owned}" if owned else ""
    1202
    1203        cache = expression.args.get("cache")
    1204        if cache is None:
    1205            cache_str = ""
    1206        elif cache is True:
    1207            cache_str = " CACHE"
    1208        else:
    1209            cache_str = f" CACHE {cache}"
    1210
    1211        options = self.expressions(expression, key="options", flat=True, sep=" ")
    1212        options = f" {options}" if options else ""
    1213
    1214        return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip()
    1215
    1216    def clone_sql(self, expression: exp.Clone) -> str:
    1217        this = self.sql(expression, "this")
    1218        shallow = "SHALLOW " if expression.args.get("shallow") else ""
    1219        keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE"
    1220        return f"{shallow}{keyword} {this}"
    1221
    1222    def describe_sql(self, expression: exp.Describe) -> str:
    1223        style = expression.args.get("style")
    1224        style = f" {style}" if style else ""
    1225        partition = self.sql(expression, "partition")
    1226        partition = f" {partition}" if partition else ""
    1227        format = self.sql(expression, "format")
    1228        format = f" {format}" if format else ""
    1229
    1230        return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}"
    1231
    1232    def heredoc_sql(self, expression: exp.Heredoc) -> str:
    1233        tag = self.sql(expression, "tag")
    1234        return f"${tag}${self.sql(expression, 'this')}${tag}$"
    1235
    1236    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
    1237        with_ = self.sql(expression, "with")
    1238        if with_:
    1239            sql = f"{with_}{self.sep()}{sql}"
    1240        return sql
    1241
    1242    def with_sql(self, expression: exp.With) -> str:
    1243        sql = self.expressions(expression, flat=True)
    1244        recursive = (
    1245            "RECURSIVE "
    1246            if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive")
    1247            else ""
    1248        )
    1249        search = self.sql(expression, "search")
    1250        search = f" {search}" if search else ""
    1251
    1252        return f"WITH {recursive}{sql}{search}"
    1253
    1254    def cte_sql(self, expression: exp.CTE) -> str:
    1255        alias = expression.args.get("alias")
    1256        if alias:
    1257            alias.add_comments(expression.pop_comments())
    1258
    1259        alias_sql = self.sql(expression, "alias")
    1260
    1261        materialized = expression.args.get("materialized")
    1262        if materialized is False:
    1263            materialized = "NOT MATERIALIZED "
    1264        elif materialized:
    1265            materialized = "MATERIALIZED "
    1266
    1267        return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}"
    1268
    1269    def tablealias_sql(self, expression: exp.TableAlias) -> str:
    1270        alias = self.sql(expression, "this")
    1271        columns = self.expressions(expression, key="columns", flat=True)
    1272        columns = f"({columns})" if columns else ""
    1273
    1274        if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS:
    1275            columns = ""
    1276            self.unsupported("Named columns are not supported in table alias.")
    1277
    1278        if not alias and not self.dialect.UNNEST_COLUMN_ONLY:
    1279            alias = self._next_name()
    1280
    1281        return f"{alias}{columns}"
    1282
    1283    def bitstring_sql(self, expression: exp.BitString) -> str:
    1284        this = self.sql(expression, "this")
    1285        if self.dialect.BIT_START:
    1286            return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}"
    1287        return f"{int(this, 2)}"
    1288
    1289    def hexstring_sql(
    1290        self, expression: exp.HexString, binary_function_repr: t.Optional[str] = None
    1291    ) -> str:
    1292        this = self.sql(expression, "this")
    1293        is_integer_type = expression.args.get("is_integer")
    1294
    1295        if (is_integer_type and not self.dialect.HEX_STRING_IS_INTEGER_TYPE) or (
    1296            not self.dialect.HEX_START and not binary_function_repr
    1297        ):
    1298            # Integer representation will be returned if:
    1299            # - The read dialect treats the hex value as integer literal but not the write
    1300            # - The transpilation is not supported (write dialect hasn't set HEX_START or the param flag)
    1301            return f"{int(this, 16)}"
    1302
    1303        if not is_integer_type:
    1304            # Read dialect treats the hex value as BINARY/BLOB
    1305            if binary_function_repr:
    1306                # The write dialect supports the transpilation to its equivalent BINARY/BLOB
    1307                return self.func(binary_function_repr, exp.Literal.string(this))
    1308            if self.dialect.HEX_STRING_IS_INTEGER_TYPE:
    1309                # The write dialect does not support the transpilation, it'll treat the hex value as INTEGER
    1310                self.unsupported("Unsupported transpilation from BINARY/BLOB hex string")
    1311
    1312        return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"
    1313
    1314    def bytestring_sql(self, expression: exp.ByteString) -> str:
    1315        this = self.sql(expression, "this")
    1316        if self.dialect.BYTE_START:
    1317            return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}"
    1318        return this
    1319
    1320    def unicodestring_sql(self, expression: exp.UnicodeString) -> str:
    1321        this = self.sql(expression, "this")
    1322        escape = expression.args.get("escape")
    1323
    1324        if self.dialect.UNICODE_START:
    1325            escape_substitute = r"\\\1"
    1326            left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END
    1327        else:
    1328            escape_substitute = r"\\u\1"
    1329            left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END
    1330
    1331        if escape:
    1332            escape_pattern = re.compile(rf"{escape.name}(\d+)")
    1333            escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else ""
    1334        else:
    1335            escape_pattern = ESCAPED_UNICODE_RE
    1336            escape_sql = ""
    1337
    1338        if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE):
    1339            this = escape_pattern.sub(escape_substitute, this)
    1340
    1341        return f"{left_quote}{this}{right_quote}{escape_sql}"
    1342
    1343    def rawstring_sql(self, expression: exp.RawString) -> str:
    1344        string = self.escape_str(expression.this.replace("\\", "\\\\"), escape_backslash=False)
    1345        return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}"
    1346
    1347    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
    1348        this = self.sql(expression, "this")
    1349        specifier = self.sql(expression, "expression")
    1350        specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else ""
    1351        return f"{this}{specifier}"
    1352
    1353    def datatype_sql(self, expression: exp.DataType) -> str:
    1354        nested = ""
    1355        values = ""
    1356        interior = self.expressions(expression, flat=True)
    1357
    1358        type_value = expression.this
    1359        if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"):
    1360            type_sql = self.sql(expression, "kind")
    1361        else:
    1362            type_sql = (
    1363                self.TYPE_MAPPING.get(type_value, type_value.value)
    1364                if isinstance(type_value, exp.DataType.Type)
    1365                else type_value
    1366            )
    1367
    1368        if interior:
    1369            if expression.args.get("nested"):
    1370                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
    1371                if expression.args.get("values") is not None:
    1372                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
    1373                    values = self.expressions(expression, key="values", flat=True)
    1374                    values = f"{delimiters[0]}{values}{delimiters[1]}"
    1375            elif type_value == exp.DataType.Type.INTERVAL:
    1376                nested = f" {interior}"
    1377            else:
    1378                nested = f"({interior})"
    1379
    1380        type_sql = f"{type_sql}{nested}{values}"
    1381        if self.TZ_TO_WITH_TIME_ZONE and type_value in (
    1382            exp.DataType.Type.TIMETZ,
    1383            exp.DataType.Type.TIMESTAMPTZ,
    1384        ):
    1385            type_sql = f"{type_sql} WITH TIME ZONE"
    1386
    1387        return type_sql
    1388
    1389    def directory_sql(self, expression: exp.Directory) -> str:
    1390        local = "LOCAL " if expression.args.get("local") else ""
    1391        row_format = self.sql(expression, "row_format")
    1392        row_format = f" {row_format}" if row_format else ""
    1393        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"
    1394
    1395    def delete_sql(self, expression: exp.Delete) -> str:
    1396        this = self.sql(expression, "this")
    1397        this = f" FROM {this}" if this else ""
    1398        using = self.sql(expression, "using")
    1399        using = f" USING {using}" if using else ""
    1400        cluster = self.sql(expression, "cluster")
    1401        cluster = f" {cluster}" if cluster else ""
    1402        where = self.sql(expression, "where")
    1403        returning = self.sql(expression, "returning")
    1404        limit = self.sql(expression, "limit")
    1405        tables = self.expressions(expression, key="tables")
    1406        tables = f" {tables}" if tables else ""
    1407        if self.RETURNING_END:
    1408            expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}"
    1409        else:
    1410            expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}"
    1411        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")
    1412
    1413    def drop_sql(self, expression: exp.Drop) -> str:
    1414        this = self.sql(expression, "this")
    1415        expressions = self.expressions(expression, flat=True)
    1416        expressions = f" ({expressions})" if expressions else ""
    1417        kind = expression.args["kind"]
    1418        kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind
    1419        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    1420        concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else ""
    1421        on_cluster = self.sql(expression, "cluster")
    1422        on_cluster = f" {on_cluster}" if on_cluster else ""
    1423        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    1424        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    1425        cascade = " CASCADE" if expression.args.get("cascade") else ""
    1426        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
    1427        purge = " PURGE" if expression.args.get("purge") else ""
    1428        return f"DROP{temporary}{materialized} {kind}{concurrently_sql}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}"
    1429
    1430    def set_operation(self, expression: exp.SetOperation) -> str:
    1431        op_type = type(expression)
    1432        op_name = op_type.key.upper()
    1433
    1434        distinct = expression.args.get("distinct")
    1435        if (
    1436            distinct is False
    1437            and op_type in (exp.Except, exp.Intersect)
    1438            and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE
    1439        ):
    1440            self.unsupported(f"{op_name} ALL is not supported")
    1441
    1442        default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type]
    1443
    1444        if distinct is None:
    1445            distinct = default_distinct
    1446            if distinct is None:
    1447                self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified")
    1448
    1449        if distinct is default_distinct:
    1450            distinct_or_all = ""
    1451        else:
    1452            distinct_or_all = " DISTINCT" if distinct else " ALL"
    1453
    1454        side_kind = " ".join(filter(None, [expression.side, expression.kind]))
    1455        side_kind = f"{side_kind} " if side_kind else ""
    1456
    1457        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1458        on = self.expressions(expression, key="on", flat=True)
    1459        on = f" ON ({on})" if on else ""
    1460
    1461        return f"{side_kind}{op_name}{distinct_or_all}{by_name}{on}"
    1462
    1463    def set_operations(self, expression: exp.SetOperation) -> str:
    1464        if not self.SET_OP_MODIFIERS:
    1465            limit = expression.args.get("limit")
    1466            order = expression.args.get("order")
    1467
    1468            if limit or order:
    1469                select = self._move_ctes_to_top_level(
    1470                    exp.subquery(expression, "_l_0", copy=False).select("*", copy=False)
    1471                )
    1472
    1473                if limit:
    1474                    select = select.limit(limit.pop(), copy=False)
    1475                if order:
    1476                    select = select.order_by(order.pop(), copy=False)
    1477                return self.sql(select)
    1478
    1479        sqls: t.List[str] = []
    1480        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    1481
    1482        while stack:
    1483            node = stack.pop()
    1484
    1485            if isinstance(node, exp.SetOperation):
    1486                stack.append(node.expression)
    1487                stack.append(
    1488                    self.maybe_comment(
    1489                        self.set_operation(node), comments=node.comments, separated=True
    1490                    )
    1491                )
    1492                stack.append(node.this)
    1493            else:
    1494                sqls.append(self.sql(node))
    1495
    1496        this = self.sep().join(sqls)
    1497        this = self.query_modifiers(expression, this)
    1498        return self.prepend_ctes(expression, this)
    1499
    1500    def fetch_sql(self, expression: exp.Fetch) -> str:
    1501        direction = expression.args.get("direction")
    1502        direction = f" {direction}" if direction else ""
    1503        count = self.sql(expression, "count")
    1504        count = f" {count}" if count else ""
    1505        limit_options = self.sql(expression, "limit_options")
    1506        limit_options = f"{limit_options}" if limit_options else " ROWS ONLY"
    1507        return f"{self.seg('FETCH')}{direction}{count}{limit_options}"
    1508
    1509    def limitoptions_sql(self, expression: exp.LimitOptions) -> str:
    1510        percent = " PERCENT" if expression.args.get("percent") else ""
    1511        rows = " ROWS" if expression.args.get("rows") else ""
    1512        with_ties = " WITH TIES" if expression.args.get("with_ties") else ""
    1513        if not with_ties and rows:
    1514            with_ties = " ONLY"
    1515        return f"{percent}{rows}{with_ties}"
    1516
    1517    def filter_sql(self, expression: exp.Filter) -> str:
    1518        if self.AGGREGATE_FILTER_SUPPORTED:
    1519            this = self.sql(expression, "this")
    1520            where = self.sql(expression, "expression").strip()
    1521            return f"{this} FILTER({where})"
    1522
    1523        agg = expression.this
    1524        agg_arg = agg.this
    1525        cond = expression.expression.this
    1526        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
    1527        return self.sql(agg)
    1528
    1529    def hint_sql(self, expression: exp.Hint) -> str:
    1530        if not self.QUERY_HINTS:
    1531            self.unsupported("Hints are not supported")
    1532            return ""
    1533
    1534        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"
    1535
    1536    def indexparameters_sql(self, expression: exp.IndexParameters) -> str:
    1537        using = self.sql(expression, "using")
    1538        using = f" USING {using}" if using else ""
    1539        columns = self.expressions(expression, key="columns", flat=True)
    1540        columns = f"({columns})" if columns else ""
    1541        partition_by = self.expressions(expression, key="partition_by", flat=True)
    1542        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
    1543        where = self.sql(expression, "where")
    1544        include = self.expressions(expression, key="include", flat=True)
    1545        if include:
    1546            include = f" INCLUDE ({include})"
    1547        with_storage = self.expressions(expression, key="with_storage", flat=True)
    1548        with_storage = f" WITH ({with_storage})" if with_storage else ""
    1549        tablespace = self.sql(expression, "tablespace")
    1550        tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else ""
    1551        on = self.sql(expression, "on")
    1552        on = f" ON {on}" if on else ""
    1553
    1554        return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"
    1555
    1556    def index_sql(self, expression: exp.Index) -> str:
    1557        unique = "UNIQUE " if expression.args.get("unique") else ""
    1558        primary = "PRIMARY " if expression.args.get("primary") else ""
    1559        amp = "AMP " if expression.args.get("amp") else ""
    1560        name = self.sql(expression, "this")
    1561        name = f"{name} " if name else ""
    1562        table = self.sql(expression, "table")
    1563        table = f"{self.INDEX_ON} {table}" if table else ""
    1564
    1565        index = "INDEX " if not table else ""
    1566
    1567        params = self.sql(expression, "params")
    1568        return f"{unique}{primary}{amp}{index}{name}{table}{params}"
    1569
    1570    def identifier_sql(self, expression: exp.Identifier) -> str:
    1571        text = expression.name
    1572        lower = text.lower()
    1573        text = lower if self.normalize and not expression.quoted else text
    1574        text = text.replace(self._identifier_end, self._escaped_identifier_end)
    1575        if (
    1576            expression.quoted
    1577            or self.dialect.can_identify(text, self.identify)
    1578            or lower in self.RESERVED_KEYWORDS
    1579            or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
    1580        ):
    1581            text = f"{self._identifier_start}{text}{self._identifier_end}"
    1582        return text
    1583
    1584    def hex_sql(self, expression: exp.Hex) -> str:
    1585        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1586        if self.dialect.HEX_LOWERCASE:
    1587            text = self.func("LOWER", text)
    1588
    1589        return text
    1590
    1591    def lowerhex_sql(self, expression: exp.LowerHex) -> str:
    1592        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1593        if not self.dialect.HEX_LOWERCASE:
    1594            text = self.func("LOWER", text)
    1595        return text
    1596
    1597    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    1598        input_format = self.sql(expression, "input_format")
    1599        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    1600        output_format = self.sql(expression, "output_format")
    1601        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    1602        return self.sep().join((input_format, output_format))
    1603
    1604    def national_sql(self, expression: exp.National, prefix: str = "N") -> str:
    1605        string = self.sql(exp.Literal.string(expression.name))
    1606        return f"{prefix}{string}"
    1607
    1608    def partition_sql(self, expression: exp.Partition) -> str:
    1609        partition_keyword = "SUBPARTITION" if expression.args.get("subpartition") else "PARTITION"
    1610        return f"{partition_keyword}({self.expressions(expression, flat=True)})"
    1611
    1612    def properties_sql(self, expression: exp.Properties) -> str:
    1613        root_properties = []
    1614        with_properties = []
    1615
    1616        for p in expression.expressions:
    1617            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1618            if p_loc == exp.Properties.Location.POST_WITH:
    1619                with_properties.append(p)
    1620            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    1621                root_properties.append(p)
    1622
    1623        root_props = self.root_properties(exp.Properties(expressions=root_properties))
    1624        with_props = self.with_properties(exp.Properties(expressions=with_properties))
    1625
    1626        if root_props and with_props and not self.pretty:
    1627            with_props = " " + with_props
    1628
    1629        return root_props + with_props
    1630
    1631    def root_properties(self, properties: exp.Properties) -> str:
    1632        if properties.expressions:
    1633            return self.expressions(properties, indent=False, sep=" ")
    1634        return ""
    1635
    1636    def properties(
    1637        self,
    1638        properties: exp.Properties,
    1639        prefix: str = "",
    1640        sep: str = ", ",
    1641        suffix: str = "",
    1642        wrapped: bool = True,
    1643    ) -> str:
    1644        if properties.expressions:
    1645            expressions = self.expressions(properties, sep=sep, indent=False)
    1646            if expressions:
    1647                expressions = self.wrap(expressions) if wrapped else expressions
    1648                return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}"
    1649        return ""
    1650
    1651    def with_properties(self, properties: exp.Properties) -> str:
    1652        return self.properties(properties, prefix=self.seg(self.WITH_PROPERTIES_PREFIX, sep=""))
    1653
    1654    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
    1655        properties_locs = defaultdict(list)
    1656        for p in properties.expressions:
    1657            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1658            if p_loc != exp.Properties.Location.UNSUPPORTED:
    1659                properties_locs[p_loc].append(p)
    1660            else:
    1661                self.unsupported(f"Unsupported property {p.key}")
    1662
    1663        return properties_locs
    1664
    1665    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
    1666        if isinstance(expression.this, exp.Dot):
    1667            return self.sql(expression, "this")
    1668        return f"'{expression.name}'" if string_key else expression.name
    1669
    1670    def property_sql(self, expression: exp.Property) -> str:
    1671        property_cls = expression.__class__
    1672        if property_cls == exp.Property:
    1673            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
    1674
    1675        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    1676        if not property_name:
    1677            self.unsupported(f"Unsupported property {expression.key}")
    1678
    1679        return f"{property_name}={self.sql(expression, 'this')}"
    1680
    1681    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
    1682        if self.SUPPORTS_CREATE_TABLE_LIKE:
    1683            options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
    1684            options = f" {options}" if options else ""
    1685
    1686            like = f"LIKE {self.sql(expression, 'this')}{options}"
    1687            if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema):
    1688                like = f"({like})"
    1689
    1690            return like
    1691
    1692        if expression.expressions:
    1693            self.unsupported("Transpilation of LIKE property options is unsupported")
    1694
    1695        select = exp.select("*").from_(expression.this).limit(0)
    1696        return f"AS {self.sql(select)}"
    1697
    1698    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1699        no = "NO " if expression.args.get("no") else ""
    1700        protection = " PROTECTION" if expression.args.get("protection") else ""
    1701        return f"{no}FALLBACK{protection}"
    1702
    1703    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1704        no = "NO " if expression.args.get("no") else ""
    1705        local = expression.args.get("local")
    1706        local = f"{local} " if local else ""
    1707        dual = "DUAL " if expression.args.get("dual") else ""
    1708        before = "BEFORE " if expression.args.get("before") else ""
    1709        after = "AFTER " if expression.args.get("after") else ""
    1710        return f"{no}{local}{dual}{before}{after}JOURNAL"
    1711
    1712    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1713        freespace = self.sql(expression, "this")
    1714        percent = " PERCENT" if expression.args.get("percent") else ""
    1715        return f"FREESPACE={freespace}{percent}"
    1716
    1717    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1718        if expression.args.get("default"):
    1719            property = "DEFAULT"
    1720        elif expression.args.get("on"):
    1721            property = "ON"
    1722        else:
    1723            property = "OFF"
    1724        return f"CHECKSUM={property}"
    1725
    1726    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1727        if expression.args.get("no"):
    1728            return "NO MERGEBLOCKRATIO"
    1729        if expression.args.get("default"):
    1730            return "DEFAULT MERGEBLOCKRATIO"
    1731
    1732        percent = " PERCENT" if expression.args.get("percent") else ""
    1733        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"
    1734
    1735    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1736        default = expression.args.get("default")
    1737        minimum = expression.args.get("minimum")
    1738        maximum = expression.args.get("maximum")
    1739        if default or minimum or maximum:
    1740            if default:
    1741                prop = "DEFAULT"
    1742            elif minimum:
    1743                prop = "MINIMUM"
    1744            else:
    1745                prop = "MAXIMUM"
    1746            return f"{prop} DATABLOCKSIZE"
    1747        units = expression.args.get("units")
    1748        units = f" {units}" if units else ""
    1749        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"
    1750
    1751    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1752        autotemp = expression.args.get("autotemp")
    1753        always = expression.args.get("always")
    1754        default = expression.args.get("default")
    1755        manual = expression.args.get("manual")
    1756        never = expression.args.get("never")
    1757
    1758        if autotemp is not None:
    1759            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1760        elif always:
    1761            prop = "ALWAYS"
    1762        elif default:
    1763            prop = "DEFAULT"
    1764        elif manual:
    1765            prop = "MANUAL"
    1766        elif never:
    1767            prop = "NEVER"
    1768        return f"BLOCKCOMPRESSION={prop}"
    1769
    1770    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1771        no = expression.args.get("no")
    1772        no = " NO" if no else ""
    1773        concurrent = expression.args.get("concurrent")
    1774        concurrent = " CONCURRENT" if concurrent else ""
    1775        target = self.sql(expression, "target")
    1776        target = f" {target}" if target else ""
    1777        return f"WITH{no}{concurrent} ISOLATED LOADING{target}"
    1778
    1779    def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str:
    1780        if isinstance(expression.this, list):
    1781            return f"IN ({self.expressions(expression, key='this', flat=True)})"
    1782        if expression.this:
    1783            modulus = self.sql(expression, "this")
    1784            remainder = self.sql(expression, "expression")
    1785            return f"WITH (MODULUS {modulus}, REMAINDER {remainder})"
    1786
    1787        from_expressions = self.expressions(expression, key="from_expressions", flat=True)
    1788        to_expressions = self.expressions(expression, key="to_expressions", flat=True)
    1789        return f"FROM ({from_expressions}) TO ({to_expressions})"
    1790
    1791    def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str:
    1792        this = self.sql(expression, "this")
    1793
    1794        for_values_or_default = expression.expression
    1795        if isinstance(for_values_or_default, exp.PartitionBoundSpec):
    1796            for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}"
    1797        else:
    1798            for_values_or_default = " DEFAULT"
    1799
    1800        return f"PARTITION OF {this}{for_values_or_default}"
    1801
    1802    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1803        kind = expression.args.get("kind")
    1804        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1805        for_or_in = expression.args.get("for_or_in")
    1806        for_or_in = f" {for_or_in}" if for_or_in else ""
    1807        lock_type = expression.args.get("lock_type")
    1808        override = " OVERRIDE" if expression.args.get("override") else ""
    1809        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"
    1810
    1811    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1812        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1813        statistics = expression.args.get("statistics")
    1814        statistics_sql = ""
    1815        if statistics is not None:
    1816            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1817        return f"{data_sql}{statistics_sql}"
    1818
    1819    def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str:
    1820        this = self.sql(expression, "this")
    1821        this = f"HISTORY_TABLE={this}" if this else ""
    1822        data_consistency: t.Optional[str] = self.sql(expression, "data_consistency")
    1823        data_consistency = (
    1824            f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None
    1825        )
    1826        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    1827        retention_period = (
    1828            f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None
    1829        )
    1830
    1831        if this:
    1832            on_sql = self.func("ON", this, data_consistency, retention_period)
    1833        else:
    1834            on_sql = "ON" if expression.args.get("on") else "OFF"
    1835
    1836        sql = f"SYSTEM_VERSIONING={on_sql}"
    1837
    1838        return f"WITH({sql})" if expression.args.get("with") else sql
    1839
    1840    def insert_sql(self, expression: exp.Insert) -> str:
    1841        hint = self.sql(expression, "hint")
    1842        overwrite = expression.args.get("overwrite")
    1843
    1844        if isinstance(expression.this, exp.Directory):
    1845            this = " OVERWRITE" if overwrite else " INTO"
    1846        else:
    1847            this = self.INSERT_OVERWRITE if overwrite else " INTO"
    1848
    1849        stored = self.sql(expression, "stored")
    1850        stored = f" {stored}" if stored else ""
    1851        alternative = expression.args.get("alternative")
    1852        alternative = f" OR {alternative}" if alternative else ""
    1853        ignore = " IGNORE" if expression.args.get("ignore") else ""
    1854        is_function = expression.args.get("is_function")
    1855        if is_function:
    1856            this = f"{this} FUNCTION"
    1857        this = f"{this} {self.sql(expression, 'this')}"
    1858
    1859        exists = " IF EXISTS" if expression.args.get("exists") else ""
    1860        where = self.sql(expression, "where")
    1861        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
    1862        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
    1863        on_conflict = self.sql(expression, "conflict")
    1864        on_conflict = f" {on_conflict}" if on_conflict else ""
    1865        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1866        returning = self.sql(expression, "returning")
    1867
    1868        if self.RETURNING_END:
    1869            expression_sql = f"{expression_sql}{on_conflict}{returning}"
    1870        else:
    1871            expression_sql = f"{returning}{expression_sql}{on_conflict}"
    1872
    1873        partition_by = self.sql(expression, "partition")
    1874        partition_by = f" {partition_by}" if partition_by else ""
    1875        settings = self.sql(expression, "settings")
    1876        settings = f" {settings}" if settings else ""
    1877
    1878        source = self.sql(expression, "source")
    1879        source = f"TABLE {source}" if source else ""
    1880
    1881        sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}"
    1882        return self.prepend_ctes(expression, sql)
    1883
    1884    def introducer_sql(self, expression: exp.Introducer) -> str:
    1885        return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}"
    1886
    1887    def kill_sql(self, expression: exp.Kill) -> str:
    1888        kind = self.sql(expression, "kind")
    1889        kind = f" {kind}" if kind else ""
    1890        this = self.sql(expression, "this")
    1891        this = f" {this}" if this else ""
    1892        return f"KILL{kind}{this}"
    1893
    1894    def pseudotype_sql(self, expression: exp.PseudoType) -> str:
    1895        return expression.name
    1896
    1897    def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str:
    1898        return expression.name
    1899
    1900    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1901        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1902
    1903        constraint = self.sql(expression, "constraint")
    1904        constraint = f" ON CONSTRAINT {constraint}" if constraint else ""
    1905
    1906        conflict_keys = self.expressions(expression, key="conflict_keys", flat=True)
    1907        conflict_keys = f"({conflict_keys}) " if conflict_keys else " "
    1908        action = self.sql(expression, "action")
    1909
    1910        expressions = self.expressions(expression, flat=True)
    1911        if expressions:
    1912            set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
    1913            expressions = f" {set_keyword}{expressions}"
    1914
    1915        where = self.sql(expression, "where")
    1916        return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}"
    1917
    1918    def returning_sql(self, expression: exp.Returning) -> str:
    1919        return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}"
    1920
    1921    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1922        fields = self.sql(expression, "fields")
    1923        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1924        escaped = self.sql(expression, "escaped")
    1925        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1926        items = self.sql(expression, "collection_items")
    1927        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1928        keys = self.sql(expression, "map_keys")
    1929        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1930        lines = self.sql(expression, "lines")
    1931        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1932        null = self.sql(expression, "null")
    1933        null = f" NULL DEFINED AS {null}" if null else ""
    1934        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"
    1935
    1936    def withtablehint_sql(self, expression: exp.WithTableHint) -> str:
    1937        return f"WITH ({self.expressions(expression, flat=True)})"
    1938
    1939    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1940        this = f"{self.sql(expression, 'this')} INDEX"
    1941        target = self.sql(expression, "target")
    1942        target = f" FOR {target}" if target else ""
    1943        return f"{this}{target} ({self.expressions(expression, flat=True)})"
    1944
    1945    def historicaldata_sql(self, expression: exp.HistoricalData) -> str:
    1946        this = self.sql(expression, "this")
    1947        kind = self.sql(expression, "kind")
    1948        expr = self.sql(expression, "expression")
    1949        return f"{this} ({kind} => {expr})"
    1950
    1951    def table_parts(self, expression: exp.Table) -> str:
    1952        return ".".join(
    1953            self.sql(part)
    1954            for part in (
    1955                expression.args.get("catalog"),
    1956                expression.args.get("db"),
    1957                expression.args.get("this"),
    1958            )
    1959            if part is not None
    1960        )
    1961
    1962    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1963        table = self.table_parts(expression)
    1964        only = "ONLY " if expression.args.get("only") else ""
    1965        partition = self.sql(expression, "partition")
    1966        partition = f" {partition}" if partition else ""
    1967        version = self.sql(expression, "version")
    1968        version = f" {version}" if version else ""
    1969        alias = self.sql(expression, "alias")
    1970        alias = f"{sep}{alias}" if alias else ""
    1971
    1972        sample = self.sql(expression, "sample")
    1973        if self.dialect.ALIAS_POST_TABLESAMPLE:
    1974            sample_pre_alias = sample
    1975            sample_post_alias = ""
    1976        else:
    1977            sample_pre_alias = ""
    1978            sample_post_alias = sample
    1979
    1980        hints = self.expressions(expression, key="hints", sep=" ")
    1981        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
    1982        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    1983        joins = self.indent(
    1984            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
    1985        )
    1986        laterals = self.expressions(expression, key="laterals", sep="")
    1987
    1988        file_format = self.sql(expression, "format")
    1989        if file_format:
    1990            pattern = self.sql(expression, "pattern")
    1991            pattern = f", PATTERN => {pattern}" if pattern else ""
    1992            file_format = f" (FILE_FORMAT => {file_format}{pattern})"
    1993
    1994        ordinality = expression.args.get("ordinality") or ""
    1995        if ordinality:
    1996            ordinality = f" WITH ORDINALITY{alias}"
    1997            alias = ""
    1998
    1999        when = self.sql(expression, "when")
    2000        if when:
    2001            table = f"{table} {when}"
    2002
    2003        changes = self.sql(expression, "changes")
    2004        changes = f" {changes}" if changes else ""
    2005
    2006        rows_from = self.expressions(expression, key="rows_from")
    2007        if rows_from:
    2008            table = f"ROWS FROM {self.wrap(rows_from)}"
    2009
    2010        return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}"
    2011
    2012    def tablefromrows_sql(self, expression: exp.TableFromRows) -> str:
    2013        table = self.func("TABLE", expression.this)
    2014        alias = self.sql(expression, "alias")
    2015        alias = f" AS {alias}" if alias else ""
    2016        sample = self.sql(expression, "sample")
    2017        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    2018        joins = self.indent(
    2019            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
    2020        )
    2021        return f"{table}{alias}{pivots}{sample}{joins}"
    2022
    2023    def tablesample_sql(
    2024        self,
    2025        expression: exp.TableSample,
    2026        tablesample_keyword: t.Optional[str] = None,
    2027    ) -> str:
    2028        method = self.sql(expression, "method")
    2029        method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    2030        numerator = self.sql(expression, "bucket_numerator")
    2031        denominator = self.sql(expression, "bucket_denominator")
    2032        field = self.sql(expression, "bucket_field")
    2033        field = f" ON {field}" if field else ""
    2034        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    2035        seed = self.sql(expression, "seed")
    2036        seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else ""
    2037
    2038        size = self.sql(expression, "size")
    2039        if size and self.TABLESAMPLE_SIZE_IS_ROWS:
    2040            size = f"{size} ROWS"
    2041
    2042        percent = self.sql(expression, "percent")
    2043        if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT:
    2044            percent = f"{percent} PERCENT"
    2045
    2046        expr = f"{bucket}{percent}{size}"
    2047        if self.TABLESAMPLE_REQUIRES_PARENS:
    2048            expr = f"({expr})"
    2049
    2050        return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}"
    2051
    2052    def pivot_sql(self, expression: exp.Pivot) -> str:
    2053        expressions = self.expressions(expression, flat=True)
    2054        direction = "UNPIVOT" if expression.unpivot else "PIVOT"
    2055
    2056        group = self.sql(expression, "group")
    2057
    2058        if expression.this:
    2059            this = self.sql(expression, "this")
    2060            if not expressions:
    2061                return f"UNPIVOT {this}"
    2062
    2063            on = f"{self.seg('ON')} {expressions}"
    2064            into = self.sql(expression, "into")
    2065            into = f"{self.seg('INTO')} {into}" if into else ""
    2066            using = self.expressions(expression, key="using", flat=True)
    2067            using = f"{self.seg('USING')} {using}" if using else ""
    2068            return f"{direction} {this}{on}{into}{using}{group}"
    2069
    2070        alias = self.sql(expression, "alias")
    2071        alias = f" AS {alias}" if alias else ""
    2072
    2073        fields = self.expressions(
    2074            expression,
    2075            "fields",
    2076            sep=" ",
    2077            dynamic=True,
    2078            new_line=True,
    2079            skip_first=True,
    2080            skip_last=True,
    2081        )
    2082
    2083        include_nulls = expression.args.get("include_nulls")
    2084        if include_nulls is not None:
    2085            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
    2086        else:
    2087            nulls = ""
    2088
    2089        default_on_null = self.sql(expression, "default_on_null")
    2090        default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else ""
    2091        return f"{self.seg(direction)}{nulls}({expressions} FOR {fields}{default_on_null}{group}){alias}"
    2092
    2093    def version_sql(self, expression: exp.Version) -> str:
    2094        this = f"FOR {expression.name}"
    2095        kind = expression.text("kind")
    2096        expr = self.sql(expression, "expression")
    2097        return f"{this} {kind} {expr}"
    2098
    2099    def tuple_sql(self, expression: exp.Tuple) -> str:
    2100        return f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})"
    2101
    2102    def update_sql(self, expression: exp.Update) -> str:
    2103        this = self.sql(expression, "this")
    2104        set_sql = self.expressions(expression, flat=True)
    2105        from_sql = self.sql(expression, "from")
    2106        where_sql = self.sql(expression, "where")
    2107        returning = self.sql(expression, "returning")
    2108        order = self.sql(expression, "order")
    2109        limit = self.sql(expression, "limit")
    2110        if self.RETURNING_END:
    2111            expression_sql = f"{from_sql}{where_sql}{returning}"
    2112        else:
    2113            expression_sql = f"{returning}{from_sql}{where_sql}"
    2114        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
    2115        return self.prepend_ctes(expression, sql)
    2116
    2117    def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str:
    2118        values_as_table = values_as_table and self.VALUES_AS_TABLE
    2119
    2120        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
    2121        if values_as_table or not expression.find_ancestor(exp.From, exp.Join):
    2122            args = self.expressions(expression)
    2123            alias = self.sql(expression, "alias")
    2124            values = f"VALUES{self.seg('')}{args}"
    2125            values = (
    2126                f"({values})"
    2127                if self.WRAP_DERIVED_VALUES
    2128                and (alias or isinstance(expression.parent, (exp.From, exp.Table)))
    2129                else values
    2130            )
    2131            return f"{values} AS {alias}" if alias else values
    2132
    2133        # Converts `VALUES...` expression into a series of select unions.
    2134        alias_node = expression.args.get("alias")
    2135        column_names = alias_node and alias_node.columns
    2136
    2137        selects: t.List[exp.Query] = []
    2138
    2139        for i, tup in enumerate(expression.expressions):
    2140            row = tup.expressions
    2141
    2142            if i == 0 and column_names:
    2143                row = [
    2144                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
    2145                ]
    2146
    2147            selects.append(exp.Select(expressions=row))
    2148
    2149        if self.pretty:
    2150            # This may result in poor performance for large-cardinality `VALUES` tables, due to
    2151            # the deep nesting of the resulting exp.Unions. If this is a problem, either increase
    2152            # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`.
    2153            query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects)
    2154            return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False))
    2155
    2156        alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else ""
    2157        unions = " UNION ALL ".join(self.sql(select) for select in selects)
    2158        return f"({unions}){alias}"
    2159
    2160    def var_sql(self, expression: exp.Var) -> str:
    2161        return self.sql(expression, "this")
    2162
    2163    @unsupported_args("expressions")
    2164    def into_sql(self, expression: exp.Into) -> str:
    2165        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    2166        unlogged = " UNLOGGED" if expression.args.get("unlogged") else ""
    2167        return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"
    2168
    2169    def from_sql(self, expression: exp.From) -> str:
    2170        return f"{self.seg('FROM')} {self.sql(expression, 'this')}"
    2171
    2172    def groupingsets_sql(self, expression: exp.GroupingSets) -> str:
    2173        grouping_sets = self.expressions(expression, indent=False)
    2174        return f"GROUPING SETS {self.wrap(grouping_sets)}"
    2175
    2176    def rollup_sql(self, expression: exp.Rollup) -> str:
    2177        expressions = self.expressions(expression, indent=False)
    2178        return f"ROLLUP {self.wrap(expressions)}" if expressions else "WITH ROLLUP"
    2179
    2180    def cube_sql(self, expression: exp.Cube) -> str:
    2181        expressions = self.expressions(expression, indent=False)
    2182        return f"CUBE {self.wrap(expressions)}" if expressions else "WITH CUBE"
    2183
    2184    def group_sql(self, expression: exp.Group) -> str:
    2185        group_by_all = expression.args.get("all")
    2186        if group_by_all is True:
    2187            modifier = " ALL"
    2188        elif group_by_all is False:
    2189            modifier = " DISTINCT"
    2190        else:
    2191            modifier = ""
    2192
    2193        group_by = self.op_expressions(f"GROUP BY{modifier}", expression)
    2194
    2195        grouping_sets = self.expressions(expression, key="grouping_sets")
    2196        cube = self.expressions(expression, key="cube")
    2197        rollup = self.expressions(expression, key="rollup")
    2198
    2199        groupings = csv(
    2200            self.seg(grouping_sets) if grouping_sets else "",
    2201            self.seg(cube) if cube else "",
    2202            self.seg(rollup) if rollup else "",
    2203            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    2204            sep=self.GROUPINGS_SEP,
    2205        )
    2206
    2207        if (
    2208            expression.expressions
    2209            and groupings
    2210            and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP")
    2211        ):
    2212            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    2213
    2214        return f"{group_by}{groupings}"
    2215
    2216    def having_sql(self, expression: exp.Having) -> str:
    2217        this = self.indent(self.sql(expression, "this"))
    2218        return f"{self.seg('HAVING')}{self.sep()}{this}"
    2219
    2220    def connect_sql(self, expression: exp.Connect) -> str:
    2221        start = self.sql(expression, "start")
    2222        start = self.seg(f"START WITH {start}") if start else ""
    2223        nocycle = " NOCYCLE" if expression.args.get("nocycle") else ""
    2224        connect = self.sql(expression, "connect")
    2225        connect = self.seg(f"CONNECT BY{nocycle} {connect}")
    2226        return start + connect
    2227
    2228    def prior_sql(self, expression: exp.Prior) -> str:
    2229        return f"PRIOR {self.sql(expression, 'this')}"
    2230
    2231    def join_sql(self, expression: exp.Join) -> str:
    2232        if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"):
    2233            side = None
    2234        else:
    2235            side = expression.side
    2236
    2237        op_sql = " ".join(
    2238            op
    2239            for op in (
    2240                expression.method,
    2241                "GLOBAL" if expression.args.get("global") else None,
    2242                side,
    2243                expression.kind,
    2244                expression.hint if self.JOIN_HINTS else None,
    2245            )
    2246            if op
    2247        )
    2248        match_cond = self.sql(expression, "match_condition")
    2249        match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else ""
    2250        on_sql = self.sql(expression, "on")
    2251        using = expression.args.get("using")
    2252
    2253        if not on_sql and using:
    2254            on_sql = csv(*(self.sql(column) for column in using))
    2255
    2256        this = expression.this
    2257        this_sql = self.sql(this)
    2258
    2259        exprs = self.expressions(expression)
    2260        if exprs:
    2261            this_sql = f"{this_sql},{self.seg(exprs)}"
    2262
    2263        if on_sql:
    2264            on_sql = self.indent(on_sql, skip_first=True)
    2265            space = self.seg(" " * self.pad) if self.pretty else " "
    2266            if using:
    2267                on_sql = f"{space}USING ({on_sql})"
    2268            else:
    2269                on_sql = f"{space}ON {on_sql}"
    2270        elif not op_sql:
    2271            if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None:
    2272                return f" {this_sql}"
    2273
    2274            return f", {this_sql}"
    2275
    2276        if op_sql != "STRAIGHT_JOIN":
    2277            op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    2278
    2279        return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}"
    2280
    2281    def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->") -> str:
    2282        args = self.expressions(expression, flat=True)
    2283        args = f"({args})" if len(args.split(",")) > 1 else args
    2284        return f"{args} {arrow_sep} {self.sql(expression, 'this')}"
    2285
    2286    def lateral_op(self, expression: exp.Lateral) -> str:
    2287        cross_apply = expression.args.get("cross_apply")
    2288
    2289        # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/
    2290        if cross_apply is True:
    2291            op = "INNER JOIN "
    2292        elif cross_apply is False:
    2293            op = "LEFT JOIN "
    2294        else:
    2295            op = ""
    2296
    2297        return f"{op}LATERAL"
    2298
    2299    def lateral_sql(self, expression: exp.Lateral) -> str:
    2300        this = self.sql(expression, "this")
    2301
    2302        if expression.args.get("view"):
    2303            alias = expression.args["alias"]
    2304            columns = self.expressions(alias, key="columns", flat=True)
    2305            table = f" {alias.name}" if alias.name else ""
    2306            columns = f" AS {columns}" if columns else ""
    2307            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    2308            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    2309
    2310        alias = self.sql(expression, "alias")
    2311        alias = f" AS {alias}" if alias else ""
    2312
    2313        ordinality = expression.args.get("ordinality") or ""
    2314        if ordinality:
    2315            ordinality = f" WITH ORDINALITY{alias}"
    2316            alias = ""
    2317
    2318        return f"{self.lateral_op(expression)} {this}{alias}{ordinality}"
    2319
    2320    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    2321        this = self.sql(expression, "this")
    2322
    2323        args = [
    2324            self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e
    2325            for e in (expression.args.get(k) for k in ("offset", "expression"))
    2326            if e
    2327        ]
    2328
    2329        args_sql = ", ".join(self.sql(e) for e in args)
    2330        args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql
    2331        expressions = self.expressions(expression, flat=True)
    2332        limit_options = self.sql(expression, "limit_options")
    2333        expressions = f" BY {expressions}" if expressions else ""
    2334
    2335        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{limit_options}{expressions}"
    2336
    2337    def offset_sql(self, expression: exp.Offset) -> str:
    2338        this = self.sql(expression, "this")
    2339        value = expression.expression
    2340        value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value
    2341        expressions = self.expressions(expression, flat=True)
    2342        expressions = f" BY {expressions}" if expressions else ""
    2343        return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"
    2344
    2345    def setitem_sql(self, expression: exp.SetItem) -> str:
    2346        kind = self.sql(expression, "kind")
    2347        kind = f"{kind} " if kind else ""
    2348        this = self.sql(expression, "this")
    2349        expressions = self.expressions(expression)
    2350        collate = self.sql(expression, "collate")
    2351        collate = f" COLLATE {collate}" if collate else ""
    2352        global_ = "GLOBAL " if expression.args.get("global") else ""
    2353        return f"{global_}{kind}{this}{expressions}{collate}"
    2354
    2355    def set_sql(self, expression: exp.Set) -> str:
    2356        expressions = f" {self.expressions(expression, flat=True)}"
    2357        tag = " TAG" if expression.args.get("tag") else ""
    2358        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"
    2359
    2360    def pragma_sql(self, expression: exp.Pragma) -> str:
    2361        return f"PRAGMA {self.sql(expression, 'this')}"
    2362
    2363    def lock_sql(self, expression: exp.Lock) -> str:
    2364        if not self.LOCKING_READS_SUPPORTED:
    2365            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    2366            return ""
    2367
    2368        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    2369        expressions = self.expressions(expression, flat=True)
    2370        expressions = f" OF {expressions}" if expressions else ""
    2371        wait = expression.args.get("wait")
    2372
    2373        if wait is not None:
    2374            if isinstance(wait, exp.Literal):
    2375                wait = f" WAIT {self.sql(wait)}"
    2376            else:
    2377                wait = " NOWAIT" if wait else " SKIP LOCKED"
    2378
    2379        return f"{lock_type}{expressions}{wait or ''}"
    2380
    2381    def literal_sql(self, expression: exp.Literal) -> str:
    2382        text = expression.this or ""
    2383        if expression.is_string:
    2384            text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}"
    2385        return text
    2386
    2387    def escape_str(self, text: str, escape_backslash: bool = True) -> str:
    2388        if self.dialect.ESCAPED_SEQUENCES:
    2389            to_escaped = self.dialect.ESCAPED_SEQUENCES
    2390            text = "".join(
    2391                to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text
    2392            )
    2393
    2394        return self._replace_line_breaks(text).replace(
    2395            self.dialect.QUOTE_END, self._escaped_quote_end
    2396        )
    2397
    2398    def loaddata_sql(self, expression: exp.LoadData) -> str:
    2399        local = " LOCAL" if expression.args.get("local") else ""
    2400        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    2401        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    2402        this = f" INTO TABLE {self.sql(expression, 'this')}"
    2403        partition = self.sql(expression, "partition")
    2404        partition = f" {partition}" if partition else ""
    2405        input_format = self.sql(expression, "input_format")
    2406        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    2407        serde = self.sql(expression, "serde")
    2408        serde = f" SERDE {serde}" if serde else ""
    2409        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"
    2410
    2411    def null_sql(self, *_) -> str:
    2412        return "NULL"
    2413
    2414    def boolean_sql(self, expression: exp.Boolean) -> str:
    2415        return "TRUE" if expression.this else "FALSE"
    2416
    2417    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    2418        this = self.sql(expression, "this")
    2419        this = f"{this} " if this else this
    2420        siblings = "SIBLINGS " if expression.args.get("siblings") else ""
    2421        return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat)  # type: ignore
    2422
    2423    def withfill_sql(self, expression: exp.WithFill) -> str:
    2424        from_sql = self.sql(expression, "from")
    2425        from_sql = f" FROM {from_sql}" if from_sql else ""
    2426        to_sql = self.sql(expression, "to")
    2427        to_sql = f" TO {to_sql}" if to_sql else ""
    2428        step_sql = self.sql(expression, "step")
    2429        step_sql = f" STEP {step_sql}" if step_sql else ""
    2430        interpolated_values = [
    2431            f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}"
    2432            if isinstance(e, exp.Alias)
    2433            else self.sql(e, "this")
    2434            for e in expression.args.get("interpolate") or []
    2435        ]
    2436        interpolate = (
    2437            f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else ""
    2438        )
    2439        return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}"
    2440
    2441    def cluster_sql(self, expression: exp.Cluster) -> str:
    2442        return self.op_expressions("CLUSTER BY", expression)
    2443
    2444    def distribute_sql(self, expression: exp.Distribute) -> str:
    2445        return self.op_expressions("DISTRIBUTE BY", expression)
    2446
    2447    def sort_sql(self, expression: exp.Sort) -> str:
    2448        return self.op_expressions("SORT BY", expression)
    2449
    2450    def ordered_sql(self, expression: exp.Ordered) -> str:
    2451        desc = expression.args.get("desc")
    2452        asc = not desc
    2453
    2454        nulls_first = expression.args.get("nulls_first")
    2455        nulls_last = not nulls_first
    2456        nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large"
    2457        nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small"
    2458        nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last"
    2459
    2460        this = self.sql(expression, "this")
    2461
    2462        sort_order = " DESC" if desc else (" ASC" if desc is False else "")
    2463        nulls_sort_change = ""
    2464        if nulls_first and (
    2465            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
    2466        ):
    2467            nulls_sort_change = " NULLS FIRST"
    2468        elif (
    2469            nulls_last
    2470            and ((asc and nulls_are_small) or (desc and nulls_are_large))
    2471            and not nulls_are_last
    2472        ):
    2473            nulls_sort_change = " NULLS LAST"
    2474
    2475        # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it
    2476        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
    2477            window = expression.find_ancestor(exp.Window, exp.Select)
    2478            if isinstance(window, exp.Window) and window.args.get("spec"):
    2479                self.unsupported(
    2480                    f"'{nulls_sort_change.strip()}' translation not supported in window functions"
    2481                )
    2482                nulls_sort_change = ""
    2483            elif self.NULL_ORDERING_SUPPORTED is False and (
    2484                (asc and nulls_sort_change == " NULLS LAST")
    2485                or (desc and nulls_sort_change == " NULLS FIRST")
    2486            ):
    2487                # BigQuery does not allow these ordering/nulls combinations when used under
    2488                # an aggregation func or under a window containing one
    2489                ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select)
    2490
    2491                if isinstance(ancestor, exp.Window):
    2492                    ancestor = ancestor.this
    2493                if isinstance(ancestor, exp.AggFunc):
    2494                    self.unsupported(
    2495                        f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order"
    2496                    )
    2497                    nulls_sort_change = ""
    2498            elif self.NULL_ORDERING_SUPPORTED is None:
    2499                if expression.this.is_int:
    2500                    self.unsupported(
    2501                        f"'{nulls_sort_change.strip()}' translation not supported with positional ordering"
    2502                    )
    2503                elif not isinstance(expression.this, exp.Rand):
    2504                    null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else ""
    2505                    this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}"
    2506                nulls_sort_change = ""
    2507
    2508        with_fill = self.sql(expression, "with_fill")
    2509        with_fill = f" {with_fill}" if with_fill else ""
    2510
    2511        return f"{this}{sort_order}{nulls_sort_change}{with_fill}"
    2512
    2513    def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str:
    2514        window_frame = self.sql(expression, "window_frame")
    2515        window_frame = f"{window_frame} " if window_frame else ""
    2516
    2517        this = self.sql(expression, "this")
    2518
    2519        return f"{window_frame}{this}"
    2520
    2521    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    2522        partition = self.partition_by_sql(expression)
    2523        order = self.sql(expression, "order")
    2524        measures = self.expressions(expression, key="measures")
    2525        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    2526        rows = self.sql(expression, "rows")
    2527        rows = self.seg(rows) if rows else ""
    2528        after = self.sql(expression, "after")
    2529        after = self.seg(after) if after else ""
    2530        pattern = self.sql(expression, "pattern")
    2531        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    2532        definition_sqls = [
    2533            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    2534            for definition in expression.args.get("define", [])
    2535        ]
    2536        definitions = self.expressions(sqls=definition_sqls)
    2537        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    2538        body = "".join(
    2539            (
    2540                partition,
    2541                order,
    2542                measures,
    2543                rows,
    2544                after,
    2545                pattern,
    2546                define,
    2547            )
    2548        )
    2549        alias = self.sql(expression, "alias")
    2550        alias = f" {alias}" if alias else ""
    2551        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"
    2552
    2553    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    2554        limit = expression.args.get("limit")
    2555
    2556        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    2557            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
    2558        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    2559            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
    2560
    2561        return csv(
    2562            *sqls,
    2563            *[self.sql(join) for join in expression.args.get("joins") or []],
    2564            self.sql(expression, "match"),
    2565            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    2566            self.sql(expression, "prewhere"),
    2567            self.sql(expression, "where"),
    2568            self.sql(expression, "connect"),
    2569            self.sql(expression, "group"),
    2570            self.sql(expression, "having"),
    2571            *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()],
    2572            self.sql(expression, "order"),
    2573            *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit),
    2574            *self.after_limit_modifiers(expression),
    2575            self.options_modifier(expression),
    2576            sep="",
    2577        )
    2578
    2579    def options_modifier(self, expression: exp.Expression) -> str:
    2580        options = self.expressions(expression, key="options")
    2581        return f" {options}" if options else ""
    2582
    2583    def queryoption_sql(self, expression: exp.QueryOption) -> str:
    2584        self.unsupported("Unsupported query option.")
    2585        return ""
    2586
    2587    def offset_limit_modifiers(
    2588        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    2589    ) -> t.List[str]:
    2590        return [
    2591            self.sql(expression, "offset") if fetch else self.sql(limit),
    2592            self.sql(limit) if fetch else self.sql(expression, "offset"),
    2593        ]
    2594
    2595    def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]:
    2596        locks = self.expressions(expression, key="locks", sep=" ")
    2597        locks = f" {locks}" if locks else ""
    2598        return [locks, self.sql(expression, "sample")]
    2599
    2600    def select_sql(self, expression: exp.Select) -> str:
    2601        into = expression.args.get("into")
    2602        if not self.SUPPORTS_SELECT_INTO and into:
    2603            into.pop()
    2604
    2605        hint = self.sql(expression, "hint")
    2606        distinct = self.sql(expression, "distinct")
    2607        distinct = f" {distinct}" if distinct else ""
    2608        kind = self.sql(expression, "kind")
    2609
    2610        limit = expression.args.get("limit")
    2611        if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP:
    2612            top = self.limit_sql(limit, top=True)
    2613            limit.pop()
    2614        else:
    2615            top = ""
    2616
    2617        expressions = self.expressions(expression)
    2618
    2619        if kind:
    2620            if kind in self.SELECT_KINDS:
    2621                kind = f" AS {kind}"
    2622            else:
    2623                if kind == "STRUCT":
    2624                    expressions = self.expressions(
    2625                        sqls=[
    2626                            self.sql(
    2627                                exp.Struct(
    2628                                    expressions=[
    2629                                        exp.PropertyEQ(this=e.args.get("alias"), expression=e.this)
    2630                                        if isinstance(e, exp.Alias)
    2631                                        else e
    2632                                        for e in expression.expressions
    2633                                    ]
    2634                                )
    2635                            )
    2636                        ]
    2637                    )
    2638                kind = ""
    2639
    2640        operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ")
    2641        operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else ""
    2642
    2643        # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata
    2644        # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first.
    2645        top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}"
    2646        expressions = f"{self.sep()}{expressions}" if expressions else expressions
    2647        sql = self.query_modifiers(
    2648            expression,
    2649            f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}",
    2650            self.sql(expression, "into", comment=False),
    2651            self.sql(expression, "from", comment=False),
    2652        )
    2653
    2654        # If both the CTE and SELECT clauses have comments, generate the latter earlier
    2655        if expression.args.get("with"):
    2656            sql = self.maybe_comment(sql, expression)
    2657            expression.pop_comments()
    2658
    2659        sql = self.prepend_ctes(expression, sql)
    2660
    2661        if not self.SUPPORTS_SELECT_INTO and into:
    2662            if into.args.get("temporary"):
    2663                table_kind = " TEMPORARY"
    2664            elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"):
    2665                table_kind = " UNLOGGED"
    2666            else:
    2667                table_kind = ""
    2668            sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}"
    2669
    2670        return sql
    2671
    2672    def schema_sql(self, expression: exp.Schema) -> str:
    2673        this = self.sql(expression, "this")
    2674        sql = self.schema_columns_sql(expression)
    2675        return f"{this} {sql}" if this and sql else this or sql
    2676
    2677    def schema_columns_sql(self, expression: exp.Schema) -> str:
    2678        if expression.expressions:
    2679            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
    2680        return ""
    2681
    2682    def star_sql(self, expression: exp.Star) -> str:
    2683        except_ = self.expressions(expression, key="except", flat=True)
    2684        except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else ""
    2685        replace = self.expressions(expression, key="replace", flat=True)
    2686        replace = f"{self.seg('REPLACE')} ({replace})" if replace else ""
    2687        rename = self.expressions(expression, key="rename", flat=True)
    2688        rename = f"{self.seg('RENAME')} ({rename})" if rename else ""
    2689        return f"*{except_}{replace}{rename}"
    2690
    2691    def parameter_sql(self, expression: exp.Parameter) -> str:
    2692        this = self.sql(expression, "this")
    2693        return f"{self.PARAMETER_TOKEN}{this}"
    2694
    2695    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    2696        this = self.sql(expression, "this")
    2697        kind = expression.text("kind")
    2698        if kind:
    2699            kind = f"{kind}."
    2700        return f"@@{kind}{this}"
    2701
    2702    def placeholder_sql(self, expression: exp.Placeholder) -> str:
    2703        return f"{self.NAMED_PLACEHOLDER_TOKEN}{expression.name}" if expression.this else "?"
    2704
    2705    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    2706        alias = self.sql(expression, "alias")
    2707        alias = f"{sep}{alias}" if alias else ""
    2708        sample = self.sql(expression, "sample")
    2709        if self.dialect.ALIAS_POST_TABLESAMPLE and sample:
    2710            alias = f"{sample}{alias}"
    2711
    2712            # Set to None so it's not generated again by self.query_modifiers()
    2713            expression.set("sample", None)
    2714
    2715        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    2716        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    2717        return self.prepend_ctes(expression, sql)
    2718
    2719    def qualify_sql(self, expression: exp.Qualify) -> str:
    2720        this = self.indent(self.sql(expression, "this"))
    2721        return f"{self.seg('QUALIFY')}{self.sep()}{this}"
    2722
    2723    def unnest_sql(self, expression: exp.Unnest) -> str:
    2724        args = self.expressions(expression, flat=True)
    2725
    2726        alias = expression.args.get("alias")
    2727        offset = expression.args.get("offset")
    2728
    2729        if self.UNNEST_WITH_ORDINALITY:
    2730            if alias and isinstance(offset, exp.Expression):
    2731                alias.append("columns", offset)
    2732
    2733        if alias and self.dialect.UNNEST_COLUMN_ONLY:
    2734            columns = alias.columns
    2735            alias = self.sql(columns[0]) if columns else ""
    2736        else:
    2737            alias = self.sql(alias)
    2738
    2739        alias = f" AS {alias}" if alias else alias
    2740        if self.UNNEST_WITH_ORDINALITY:
    2741            suffix = f" WITH ORDINALITY{alias}" if offset else alias
    2742        else:
    2743            if isinstance(offset, exp.Expression):
    2744                suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}"
    2745            elif offset:
    2746                suffix = f"{alias} WITH OFFSET"
    2747            else:
    2748                suffix = alias
    2749
    2750        return f"UNNEST({args}){suffix}"
    2751
    2752    def prewhere_sql(self, expression: exp.PreWhere) -> str:
    2753        return ""
    2754
    2755    def where_sql(self, expression: exp.Where) -> str:
    2756        this = self.indent(self.sql(expression, "this"))
    2757        return f"{self.seg('WHERE')}{self.sep()}{this}"
    2758
    2759    def window_sql(self, expression: exp.Window) -> str:
    2760        this = self.sql(expression, "this")
    2761        partition = self.partition_by_sql(expression)
    2762        order = expression.args.get("order")
    2763        order = self.order_sql(order, flat=True) if order else ""
    2764        spec = self.sql(expression, "spec")
    2765        alias = self.sql(expression, "alias")
    2766        over = self.sql(expression, "over") or "OVER"
    2767
    2768        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    2769
    2770        first = expression.args.get("first")
    2771        if first is None:
    2772            first = ""
    2773        else:
    2774            first = "FIRST" if first else "LAST"
    2775
    2776        if not partition and not order and not spec and alias:
    2777            return f"{this} {alias}"
    2778
    2779        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
    2780        return f"{this} ({args})"
    2781
    2782    def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str:
    2783        partition = self.expressions(expression, key="partition_by", flat=True)
    2784        return f"PARTITION BY {partition}" if partition else ""
    2785
    2786    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    2787        kind = self.sql(expression, "kind")
    2788        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    2789        end = (
    2790            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    2791            or "CURRENT ROW"
    2792        )
    2793        return f"{kind} BETWEEN {start} AND {end}"
    2794
    2795    def withingroup_sql(self, expression: exp.WithinGroup) -> str:
    2796        this = self.sql(expression, "this")
    2797        expression_sql = self.sql(expression, "expression")[1:]  # order has a leading space
    2798        return f"{this} WITHIN GROUP ({expression_sql})"
    2799
    2800    def between_sql(self, expression: exp.Between) -> str:
    2801        this = self.sql(expression, "this")
    2802        low = self.sql(expression, "low")
    2803        high = self.sql(expression, "high")
    2804        return f"{this} BETWEEN {low} AND {high}"
    2805
    2806    def bracket_offset_expressions(
    2807        self, expression: exp.Bracket, index_offset: t.Optional[int] = None
    2808    ) -> t.List[exp.Expression]:
    2809        return apply_index_offset(
    2810            expression.this,
    2811            expression.expressions,
    2812            (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0),
    2813            dialect=self.dialect,
    2814        )
    2815
    2816    def bracket_sql(self, expression: exp.Bracket) -> str:
    2817        expressions = self.bracket_offset_expressions(expression)
    2818        expressions_sql = ", ".join(self.sql(e) for e in expressions)
    2819        return f"{self.sql(expression, 'this')}[{expressions_sql}]"
    2820
    2821    def all_sql(self, expression: exp.All) -> str:
    2822        return f"ALL {self.wrap(expression)}"
    2823
    2824    def any_sql(self, expression: exp.Any) -> str:
    2825        this = self.sql(expression, "this")
    2826        if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)):
    2827            if isinstance(expression.this, exp.UNWRAPPED_QUERIES):
    2828                this = self.wrap(this)
    2829            return f"ANY{this}"
    2830        return f"ANY {this}"
    2831
    2832    def exists_sql(self, expression: exp.Exists) -> str:
    2833        return f"EXISTS{self.wrap(expression)}"
    2834
    2835    def case_sql(self, expression: exp.Case) -> str:
    2836        this = self.sql(expression, "this")
    2837        statements = [f"CASE {this}" if this else "CASE"]
    2838
    2839        for e in expression.args["ifs"]:
    2840            statements.append(f"WHEN {self.sql(e, 'this')}")
    2841            statements.append(f"THEN {self.sql(e, 'true')}")
    2842
    2843        default = self.sql(expression, "default")
    2844
    2845        if default:
    2846            statements.append(f"ELSE {default}")
    2847
    2848        statements.append("END")
    2849
    2850        if self.pretty and self.too_wide(statements):
    2851            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    2852
    2853        return " ".join(statements)
    2854
    2855    def constraint_sql(self, expression: exp.Constraint) -> str:
    2856        this = self.sql(expression, "this")
    2857        expressions = self.expressions(expression, flat=True)
    2858        return f"CONSTRAINT {this} {expressions}"
    2859
    2860    def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str:
    2861        order = expression.args.get("order")
    2862        order = f" OVER ({self.order_sql(order, flat=True)})" if order else ""
    2863        return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}"
    2864
    2865    def extract_sql(self, expression: exp.Extract) -> str:
    2866        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
    2867        expression_sql = self.sql(expression, "expression")
    2868        return f"EXTRACT({this} FROM {expression_sql})"
    2869
    2870    def trim_sql(self, expression: exp.Trim) -> str:
    2871        trim_type = self.sql(expression, "position")
    2872
    2873        if trim_type == "LEADING":
    2874            func_name = "LTRIM"
    2875        elif trim_type == "TRAILING":
    2876            func_name = "RTRIM"
    2877        else:
    2878            func_name = "TRIM"
    2879
    2880        return self.func(func_name, expression.this, expression.expression)
    2881
    2882    def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]:
    2883        args = expression.expressions
    2884        if isinstance(expression, exp.ConcatWs):
    2885            args = args[1:]  # Skip the delimiter
    2886
    2887        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    2888            args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args]
    2889
    2890        if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"):
    2891            args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args]
    2892
    2893        return args
    2894
    2895    def concat_sql(self, expression: exp.Concat) -> str:
    2896        expressions = self.convert_concat_args(expression)
    2897
    2898        # Some dialects don't allow a single-argument CONCAT call
    2899        if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1:
    2900            return self.sql(expressions[0])
    2901
    2902        return self.func("CONCAT", *expressions)
    2903
    2904    def concatws_sql(self, expression: exp.ConcatWs) -> str:
    2905        return self.func(
    2906            "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression)
    2907        )
    2908
    2909    def check_sql(self, expression: exp.Check) -> str:
    2910        this = self.sql(expression, key="this")
    2911        return f"CHECK ({this})"
    2912
    2913    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    2914        expressions = self.expressions(expression, flat=True)
    2915        expressions = f" ({expressions})" if expressions else ""
    2916        reference = self.sql(expression, "reference")
    2917        reference = f" {reference}" if reference else ""
    2918        delete = self.sql(expression, "delete")
    2919        delete = f" ON DELETE {delete}" if delete else ""
    2920        update = self.sql(expression, "update")
    2921        update = f" ON UPDATE {update}" if update else ""
    2922        return f"FOREIGN KEY{expressions}{reference}{delete}{update}"
    2923
    2924    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    2925        expressions = self.expressions(expression, flat=True)
    2926        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2927        options = f" {options}" if options else ""
    2928        return f"PRIMARY KEY ({expressions}){options}"
    2929
    2930    def if_sql(self, expression: exp.If) -> str:
    2931        return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false")))
    2932
    2933    def matchagainst_sql(self, expression: exp.MatchAgainst) -> str:
    2934        modifier = expression.args.get("modifier")
    2935        modifier = f" {modifier}" if modifier else ""
    2936        return f"{self.func('MATCH', *expression.expressions)} AGAINST({self.sql(expression, 'this')}{modifier})"
    2937
    2938    def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str:
    2939        return f"{self.sql(expression, 'this')}{self.JSON_KEY_VALUE_PAIR_SEP} {self.sql(expression, 'expression')}"
    2940
    2941    def jsonpath_sql(self, expression: exp.JSONPath) -> str:
    2942        path = self.expressions(expression, sep="", flat=True).lstrip(".")
    2943
    2944        if expression.args.get("escape"):
    2945            path = self.escape_str(path)
    2946
    2947        if self.QUOTE_JSON_PATH:
    2948            path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"
    2949
    2950        return path
    2951
    2952    def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str:
    2953        if isinstance(expression, exp.JSONPathPart):
    2954            transform = self.TRANSFORMS.get(expression.__class__)
    2955            if not callable(transform):
    2956                self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}")
    2957                return ""
    2958
    2959            return transform(self, expression)
    2960
    2961        if isinstance(expression, int):
    2962            return str(expression)
    2963
    2964        if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE:
    2965            escaped = expression.replace("'", "\\'")
    2966            escaped = f"\\'{expression}\\'"
    2967        else:
    2968            escaped = expression.replace('"', '\\"')
    2969            escaped = f'"{escaped}"'
    2970
    2971        return escaped
    2972
    2973    def formatjson_sql(self, expression: exp.FormatJson) -> str:
    2974        return f"{self.sql(expression, 'this')} FORMAT JSON"
    2975
    2976    def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str:
    2977        null_handling = expression.args.get("null_handling")
    2978        null_handling = f" {null_handling}" if null_handling else ""
    2979
    2980        unique_keys = expression.args.get("unique_keys")
    2981        if unique_keys is not None:
    2982            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    2983        else:
    2984            unique_keys = ""
    2985
    2986        return_type = self.sql(expression, "return_type")
    2987        return_type = f" RETURNING {return_type}" if return_type else ""
    2988        encoding = self.sql(expression, "encoding")
    2989        encoding = f" ENCODING {encoding}" if encoding else ""
    2990
    2991        return self.func(
    2992            "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG",
    2993            *expression.expressions,
    2994            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
    2995        )
    2996
    2997    def jsonobjectagg_sql(self, expression: exp.JSONObjectAgg) -> str:
    2998        return self.jsonobject_sql(expression)
    2999
    3000    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
    3001        null_handling = expression.args.get("null_handling")
    3002        null_handling = f" {null_handling}" if null_handling else ""
    3003        return_type = self.sql(expression, "return_type")
    3004        return_type = f" RETURNING {return_type}" if return_type else ""
    3005        strict = " STRICT" if expression.args.get("strict") else ""
    3006        return self.func(
    3007            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
    3008        )
    3009
    3010    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
    3011        this = self.sql(expression, "this")
    3012        order = self.sql(expression, "order")
    3013        null_handling = expression.args.get("null_handling")
    3014        null_handling = f" {null_handling}" if null_handling else ""
    3015        return_type = self.sql(expression, "return_type")
    3016        return_type = f" RETURNING {return_type}" if return_type else ""
    3017        strict = " STRICT" if expression.args.get("strict") else ""
    3018        return self.func(
    3019            "JSON_ARRAYAGG",
    3020            this,
    3021            suffix=f"{order}{null_handling}{return_type}{strict})",
    3022        )
    3023
    3024    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
    3025        path = self.sql(expression, "path")
    3026        path = f" PATH {path}" if path else ""
    3027        nested_schema = self.sql(expression, "nested_schema")
    3028
    3029        if nested_schema:
    3030            return f"NESTED{path} {nested_schema}"
    3031
    3032        this = self.sql(expression, "this")
    3033        kind = self.sql(expression, "kind")
    3034        kind = f" {kind}" if kind else ""
    3035        return f"{this}{kind}{path}"
    3036
    3037    def jsonschema_sql(self, expression: exp.JSONSchema) -> str:
    3038        return self.func("COLUMNS", *expression.expressions)
    3039
    3040    def jsontable_sql(self, expression: exp.JSONTable) -> str:
    3041        this = self.sql(expression, "this")
    3042        path = self.sql(expression, "path")
    3043        path = f", {path}" if path else ""
    3044        error_handling = expression.args.get("error_handling")
    3045        error_handling = f" {error_handling}" if error_handling else ""
    3046        empty_handling = expression.args.get("empty_handling")
    3047        empty_handling = f" {empty_handling}" if empty_handling else ""
    3048        schema = self.sql(expression, "schema")
    3049        return self.func(
    3050            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
    3051        )
    3052
    3053    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    3054        this = self.sql(expression, "this")
    3055        kind = self.sql(expression, "kind")
    3056        path = self.sql(expression, "path")
    3057        path = f" {path}" if path else ""
    3058        as_json = " AS JSON" if expression.args.get("as_json") else ""
    3059        return f"{this} {kind}{path}{as_json}"
    3060
    3061    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    3062        this = self.sql(expression, "this")
    3063        path = self.sql(expression, "path")
    3064        path = f", {path}" if path else ""
    3065        expressions = self.expressions(expression)
    3066        with_ = (
    3067            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    3068            if expressions
    3069            else ""
    3070        )
    3071        return f"OPENJSON({this}{path}){with_}"
    3072
    3073    def in_sql(self, expression: exp.In) -> str:
    3074        query = expression.args.get("query")
    3075        unnest = expression.args.get("unnest")
    3076        field = expression.args.get("field")
    3077        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    3078
    3079        if query:
    3080            in_sql = self.sql(query)
    3081        elif unnest:
    3082            in_sql = self.in_unnest_op(unnest)
    3083        elif field:
    3084            in_sql = self.sql(field)
    3085        else:
    3086            in_sql = f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})"
    3087
    3088        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"
    3089
    3090    def in_unnest_op(self, unnest: exp.Unnest) -> str:
    3091        return f"(SELECT {self.sql(unnest)})"
    3092
    3093    def interval_sql(self, expression: exp.Interval) -> str:
    3094        unit = self.sql(expression, "unit")
    3095        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    3096            unit = self.TIME_PART_SINGULARS.get(unit, unit)
    3097        unit = f" {unit}" if unit else ""
    3098
    3099        if self.SINGLE_STRING_INTERVAL:
    3100            this = expression.this.name if expression.this else ""
    3101            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    3102
    3103        this = self.sql(expression, "this")
    3104        if this:
    3105            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    3106            this = f" {this}" if unwrapped else f" ({this})"
    3107
    3108        return f"INTERVAL{this}{unit}"
    3109
    3110    def return_sql(self, expression: exp.Return) -> str:
    3111        return f"RETURN {self.sql(expression, 'this')}"
    3112
    3113    def reference_sql(self, expression: exp.Reference) -> str:
    3114        this = self.sql(expression, "this")
    3115        expressions = self.expressions(expression, flat=True)
    3116        expressions = f"({expressions})" if expressions else ""
    3117        options = self.expressions(expression, key="options", flat=True, sep=" ")
    3118        options = f" {options}" if options else ""
    3119        return f"REFERENCES {this}{expressions}{options}"
    3120
    3121    def anonymous_sql(self, expression: exp.Anonymous) -> str:
    3122        # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive
    3123        parent = expression.parent
    3124        is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression
    3125        return self.func(
    3126            self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified
    3127        )
    3128
    3129    def paren_sql(self, expression: exp.Paren) -> str:
    3130        sql = self.seg(self.indent(self.sql(expression, "this")), sep="")
    3131        return f"({sql}{self.seg(')', sep='')}"
    3132
    3133    def neg_sql(self, expression: exp.Neg) -> str:
    3134        # This makes sure we don't convert "- - 5" to "--5", which is a comment
    3135        this_sql = self.sql(expression, "this")
    3136        sep = " " if this_sql[0] == "-" else ""
    3137        return f"-{sep}{this_sql}"
    3138
    3139    def not_sql(self, expression: exp.Not) -> str:
    3140        return f"NOT {self.sql(expression, 'this')}"
    3141
    3142    def alias_sql(self, expression: exp.Alias) -> str:
    3143        alias = self.sql(expression, "alias")
    3144        alias = f" AS {alias}" if alias else ""
    3145        return f"{self.sql(expression, 'this')}{alias}"
    3146
    3147    def pivotalias_sql(self, expression: exp.PivotAlias) -> str:
    3148        alias = expression.args["alias"]
    3149
    3150        parent = expression.parent
    3151        pivot = parent and parent.parent
    3152
    3153        if isinstance(pivot, exp.Pivot) and pivot.unpivot:
    3154            identifier_alias = isinstance(alias, exp.Identifier)
    3155            literal_alias = isinstance(alias, exp.Literal)
    3156
    3157            if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    3158                alias.replace(exp.Literal.string(alias.output_name))
    3159            elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    3160                alias.replace(exp.to_identifier(alias.output_name))
    3161
    3162        return self.alias_sql(expression)
    3163
    3164    def aliases_sql(self, expression: exp.Aliases) -> str:
    3165        return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})"
    3166
    3167    def atindex_sql(self, expression: exp.AtTimeZone) -> str:
    3168        this = self.sql(expression, "this")
    3169        index = self.sql(expression, "expression")
    3170        return f"{this} AT {index}"
    3171
    3172    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    3173        this = self.sql(expression, "this")
    3174        zone = self.sql(expression, "zone")
    3175        return f"{this} AT TIME ZONE {zone}"
    3176
    3177    def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str:
    3178        this = self.sql(expression, "this")
    3179        zone = self.sql(expression, "zone")
    3180        return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'"
    3181
    3182    def add_sql(self, expression: exp.Add) -> str:
    3183        return self.binary(expression, "+")
    3184
    3185    def and_sql(
    3186        self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None
    3187    ) -> str:
    3188        return self.connector_sql(expression, "AND", stack)
    3189
    3190    def or_sql(
    3191        self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None
    3192    ) -> str:
    3193        return self.connector_sql(expression, "OR", stack)
    3194
    3195    def xor_sql(
    3196        self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None
    3197    ) -> str:
    3198        return self.connector_sql(expression, "XOR", stack)
    3199
    3200    def connector_sql(
    3201        self,
    3202        expression: exp.Connector,
    3203        op: str,
    3204        stack: t.Optional[t.List[str | exp.Expression]] = None,
    3205    ) -> str:
    3206        if stack is not None:
    3207            if expression.expressions:
    3208                stack.append(self.expressions(expression, sep=f" {op} "))
    3209            else:
    3210                stack.append(expression.right)
    3211                if expression.comments and self.comments:
    3212                    for comment in expression.comments:
    3213                        if comment:
    3214                            op += f" /*{self.pad_comment(comment)}*/"
    3215                stack.extend((op, expression.left))
    3216            return op
    3217
    3218        stack = [expression]
    3219        sqls: t.List[str] = []
    3220        ops = set()
    3221
    3222        while stack:
    3223            node = stack.pop()
    3224            if isinstance(node, exp.Connector):
    3225                ops.add(getattr(self, f"{node.key}_sql")(node, stack))
    3226            else:
    3227                sql = self.sql(node)
    3228                if sqls and sqls[-1] in ops:
    3229                    sqls[-1] += f" {sql}"
    3230                else:
    3231                    sqls.append(sql)
    3232
    3233        sep = "\n" if self.pretty and self.too_wide(sqls) else " "
    3234        return sep.join(sqls)
    3235
    3236    def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str:
    3237        return self.binary(expression, "&")
    3238
    3239    def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str:
    3240        return self.binary(expression, "<<")
    3241
    3242    def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str:
    3243        return f"~{self.sql(expression, 'this')}"
    3244
    3245    def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str:
    3246        return self.binary(expression, "|")
    3247
    3248    def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str:
    3249        return self.binary(expression, ">>")
    3250
    3251    def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str:
    3252        return self.binary(expression, "^")
    3253
    3254    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    3255        format_sql = self.sql(expression, "format")
    3256        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    3257        to_sql = self.sql(expression, "to")
    3258        to_sql = f" {to_sql}" if to_sql else ""
    3259        action = self.sql(expression, "action")
    3260        action = f" {action}" if action else ""
    3261        default = self.sql(expression, "default")
    3262        default = f" DEFAULT {default} ON CONVERSION ERROR" if default else ""
    3263        return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{default}{format_sql}{action})"
    3264
    3265    def currentdate_sql(self, expression: exp.CurrentDate) -> str:
    3266        zone = self.sql(expression, "this")
    3267        return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE"
    3268
    3269    def collate_sql(self, expression: exp.Collate) -> str:
    3270        if self.COLLATE_IS_FUNC:
    3271            return self.function_fallback_sql(expression)
    3272        return self.binary(expression, "COLLATE")
    3273
    3274    def command_sql(self, expression: exp.Command) -> str:
    3275        return f"{self.sql(expression, 'this')} {expression.text('expression').strip()}"
    3276
    3277    def comment_sql(self, expression: exp.Comment) -> str:
    3278        this = self.sql(expression, "this")
    3279        kind = expression.args["kind"]
    3280        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    3281        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    3282        expression_sql = self.sql(expression, "expression")
    3283        return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"
    3284
    3285    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    3286        this = self.sql(expression, "this")
    3287        delete = " DELETE" if expression.args.get("delete") else ""
    3288        recompress = self.sql(expression, "recompress")
    3289        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    3290        to_disk = self.sql(expression, "to_disk")
    3291        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    3292        to_volume = self.sql(expression, "to_volume")
    3293        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    3294        return f"{this}{delete}{recompress}{to_disk}{to_volume}"
    3295
    3296    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    3297        where = self.sql(expression, "where")
    3298        group = self.sql(expression, "group")
    3299        aggregates = self.expressions(expression, key="aggregates")
    3300        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    3301
    3302        if not (where or group or aggregates) and len(expression.expressions) == 1:
    3303            return f"TTL {self.expressions(expression, flat=True)}"
    3304
    3305        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"
    3306
    3307    def transaction_sql(self, expression: exp.Transaction) -> str:
    3308        return "BEGIN"
    3309
    3310    def commit_sql(self, expression: exp.Commit) -> str:
    3311        chain = expression.args.get("chain")
    3312        if chain is not None:
    3313            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    3314
    3315        return f"COMMIT{chain or ''}"
    3316
    3317    def rollback_sql(self, expression: exp.Rollback) -> str:
    3318        savepoint = expression.args.get("savepoint")
    3319        savepoint = f" TO {savepoint}" if savepoint else ""
    3320        return f"ROLLBACK{savepoint}"
    3321
    3322    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    3323        this = self.sql(expression, "this")
    3324
    3325        dtype = self.sql(expression, "dtype")
    3326        if dtype:
    3327            collate = self.sql(expression, "collate")
    3328            collate = f" COLLATE {collate}" if collate else ""
    3329            using = self.sql(expression, "using")
    3330            using = f" USING {using}" if using else ""
    3331            return f"ALTER COLUMN {this} {self.ALTER_SET_TYPE} {dtype}{collate}{using}"
    3332
    3333        default = self.sql(expression, "default")
    3334        if default:
    3335            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    3336
    3337        comment = self.sql(expression, "comment")
    3338        if comment:
    3339            return f"ALTER COLUMN {this} COMMENT {comment}"
    3340
    3341        visible = expression.args.get("visible")
    3342        if visible:
    3343            return f"ALTER COLUMN {this} SET {visible}"
    3344
    3345        allow_null = expression.args.get("allow_null")
    3346        drop = expression.args.get("drop")
    3347
    3348        if not drop and not allow_null:
    3349            self.unsupported("Unsupported ALTER COLUMN syntax")
    3350
    3351        if allow_null is not None:
    3352            keyword = "DROP" if drop else "SET"
    3353            return f"ALTER COLUMN {this} {keyword} NOT NULL"
    3354
    3355        return f"ALTER COLUMN {this} DROP DEFAULT"
    3356
    3357    def alterindex_sql(self, expression: exp.AlterIndex) -> str:
    3358        this = self.sql(expression, "this")
    3359
    3360        visible = expression.args.get("visible")
    3361        visible_sql = "VISIBLE" if visible else "INVISIBLE"
    3362
    3363        return f"ALTER INDEX {this} {visible_sql}"
    3364
    3365    def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str:
    3366        this = self.sql(expression, "this")
    3367        if not isinstance(expression.this, exp.Var):
    3368            this = f"KEY DISTKEY {this}"
    3369        return f"ALTER DISTSTYLE {this}"
    3370
    3371    def altersortkey_sql(self, expression: exp.AlterSortKey) -> str:
    3372        compound = " COMPOUND" if expression.args.get("compound") else ""
    3373        this = self.sql(expression, "this")
    3374        expressions = self.expressions(expression, flat=True)
    3375        expressions = f"({expressions})" if expressions else ""
    3376        return f"ALTER{compound} SORTKEY {this or expressions}"
    3377
    3378    def alterrename_sql(self, expression: exp.AlterRename) -> str:
    3379        if not self.RENAME_TABLE_WITH_DB:
    3380            # Remove db from tables
    3381            expression = expression.transform(
    3382                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    3383            ).assert_is(exp.AlterRename)
    3384        this = self.sql(expression, "this")
    3385        return f"RENAME TO {this}"
    3386
    3387    def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
    3388        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3389        old_column = self.sql(expression, "this")
    3390        new_column = self.sql(expression, "to")
    3391        return f"RENAME COLUMN{exists} {old_column} TO {new_column}"
    3392
    3393    def alterset_sql(self, expression: exp.AlterSet) -> str:
    3394        exprs = self.expressions(expression, flat=True)
    3395        return f"SET {exprs}"
    3396
    3397    def alter_sql(self, expression: exp.Alter) -> str:
    3398        actions = expression.args["actions"]
    3399
    3400        if isinstance(actions[0], exp.ColumnDef):
    3401            actions = self.add_column_sql(expression)
    3402        elif isinstance(actions[0], exp.Schema):
    3403            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    3404        elif isinstance(actions[0], exp.Delete):
    3405            actions = self.expressions(expression, key="actions", flat=True)
    3406        elif isinstance(actions[0], exp.Query):
    3407            actions = "AS " + self.expressions(expression, key="actions")
    3408        else:
    3409            actions = self.expressions(expression, key="actions", flat=True)
    3410
    3411        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3412        on_cluster = self.sql(expression, "cluster")
    3413        on_cluster = f" {on_cluster}" if on_cluster else ""
    3414        only = " ONLY" if expression.args.get("only") else ""
    3415        options = self.expressions(expression, key="options")
    3416        options = f", {options}" if options else ""
    3417        kind = self.sql(expression, "kind")
    3418        not_valid = " NOT VALID" if expression.args.get("not_valid") else ""
    3419
    3420        return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions}{not_valid}{options}"
    3421
    3422    def add_column_sql(self, expression: exp.Alter) -> str:
    3423        if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD:
    3424            return self.expressions(
    3425                expression,
    3426                key="actions",
    3427                prefix="ADD COLUMN ",
    3428                skip_first=True,
    3429            )
    3430        return f"ADD {self.expressions(expression, key='actions', flat=True)}"
    3431
    3432    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    3433        expressions = self.expressions(expression)
    3434        exists = " IF EXISTS " if expression.args.get("exists") else " "
    3435        return f"DROP{exists}{expressions}"
    3436
    3437    def addconstraint_sql(self, expression: exp.AddConstraint) -> str:
    3438        return f"ADD {self.expressions(expression)}"
    3439
    3440    def distinct_sql(self, expression: exp.Distinct) -> str:
    3441        this = self.expressions(expression, flat=True)
    3442
    3443        if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1:
    3444            case = exp.case()
    3445            for arg in expression.expressions:
    3446                case = case.when(arg.is_(exp.null()), exp.null())
    3447            this = self.sql(case.else_(f"({this})"))
    3448
    3449        this = f" {this}" if this else ""
    3450
    3451        on = self.sql(expression, "on")
    3452        on = f" ON {on}" if on else ""
    3453        return f"DISTINCT{this}{on}"
    3454
    3455    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
    3456        return self._embed_ignore_nulls(expression, "IGNORE NULLS")
    3457
    3458    def respectnulls_sql(self, expression: exp.RespectNulls) -> str:
    3459        return self._embed_ignore_nulls(expression, "RESPECT NULLS")
    3460
    3461    def havingmax_sql(self, expression: exp.HavingMax) -> str:
    3462        this_sql = self.sql(expression, "this")
    3463        expression_sql = self.sql(expression, "expression")
    3464        kind = "MAX" if expression.args.get("max") else "MIN"
    3465        return f"{this_sql} HAVING {kind} {expression_sql}"
    3466
    3467    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    3468        return self.sql(
    3469            exp.Cast(
    3470                this=exp.Div(this=expression.this, expression=expression.expression),
    3471                to=exp.DataType(this=exp.DataType.Type.INT),
    3472            )
    3473        )
    3474
    3475    def dpipe_sql(self, expression: exp.DPipe) -> str:
    3476        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    3477            return self.func(
    3478                "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten())
    3479            )
    3480        return self.binary(expression, "||")
    3481
    3482    def div_sql(self, expression: exp.Div) -> str:
    3483        l, r = expression.left, expression.right
    3484
    3485        if not self.dialect.SAFE_DIVISION and expression.args.get("safe"):
    3486            r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0)))
    3487
    3488        if self.dialect.TYPED_DIVISION and not expression.args.get("typed"):
    3489            if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES):
    3490                l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE))
    3491
    3492        elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"):
    3493            if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES):
    3494                return self.sql(
    3495                    exp.cast(
    3496                        l / r,
    3497                        to=exp.DataType.Type.BIGINT,
    3498                    )
    3499                )
    3500
    3501        return self.binary(expression, "/")
    3502
    3503    def safedivide_sql(self, expression: exp.SafeDivide) -> str:
    3504        n = exp._wrap(expression.this, exp.Binary)
    3505        d = exp._wrap(expression.expression, exp.Binary)
    3506        return self.sql(exp.If(this=d.neq(0), true=n / d, false=exp.Null()))
    3507
    3508    def overlaps_sql(self, expression: exp.Overlaps) -> str:
    3509        return self.binary(expression, "OVERLAPS")
    3510
    3511    def distance_sql(self, expression: exp.Distance) -> str:
    3512        return self.binary(expression, "<->")
    3513
    3514    def dot_sql(self, expression: exp.Dot) -> str:
    3515        return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}"
    3516
    3517    def eq_sql(self, expression: exp.EQ) -> str:
    3518        return self.binary(expression, "=")
    3519
    3520    def propertyeq_sql(self, expression: exp.PropertyEQ) -> str:
    3521        return self.binary(expression, ":=")
    3522
    3523    def escape_sql(self, expression: exp.Escape) -> str:
    3524        return self.binary(expression, "ESCAPE")
    3525
    3526    def glob_sql(self, expression: exp.Glob) -> str:
    3527        return self.binary(expression, "GLOB")
    3528
    3529    def gt_sql(self, expression: exp.GT) -> str:
    3530        return self.binary(expression, ">")
    3531
    3532    def gte_sql(self, expression: exp.GTE) -> str:
    3533        return self.binary(expression, ">=")
    3534
    3535    def ilike_sql(self, expression: exp.ILike) -> str:
    3536        return self.binary(expression, "ILIKE")
    3537
    3538    def ilikeany_sql(self, expression: exp.ILikeAny) -> str:
    3539        return self.binary(expression, "ILIKE ANY")
    3540
    3541    def is_sql(self, expression: exp.Is) -> str:
    3542        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    3543            return self.sql(
    3544                expression.this if expression.expression.this else exp.not_(expression.this)
    3545            )
    3546        return self.binary(expression, "IS")
    3547
    3548    def like_sql(self, expression: exp.Like) -> str:
    3549        return self.binary(expression, "LIKE")
    3550
    3551    def likeany_sql(self, expression: exp.LikeAny) -> str:
    3552        return self.binary(expression, "LIKE ANY")
    3553
    3554    def similarto_sql(self, expression: exp.SimilarTo) -> str:
    3555        return self.binary(expression, "SIMILAR TO")
    3556
    3557    def lt_sql(self, expression: exp.LT) -> str:
    3558        return self.binary(expression, "<")
    3559
    3560    def lte_sql(self, expression: exp.LTE) -> str:
    3561        return self.binary(expression, "<=")
    3562
    3563    def mod_sql(self, expression: exp.Mod) -> str:
    3564        return self.binary(expression, "%")
    3565
    3566    def mul_sql(self, expression: exp.Mul) -> str:
    3567        return self.binary(expression, "*")
    3568
    3569    def neq_sql(self, expression: exp.NEQ) -> str:
    3570        return self.binary(expression, "<>")
    3571
    3572    def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str:
    3573        return self.binary(expression, "IS NOT DISTINCT FROM")
    3574
    3575    def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str:
    3576        return self.binary(expression, "IS DISTINCT FROM")
    3577
    3578    def slice_sql(self, expression: exp.Slice) -> str:
    3579        return self.binary(expression, ":")
    3580
    3581    def sub_sql(self, expression: exp.Sub) -> str:
    3582        return self.binary(expression, "-")
    3583
    3584    def trycast_sql(self, expression: exp.TryCast) -> str:
    3585        return self.cast_sql(expression, safe_prefix="TRY_")
    3586
    3587    def jsoncast_sql(self, expression: exp.JSONCast) -> str:
    3588        return self.cast_sql(expression)
    3589
    3590    def try_sql(self, expression: exp.Try) -> str:
    3591        if not self.TRY_SUPPORTED:
    3592            self.unsupported("Unsupported TRY function")
    3593            return self.sql(expression, "this")
    3594
    3595        return self.func("TRY", expression.this)
    3596
    3597    def log_sql(self, expression: exp.Log) -> str:
    3598        this = expression.this
    3599        expr = expression.expression
    3600
    3601        if self.dialect.LOG_BASE_FIRST is False:
    3602            this, expr = expr, this
    3603        elif self.dialect.LOG_BASE_FIRST is None and expr:
    3604            if this.name in ("2", "10"):
    3605                return self.func(f"LOG{this.name}", expr)
    3606
    3607            self.unsupported(f"Unsupported logarithm with base {self.sql(this)}")
    3608
    3609        return self.func("LOG", this, expr)
    3610
    3611    def use_sql(self, expression: exp.Use) -> str:
    3612        kind = self.sql(expression, "kind")
    3613        kind = f" {kind}" if kind else ""
    3614        this = self.sql(expression, "this") or self.expressions(expression, flat=True)
    3615        this = f" {this}" if this else ""
    3616        return f"USE{kind}{this}"
    3617
    3618    def binary(self, expression: exp.Binary, op: str) -> str:
    3619        sqls: t.List[str] = []
    3620        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    3621        binary_type = type(expression)
    3622
    3623        while stack:
    3624            node = stack.pop()
    3625
    3626            if type(node) is binary_type:
    3627                op_func = node.args.get("operator")
    3628                if op_func:
    3629                    op = f"OPERATOR({self.sql(op_func)})"
    3630
    3631                stack.append(node.right)
    3632                stack.append(f" {self.maybe_comment(op, comments=node.comments)} ")
    3633                stack.append(node.left)
    3634            else:
    3635                sqls.append(self.sql(node))
    3636
    3637        return "".join(sqls)
    3638
    3639    def ceil_floor(self, expression: exp.Ceil | exp.Floor) -> str:
    3640        to_clause = self.sql(expression, "to")
    3641        if to_clause:
    3642            return f"{expression.sql_name()}({self.sql(expression, 'this')} TO {to_clause})"
    3643
    3644        return self.function_fallback_sql(expression)
    3645
    3646    def function_fallback_sql(self, expression: exp.Func) -> str:
    3647        args = []
    3648
    3649        for key in expression.arg_types:
    3650            arg_value = expression.args.get(key)
    3651
    3652            if isinstance(arg_value, list):
    3653                for value in arg_value:
    3654                    args.append(value)
    3655            elif arg_value is not None:
    3656                args.append(arg_value)
    3657
    3658        if self.dialect.PRESERVE_ORIGINAL_NAMES:
    3659            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
    3660        else:
    3661            name = expression.sql_name()
    3662
    3663        return self.func(name, *args)
    3664
    3665    def func(
    3666        self,
    3667        name: str,
    3668        *args: t.Optional[exp.Expression | str],
    3669        prefix: str = "(",
    3670        suffix: str = ")",
    3671        normalize: bool = True,
    3672    ) -> str:
    3673        name = self.normalize_func(name) if normalize else name
    3674        return f"{name}{prefix}{self.format_args(*args)}{suffix}"
    3675
    3676    def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str:
    3677        arg_sqls = tuple(
    3678            self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool)
    3679        )
    3680        if self.pretty and self.too_wide(arg_sqls):
    3681            return self.indent(
    3682                "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True
    3683            )
    3684        return sep.join(arg_sqls)
    3685
    3686    def too_wide(self, args: t.Iterable) -> bool:
    3687        return sum(len(arg) for arg in args) > self.max_text_width
    3688
    3689    def format_time(
    3690        self,
    3691        expression: exp.Expression,
    3692        inverse_time_mapping: t.Optional[t.Dict[str, str]] = None,
    3693        inverse_time_trie: t.Optional[t.Dict] = None,
    3694    ) -> t.Optional[str]:
    3695        return format_time(
    3696            self.sql(expression, "format"),
    3697            inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING,
    3698            inverse_time_trie or self.dialect.INVERSE_TIME_TRIE,
    3699        )
    3700
    3701    def expressions(
    3702        self,
    3703        expression: t.Optional[exp.Expression] = None,
    3704        key: t.Optional[str] = None,
    3705        sqls: t.Optional[t.Collection[str | exp.Expression]] = None,
    3706        flat: bool = False,
    3707        indent: bool = True,
    3708        skip_first: bool = False,
    3709        skip_last: bool = False,
    3710        sep: str = ", ",
    3711        prefix: str = "",
    3712        dynamic: bool = False,
    3713        new_line: bool = False,
    3714    ) -> str:
    3715        expressions = expression.args.get(key or "expressions") if expression else sqls
    3716
    3717        if not expressions:
    3718            return ""
    3719
    3720        if flat:
    3721            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
    3722
    3723        num_sqls = len(expressions)
    3724        result_sqls = []
    3725
    3726        for i, e in enumerate(expressions):
    3727            sql = self.sql(e, comment=False)
    3728            if not sql:
    3729                continue
    3730
    3731            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    3732
    3733            if self.pretty:
    3734                if self.leading_comma:
    3735                    result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}")
    3736                else:
    3737                    result_sqls.append(
    3738                        f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}"
    3739                    )
    3740            else:
    3741                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    3742
    3743        if self.pretty and (not dynamic or self.too_wide(result_sqls)):
    3744            if new_line:
    3745                result_sqls.insert(0, "")
    3746                result_sqls.append("")
    3747            result_sql = "\n".join(s.rstrip() for s in result_sqls)
    3748        else:
    3749            result_sql = "".join(result_sqls)
    3750
    3751        return (
    3752            self.indent(result_sql, skip_first=skip_first, skip_last=skip_last)
    3753            if indent
    3754            else result_sql
    3755        )
    3756
    3757    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    3758        flat = flat or isinstance(expression.parent, exp.Properties)
    3759        expressions_sql = self.expressions(expression, flat=flat)
    3760        if flat:
    3761            return f"{op} {expressions_sql}"
    3762        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"
    3763
    3764    def naked_property(self, expression: exp.Property) -> str:
    3765        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    3766        if not property_name:
    3767            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    3768        return f"{property_name} {self.sql(expression, 'this')}"
    3769
    3770    def tag_sql(self, expression: exp.Tag) -> str:
    3771        return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}"
    3772
    3773    def token_sql(self, token_type: TokenType) -> str:
    3774        return self.TOKEN_MAPPING.get(token_type, token_type.name)
    3775
    3776    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    3777        this = self.sql(expression, "this")
    3778        expressions = self.no_identify(self.expressions, expression)
    3779        expressions = (
    3780            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    3781        )
    3782        return f"{this}{expressions}" if expressions.strip() != "" else this
    3783
    3784    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    3785        this = self.sql(expression, "this")
    3786        expressions = self.expressions(expression, flat=True)
    3787        return f"{this}({expressions})"
    3788
    3789    def kwarg_sql(self, expression: exp.Kwarg) -> str:
    3790        return self.binary(expression, "=>")
    3791
    3792    def when_sql(self, expression: exp.When) -> str:
    3793        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    3794        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    3795        condition = self.sql(expression, "condition")
    3796        condition = f" AND {condition}" if condition else ""
    3797
    3798        then_expression = expression.args.get("then")
    3799        if isinstance(then_expression, exp.Insert):
    3800            this = self.sql(then_expression, "this")
    3801            this = f"INSERT {this}" if this else "INSERT"
    3802            then = self.sql(then_expression, "expression")
    3803            then = f"{this} VALUES {then}" if then else this
    3804        elif isinstance(then_expression, exp.Update):
    3805            if isinstance(then_expression.args.get("expressions"), exp.Star):
    3806                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    3807            else:
    3808                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    3809        else:
    3810            then = self.sql(then_expression)
    3811        return f"WHEN {matched}{source}{condition} THEN {then}"
    3812
    3813    def whens_sql(self, expression: exp.Whens) -> str:
    3814        return self.expressions(expression, sep=" ", indent=False)
    3815
    3816    def merge_sql(self, expression: exp.Merge) -> str:
    3817        table = expression.this
    3818        table_alias = ""
    3819
    3820        hints = table.args.get("hints")
    3821        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
    3822            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
    3823            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
    3824
    3825        this = self.sql(table)
    3826        using = f"USING {self.sql(expression, 'using')}"
    3827        on = f"ON {self.sql(expression, 'on')}"
    3828        whens = self.sql(expression, "whens")
    3829
    3830        returning = self.sql(expression, "returning")
    3831        if returning:
    3832            whens = f"{whens}{returning}"
    3833
    3834        sep = self.sep()
    3835
    3836        return self.prepend_ctes(
    3837            expression,
    3838            f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}",
    3839        )
    3840
    3841    @unsupported_args("format")
    3842    def tochar_sql(self, expression: exp.ToChar) -> str:
    3843        return self.sql(exp.cast(expression.this, exp.DataType.Type.TEXT))
    3844
    3845    def tonumber_sql(self, expression: exp.ToNumber) -> str:
    3846        if not self.SUPPORTS_TO_NUMBER:
    3847            self.unsupported("Unsupported TO_NUMBER function")
    3848            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3849
    3850        fmt = expression.args.get("format")
    3851        if not fmt:
    3852            self.unsupported("Conversion format is required for TO_NUMBER")
    3853            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3854
    3855        return self.func("TO_NUMBER", expression.this, fmt)
    3856
    3857    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    3858        this = self.sql(expression, "this")
    3859        kind = self.sql(expression, "kind")
    3860        settings_sql = self.expressions(expression, key="settings", sep=" ")
    3861        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    3862        return f"{this}({kind}{args})"
    3863
    3864    def dictrange_sql(self, expression: exp.DictRange) -> str:
    3865        this = self.sql(expression, "this")
    3866        max = self.sql(expression, "max")
    3867        min = self.sql(expression, "min")
    3868        return f"{this}(MIN {min} MAX {max})"
    3869
    3870    def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str:
    3871        return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}"
    3872
    3873    def duplicatekeyproperty_sql(self, expression: exp.DuplicateKeyProperty) -> str:
    3874        return f"DUPLICATE KEY ({self.expressions(expression, flat=True)})"
    3875
    3876    # https://docs.starrocks.io/docs/sql-reference/sql-statements/table_bucket_part_index/CREATE_TABLE/
    3877    def uniquekeyproperty_sql(self, expression: exp.UniqueKeyProperty) -> str:
    3878        return f"UNIQUE KEY ({self.expressions(expression, flat=True)})"
    3879
    3880    # https://docs.starrocks.io/docs/sql-reference/sql-statements/data-definition/CREATE_TABLE/#distribution_desc
    3881    def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str:
    3882        expressions = self.expressions(expression, flat=True)
    3883        expressions = f" {self.wrap(expressions)}" if expressions else ""
    3884        buckets = self.sql(expression, "buckets")
    3885        kind = self.sql(expression, "kind")
    3886        buckets = f" BUCKETS {buckets}" if buckets else ""
    3887        order = self.sql(expression, "order")
    3888        return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}"
    3889
    3890    def oncluster_sql(self, expression: exp.OnCluster) -> str:
    3891        return ""
    3892
    3893    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    3894        expressions = self.expressions(expression, key="expressions", flat=True)
    3895        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    3896        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    3897        buckets = self.sql(expression, "buckets")
    3898        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"
    3899
    3900    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    3901        this = self.sql(expression, "this")
    3902        having = self.sql(expression, "having")
    3903
    3904        if having:
    3905            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    3906
    3907        return self.func("ANY_VALUE", this)
    3908
    3909    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
    3910        transform = self.func("TRANSFORM", *expression.expressions)
    3911        row_format_before = self.sql(expression, "row_format_before")
    3912        row_format_before = f" {row_format_before}" if row_format_before else ""
    3913        record_writer = self.sql(expression, "record_writer")
    3914        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
    3915        using = f" USING {self.sql(expression, 'command_script')}"
    3916        schema = self.sql(expression, "schema")
    3917        schema = f" AS {schema}" if schema else ""
    3918        row_format_after = self.sql(expression, "row_format_after")
    3919        row_format_after = f" {row_format_after}" if row_format_after else ""
    3920        record_reader = self.sql(expression, "record_reader")
    3921        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
    3922        return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}"
    3923
    3924    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
    3925        key_block_size = self.sql(expression, "key_block_size")
    3926        if key_block_size:
    3927            return f"KEY_BLOCK_SIZE = {key_block_size}"
    3928
    3929        using = self.sql(expression, "using")
    3930        if using:
    3931            return f"USING {using}"
    3932
    3933        parser = self.sql(expression, "parser")
    3934        if parser:
    3935            return f"WITH PARSER {parser}"
    3936
    3937        comment = self.sql(expression, "comment")
    3938        if comment:
    3939            return f"COMMENT {comment}"
    3940
    3941        visible = expression.args.get("visible")
    3942        if visible is not None:
    3943            return "VISIBLE" if visible else "INVISIBLE"
    3944
    3945        engine_attr = self.sql(expression, "engine_attr")
    3946        if engine_attr:
    3947            return f"ENGINE_ATTRIBUTE = {engine_attr}"
    3948
    3949        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
    3950        if secondary_engine_attr:
    3951            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
    3952
    3953        self.unsupported("Unsupported index constraint option.")
    3954        return ""
    3955
    3956    def checkcolumnconstraint_sql(self, expression: exp.CheckColumnConstraint) -> str:
    3957        enforced = " ENFORCED" if expression.args.get("enforced") else ""
    3958        return f"CHECK ({self.sql(expression, 'this')}){enforced}"
    3959
    3960    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
    3961        kind = self.sql(expression, "kind")
    3962        kind = f"{kind} INDEX" if kind else "INDEX"
    3963        this = self.sql(expression, "this")
    3964        this = f" {this}" if this else ""
    3965        index_type = self.sql(expression, "index_type")
    3966        index_type = f" USING {index_type}" if index_type else ""
    3967        expressions = self.expressions(expression, flat=True)
    3968        expressions = f" ({expressions})" if expressions else ""
    3969        options = self.expressions(expression, key="options", sep=" ")
    3970        options = f" {options}" if options else ""
    3971        return f"{kind}{this}{index_type}{expressions}{options}"
    3972
    3973    def nvl2_sql(self, expression: exp.Nvl2) -> str:
    3974        if self.NVL2_SUPPORTED:
    3975            return self.function_fallback_sql(expression)
    3976
    3977        case = exp.Case().when(
    3978            expression.this.is_(exp.null()).not_(copy=False),
    3979            expression.args["true"],
    3980            copy=False,
    3981        )
    3982        else_cond = expression.args.get("false")
    3983        if else_cond:
    3984            case.else_(else_cond, copy=False)
    3985
    3986        return self.sql(case)
    3987
    3988    def comprehension_sql(self, expression: exp.Comprehension) -> str:
    3989        this = self.sql(expression, "this")
    3990        expr = self.sql(expression, "expression")
    3991        iterator = self.sql(expression, "iterator")
    3992        condition = self.sql(expression, "condition")
    3993        condition = f" IF {condition}" if condition else ""
    3994        return f"{this} FOR {expr} IN {iterator}{condition}"
    3995
    3996    def columnprefix_sql(self, expression: exp.ColumnPrefix) -> str:
    3997        return f"{self.sql(expression, 'this')}({self.sql(expression, 'expression')})"
    3998
    3999    def opclass_sql(self, expression: exp.Opclass) -> str:
    4000        return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}"
    4001
    4002    def predict_sql(self, expression: exp.Predict) -> str:
    4003        model = self.sql(expression, "this")
    4004        model = f"MODEL {model}"
    4005        table = self.sql(expression, "expression")
    4006        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
    4007        parameters = self.sql(expression, "params_struct")
    4008        return self.func("PREDICT", model, table, parameters or None)
    4009
    4010    def forin_sql(self, expression: exp.ForIn) -> str:
    4011        this = self.sql(expression, "this")
    4012        expression_sql = self.sql(expression, "expression")
    4013        return f"FOR {this} DO {expression_sql}"
    4014
    4015    def refresh_sql(self, expression: exp.Refresh) -> str:
    4016        this = self.sql(expression, "this")
    4017        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
    4018        return f"REFRESH {table}{this}"
    4019
    4020    def toarray_sql(self, expression: exp.ToArray) -> str:
    4021        arg = expression.this
    4022        if not arg.type:
    4023            from sqlglot.optimizer.annotate_types import annotate_types
    4024
    4025            arg = annotate_types(arg, dialect=self.dialect)
    4026
    4027        if arg.is_type(exp.DataType.Type.ARRAY):
    4028            return self.sql(arg)
    4029
    4030        cond_for_null = arg.is_(exp.null())
    4031        return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False)))
    4032
    4033    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
    4034        this = expression.this
    4035        time_format = self.format_time(expression)
    4036
    4037        if time_format:
    4038            return self.sql(
    4039                exp.cast(
    4040                    exp.StrToTime(this=this, format=expression.args["format"]),
    4041                    exp.DataType.Type.TIME,
    4042                )
    4043            )
    4044
    4045        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
    4046            return self.sql(this)
    4047
    4048        return self.sql(exp.cast(this, exp.DataType.Type.TIME))
    4049
    4050    def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str:
    4051        this = expression.this
    4052        if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP):
    4053            return self.sql(this)
    4054
    4055        return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect))
    4056
    4057    def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str:
    4058        this = expression.this
    4059        if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME):
    4060            return self.sql(this)
    4061
    4062        return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect))
    4063
    4064    def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:
    4065        this = expression.this
    4066        time_format = self.format_time(expression)
    4067
    4068        if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT):
    4069            return self.sql(
    4070                exp.cast(
    4071                    exp.StrToTime(this=this, format=expression.args["format"]),
    4072                    exp.DataType.Type.DATE,
    4073                )
    4074            )
    4075
    4076        if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE):
    4077            return self.sql(this)
    4078
    4079        return self.sql(exp.cast(this, exp.DataType.Type.DATE))
    4080
    4081    def unixdate_sql(self, expression: exp.UnixDate) -> str:
    4082        return self.sql(
    4083            exp.func(
    4084                "DATEDIFF",
    4085                expression.this,
    4086                exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE),
    4087                "day",
    4088            )
    4089        )
    4090
    4091    def lastday_sql(self, expression: exp.LastDay) -> str:
    4092        if self.LAST_DAY_SUPPORTS_DATE_PART:
    4093            return self.function_fallback_sql(expression)
    4094
    4095        unit = expression.text("unit")
    4096        if unit and unit != "MONTH":
    4097            self.unsupported("Date parts are not supported in LAST_DAY.")
    4098
    4099        return self.func("LAST_DAY", expression.this)
    4100
    4101    def dateadd_sql(self, expression: exp.DateAdd) -> str:
    4102        from sqlglot.dialects.dialect import unit_to_str
    4103
    4104        return self.func(
    4105            "DATE_ADD", expression.this, expression.expression, unit_to_str(expression)
    4106        )
    4107
    4108    def arrayany_sql(self, expression: exp.ArrayAny) -> str:
    4109        if self.CAN_IMPLEMENT_ARRAY_ANY:
    4110            filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression)
    4111            filtered_not_empty = exp.ArraySize(this=filtered).neq(0)
    4112            original_is_empty = exp.ArraySize(this=expression.this).eq(0)
    4113            return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty)))
    4114
    4115        from sqlglot.dialects import Dialect
    4116
    4117        # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect
    4118        if self.dialect.__class__ != Dialect:
    4119            self.unsupported("ARRAY_ANY is unsupported")
    4120
    4121        return self.function_fallback_sql(expression)
    4122
    4123    def struct_sql(self, expression: exp.Struct) -> str:
    4124        expression.set(
    4125            "expressions",
    4126            [
    4127                exp.alias_(e.expression, e.name if e.this.is_string else e.this)
    4128                if isinstance(e, exp.PropertyEQ)
    4129                else e
    4130                for e in expression.expressions
    4131            ],
    4132        )
    4133
    4134        return self.function_fallback_sql(expression)
    4135
    4136    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
    4137        low = self.sql(expression, "this")
    4138        high = self.sql(expression, "expression")
    4139
    4140        return f"{low} TO {high}"
    4141
    4142    def truncatetable_sql(self, expression: exp.TruncateTable) -> str:
    4143        target = "DATABASE" if expression.args.get("is_database") else "TABLE"
    4144        tables = f" {self.expressions(expression)}"
    4145
    4146        exists = " IF EXISTS" if expression.args.get("exists") else ""
    4147
    4148        on_cluster = self.sql(expression, "cluster")
    4149        on_cluster = f" {on_cluster}" if on_cluster else ""
    4150
    4151        identity = self.sql(expression, "identity")
    4152        identity = f" {identity} IDENTITY" if identity else ""
    4153
    4154        option = self.sql(expression, "option")
    4155        option = f" {option}" if option else ""
    4156
    4157        partition = self.sql(expression, "partition")
    4158        partition = f" {partition}" if partition else ""
    4159
    4160        return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"
    4161
    4162    # This transpiles T-SQL's CONVERT function
    4163    # https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16
    4164    def convert_sql(self, expression: exp.Convert) -> str:
    4165        to = expression.this
    4166        value = expression.expression
    4167        style = expression.args.get("style")
    4168        safe = expression.args.get("safe")
    4169        strict = expression.args.get("strict")
    4170
    4171        if not to or not value:
    4172            return ""
    4173
    4174        # Retrieve length of datatype and override to default if not specified
    4175        if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    4176            to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
    4177
    4178        transformed: t.Optional[exp.Expression] = None
    4179        cast = exp.Cast if strict else exp.TryCast
    4180
    4181        # Check whether a conversion with format (T-SQL calls this 'style') is applicable
    4182        if isinstance(style, exp.Literal) and style.is_int:
    4183            from sqlglot.dialects.tsql import TSQL
    4184
    4185            style_value = style.name
    4186            converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value)
    4187            if not converted_style:
    4188                self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}")
    4189
    4190            fmt = exp.Literal.string(converted_style)
    4191
    4192            if to.this == exp.DataType.Type.DATE:
    4193                transformed = exp.StrToDate(this=value, format=fmt)
    4194            elif to.this in (exp.DataType.Type.DATETIME, exp.DataType.Type.DATETIME2):
    4195                transformed = exp.StrToTime(this=value, format=fmt)
    4196            elif to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    4197                transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe)
    4198            elif to.this == exp.DataType.Type.TEXT:
    4199                transformed = exp.TimeToStr(this=value, format=fmt)
    4200
    4201        if not transformed:
    4202            transformed = cast(this=value, to=to, safe=safe)
    4203
    4204        return self.sql(transformed)
    4205
    4206    def _jsonpathkey_sql(self, expression: exp.JSONPathKey) -> str:
    4207        this = expression.this
    4208        if isinstance(this, exp.JSONPathWildcard):
    4209            this = self.json_path_part(this)
    4210            return f".{this}" if this else ""
    4211
    4212        if exp.SAFE_IDENTIFIER_RE.match(this):
    4213            return f".{this}"
    4214
    4215        this = self.json_path_part(this)
    4216        return (
    4217            f"[{this}]"
    4218            if self._quote_json_path_key_using_brackets and self.JSON_PATH_BRACKETED_KEY_SUPPORTED
    4219            else f".{this}"
    4220        )
    4221
    4222    def _jsonpathsubscript_sql(self, expression: exp.JSONPathSubscript) -> str:
    4223        this = self.json_path_part(expression.this)
    4224        return f"[{this}]" if this else ""
    4225
    4226    def _simplify_unless_literal(self, expression: E) -> E:
    4227        if not isinstance(expression, exp.Literal):
    4228            from sqlglot.optimizer.simplify import simplify
    4229
    4230            expression = simplify(expression, dialect=self.dialect)
    4231
    4232        return expression
    4233
    4234    def _embed_ignore_nulls(self, expression: exp.IgnoreNulls | exp.RespectNulls, text: str) -> str:
    4235        if self.IGNORE_NULLS_IN_FUNC and not expression.meta.get("inline"):
    4236            # The first modifier here will be the one closest to the AggFunc's arg
    4237            mods = sorted(
    4238                expression.find_all(exp.HavingMax, exp.Order, exp.Limit),
    4239                key=lambda x: 0
    4240                if isinstance(x, exp.HavingMax)
    4241                else (1 if isinstance(x, exp.Order) else 2),
    4242            )
    4243
    4244            if mods:
    4245                mod = mods[0]
    4246                this = expression.__class__(this=mod.this.copy())
    4247                this.meta["inline"] = True
    4248                mod.this.replace(this)
    4249                return self.sql(expression.this)
    4250
    4251            agg_func = expression.find(exp.AggFunc)
    4252
    4253            if agg_func:
    4254                return self.sql(agg_func)[:-1] + f" {text})"
    4255
    4256        return f"{self.sql(expression, 'this')} {text}"
    4257
    4258    def _replace_line_breaks(self, string: str) -> str:
    4259        """We don't want to extra indent line breaks so we temporarily replace them with sentinels."""
    4260        if self.pretty:
    4261            return string.replace("\n", self.SENTINEL_LINE_BREAK)
    4262        return string
    4263
    4264    def copyparameter_sql(self, expression: exp.CopyParameter) -> str:
    4265        option = self.sql(expression, "this")
    4266
    4267        if expression.expressions:
    4268            upper = option.upper()
    4269
    4270            # Snowflake FILE_FORMAT options are separated by whitespace
    4271            sep = " " if upper == "FILE_FORMAT" else ", "
    4272
    4273            # Databricks copy/format options do not set their list of values with EQ
    4274            op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = "
    4275            values = self.expressions(expression, flat=True, sep=sep)
    4276            return f"{option}{op}({values})"
    4277
    4278        value = self.sql(expression, "expression")
    4279
    4280        if not value:
    4281            return option
    4282
    4283        op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " "
    4284
    4285        return f"{option}{op}{value}"
    4286
    4287    def credentials_sql(self, expression: exp.Credentials) -> str:
    4288        cred_expr = expression.args.get("credentials")
    4289        if isinstance(cred_expr, exp.Literal):
    4290            # Redshift case: CREDENTIALS <string>
    4291            credentials = self.sql(expression, "credentials")
    4292            credentials = f"CREDENTIALS {credentials}" if credentials else ""
    4293        else:
    4294            # Snowflake case: CREDENTIALS = (...)
    4295            credentials = self.expressions(expression, key="credentials", flat=True, sep=" ")
    4296            credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else ""
    4297
    4298        storage = self.sql(expression, "storage")
    4299        storage = f"STORAGE_INTEGRATION = {storage}" if storage else ""
    4300
    4301        encryption = self.expressions(expression, key="encryption", flat=True, sep=" ")
    4302        encryption = f" ENCRYPTION = ({encryption})" if encryption else ""
    4303
    4304        iam_role = self.sql(expression, "iam_role")
    4305        iam_role = f"IAM_ROLE {iam_role}" if iam_role else ""
    4306
    4307        region = self.sql(expression, "region")
    4308        region = f" REGION {region}" if region else ""
    4309
    4310        return f"{credentials}{storage}{encryption}{iam_role}{region}"
    4311
    4312    def copy_sql(self, expression: exp.Copy) -> str:
    4313        this = self.sql(expression, "this")
    4314        this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}"
    4315
    4316        credentials = self.sql(expression, "credentials")
    4317        credentials = self.seg(credentials) if credentials else ""
    4318        kind = self.seg("FROM" if expression.args.get("kind") else "TO")
    4319        files = self.expressions(expression, key="files", flat=True)
    4320
    4321        sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " "
    4322        params = self.expressions(
    4323            expression,
    4324            key="params",
    4325            sep=sep,
    4326            new_line=True,
    4327            skip_last=True,
    4328            skip_first=True,
    4329            indent=self.COPY_PARAMS_ARE_WRAPPED,
    4330        )
    4331
    4332        if params:
    4333            if self.COPY_PARAMS_ARE_WRAPPED:
    4334                params = f" WITH ({params})"
    4335            elif not self.pretty:
    4336                params = f" {params}"
    4337
    4338        return f"COPY{this}{kind} {files}{credentials}{params}"
    4339
    4340    def semicolon_sql(self, expression: exp.Semicolon) -> str:
    4341        return ""
    4342
    4343    def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str:
    4344        on_sql = "ON" if expression.args.get("on") else "OFF"
    4345        filter_col: t.Optional[str] = self.sql(expression, "filter_column")
    4346        filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None
    4347        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    4348        retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None
    4349
    4350        if filter_col or retention_period:
    4351            on_sql = self.func("ON", filter_col, retention_period)
    4352
    4353        return f"DATA_DELETION={on_sql}"
    4354
    4355    def maskingpolicycolumnconstraint_sql(
    4356        self, expression: exp.MaskingPolicyColumnConstraint
    4357    ) -> str:
    4358        this = self.sql(expression, "this")
    4359        expressions = self.expressions(expression, flat=True)
    4360        expressions = f" USING ({expressions})" if expressions else ""
    4361        return f"MASKING POLICY {this}{expressions}"
    4362
    4363    def gapfill_sql(self, expression: exp.GapFill) -> str:
    4364        this = self.sql(expression, "this")
    4365        this = f"TABLE {this}"
    4366        return self.func("GAP_FILL", this, *[v for k, v in expression.args.items() if k != "this"])
    4367
    4368    def scope_resolution(self, rhs: str, scope_name: str) -> str:
    4369        return self.func("SCOPE_RESOLUTION", scope_name or None, rhs)
    4370
    4371    def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str:
    4372        this = self.sql(expression, "this")
    4373        expr = expression.expression
    4374
    4375        if isinstance(expr, exp.Func):
    4376            # T-SQL's CLR functions are case sensitive
    4377            expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})"
    4378        else:
    4379            expr = self.sql(expression, "expression")
    4380
    4381        return self.scope_resolution(expr, this)
    4382
    4383    def parsejson_sql(self, expression: exp.ParseJSON) -> str:
    4384        if self.PARSE_JSON_NAME is None:
    4385            return self.sql(expression.this)
    4386
    4387        return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression)
    4388
    4389    def rand_sql(self, expression: exp.Rand) -> str:
    4390        lower = self.sql(expression, "lower")
    4391        upper = self.sql(expression, "upper")
    4392
    4393        if lower and upper:
    4394            return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}"
    4395        return self.func("RAND", expression.this)
    4396
    4397    def changes_sql(self, expression: exp.Changes) -> str:
    4398        information = self.sql(expression, "information")
    4399        information = f"INFORMATION => {information}"
    4400        at_before = self.sql(expression, "at_before")
    4401        at_before = f"{self.seg('')}{at_before}" if at_before else ""
    4402        end = self.sql(expression, "end")
    4403        end = f"{self.seg('')}{end}" if end else ""
    4404
    4405        return f"CHANGES ({information}){at_before}{end}"
    4406
    4407    def pad_sql(self, expression: exp.Pad) -> str:
    4408        prefix = "L" if expression.args.get("is_left") else "R"
    4409
    4410        fill_pattern = self.sql(expression, "fill_pattern") or None
    4411        if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED:
    4412            fill_pattern = "' '"
    4413
    4414        return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)
    4415
    4416    def summarize_sql(self, expression: exp.Summarize) -> str:
    4417        table = " TABLE" if expression.args.get("table") else ""
    4418        return f"SUMMARIZE{table} {self.sql(expression.this)}"
    4419
    4420    def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str:
    4421        generate_series = exp.GenerateSeries(**expression.args)
    4422
    4423        parent = expression.parent
    4424        if isinstance(parent, (exp.Alias, exp.TableAlias)):
    4425            parent = parent.parent
    4426
    4427        if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)):
    4428            return self.sql(exp.Unnest(expressions=[generate_series]))
    4429
    4430        if isinstance(parent, exp.Select):
    4431            self.unsupported("GenerateSeries projection unnesting is not supported.")
    4432
    4433        return self.sql(generate_series)
    4434
    4435    def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str:
    4436        exprs = expression.expressions
    4437        if not self.ARRAY_CONCAT_IS_VAR_LEN:
    4438            rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs)
    4439        else:
    4440            rhs = self.expressions(expression)
    4441
    4442        return self.func(name, expression.this, rhs or None)
    4443
    4444    def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str:
    4445        if self.SUPPORTS_CONVERT_TIMEZONE:
    4446            return self.function_fallback_sql(expression)
    4447
    4448        source_tz = expression.args.get("source_tz")
    4449        target_tz = expression.args.get("target_tz")
    4450        timestamp = expression.args.get("timestamp")
    4451
    4452        if source_tz and timestamp:
    4453            timestamp = exp.AtTimeZone(
    4454                this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz
    4455            )
    4456
    4457        expr = exp.AtTimeZone(this=timestamp, zone=target_tz)
    4458
    4459        return self.sql(expr)
    4460
    4461    def json_sql(self, expression: exp.JSON) -> str:
    4462        this = self.sql(expression, "this")
    4463        this = f" {this}" if this else ""
    4464
    4465        _with = expression.args.get("with")
    4466
    4467        if _with is None:
    4468            with_sql = ""
    4469        elif not _with:
    4470            with_sql = " WITHOUT"
    4471        else:
    4472            with_sql = " WITH"
    4473
    4474        unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else ""
    4475
    4476        return f"JSON{this}{with_sql}{unique_sql}"
    4477
    4478    def jsonvalue_sql(self, expression: exp.JSONValue) -> str:
    4479        def _generate_on_options(arg: t.Any) -> str:
    4480            return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}"
    4481
    4482        path = self.sql(expression, "path")
    4483        returning = self.sql(expression, "returning")
    4484        returning = f" RETURNING {returning}" if returning else ""
    4485
    4486        on_condition = self.sql(expression, "on_condition")
    4487        on_condition = f" {on_condition}" if on_condition else ""
    4488
    4489        return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}")
    4490
    4491    def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str:
    4492        else_ = "ELSE " if expression.args.get("else_") else ""
    4493        condition = self.sql(expression, "expression")
    4494        condition = f"WHEN {condition} THEN " if condition else else_
    4495        insert = self.sql(expression, "this")[len("INSERT") :].strip()
    4496        return f"{condition}{insert}"
    4497
    4498    def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str:
    4499        kind = self.sql(expression, "kind")
    4500        expressions = self.seg(self.expressions(expression, sep=" "))
    4501        res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}"
    4502        return res
    4503
    4504    def oncondition_sql(self, expression: exp.OnCondition) -> str:
    4505        # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR"
    4506        empty = expression.args.get("empty")
    4507        empty = (
    4508            f"DEFAULT {empty} ON EMPTY"
    4509            if isinstance(empty, exp.Expression)
    4510            else self.sql(expression, "empty")
    4511        )
    4512
    4513        error = expression.args.get("error")
    4514        error = (
    4515            f"DEFAULT {error} ON ERROR"
    4516            if isinstance(error, exp.Expression)
    4517            else self.sql(expression, "error")
    4518        )
    4519
    4520        if error and empty:
    4521            error = (
    4522                f"{empty} {error}"
    4523                if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR
    4524                else f"{error} {empty}"
    4525            )
    4526            empty = ""
    4527
    4528        null = self.sql(expression, "null")
    4529
    4530        return f"{empty}{error}{null}"
    4531
    4532    def jsonextractquote_sql(self, expression: exp.JSONExtractQuote) -> str:
    4533        scalar = " ON SCALAR STRING" if expression.args.get("scalar") else ""
    4534        return f"{self.sql(expression, 'option')} QUOTES{scalar}"
    4535
    4536    def jsonexists_sql(self, expression: exp.JSONExists) -> str:
    4537        this = self.sql(expression, "this")
    4538        path = self.sql(expression, "path")
    4539
    4540        passing = self.expressions(expression, "passing")
    4541        passing = f" PASSING {passing}" if passing else ""
    4542
    4543        on_condition = self.sql(expression, "on_condition")
    4544        on_condition = f" {on_condition}" if on_condition else ""
    4545
    4546        path = f"{path}{passing}{on_condition}"
    4547
    4548        return self.func("JSON_EXISTS", this, path)
    4549
    4550    def arrayagg_sql(self, expression: exp.ArrayAgg) -> str:
    4551        array_agg = self.function_fallback_sql(expression)
    4552
    4553        # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls
    4554        # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB)
    4555        if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"):
    4556            parent = expression.parent
    4557            if isinstance(parent, exp.Filter):
    4558                parent_cond = parent.expression.this
    4559                parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_()))
    4560            else:
    4561                this = expression.this
    4562                # Do not add the filter if the input is not a column (e.g. literal, struct etc)
    4563                if this.find(exp.Column):
    4564                    # DISTINCT is already present in the agg function, do not propagate it to FILTER as well
    4565                    this_sql = (
    4566                        self.expressions(this)
    4567                        if isinstance(this, exp.Distinct)
    4568                        else self.sql(expression, "this")
    4569                    )
    4570
    4571                    array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)"
    4572
    4573        return array_agg
    4574
    4575    def apply_sql(self, expression: exp.Apply) -> str:
    4576        this = self.sql(expression, "this")
    4577        expr = self.sql(expression, "expression")
    4578
    4579        return f"{this} APPLY({expr})"
    4580
    4581    def grant_sql(self, expression: exp.Grant) -> str:
    4582        privileges_sql = self.expressions(expression, key="privileges", flat=True)
    4583
    4584        kind = self.sql(expression, "kind")
    4585        kind = f" {kind}" if kind else ""
    4586
    4587        securable = self.sql(expression, "securable")
    4588        securable = f" {securable}" if securable else ""
    4589
    4590        principals = self.expressions(expression, key="principals", flat=True)
    4591
    4592        grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else ""
    4593
    4594        return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}"
    4595
    4596    def grantprivilege_sql(self, expression: exp.GrantPrivilege):
    4597        this = self.sql(expression, "this")
    4598        columns = self.expressions(expression, flat=True)
    4599        columns = f"({columns})" if columns else ""
    4600
    4601        return f"{this}{columns}"
    4602
    4603    def grantprincipal_sql(self, expression: exp.GrantPrincipal):
    4604        this = self.sql(expression, "this")
    4605
    4606        kind = self.sql(expression, "kind")
    4607        kind = f"{kind} " if kind else ""
    4608
    4609        return f"{kind}{this}"
    4610
    4611    def columns_sql(self, expression: exp.Columns):
    4612        func = self.function_fallback_sql(expression)
    4613        if expression.args.get("unpack"):
    4614            func = f"*{func}"
    4615
    4616        return func
    4617
    4618    def overlay_sql(self, expression: exp.Overlay):
    4619        this = self.sql(expression, "this")
    4620        expr = self.sql(expression, "expression")
    4621        from_sql = self.sql(expression, "from")
    4622        for_sql = self.sql(expression, "for")
    4623        for_sql = f" FOR {for_sql}" if for_sql else ""
    4624
    4625        return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})"
    4626
    4627    @unsupported_args("format")
    4628    def todouble_sql(self, expression: exp.ToDouble) -> str:
    4629        return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    4630
    4631    def string_sql(self, expression: exp.String) -> str:
    4632        this = expression.this
    4633        zone = expression.args.get("zone")
    4634
    4635        if zone:
    4636            # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>)
    4637            # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC
    4638            # set for source_tz to transpile the time conversion before the STRING cast
    4639            this = exp.ConvertTimezone(
    4640                source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this
    4641            )
    4642
    4643        return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR))
    4644
    4645    def median_sql(self, expression: exp.Median):
    4646        if not self.SUPPORTS_MEDIAN:
    4647            return self.sql(
    4648                exp.PercentileCont(this=expression.this, expression=exp.Literal.number(0.5))
    4649            )
    4650
    4651        return self.function_fallback_sql(expression)
    4652
    4653    def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str:
    4654        filler = self.sql(expression, "this")
    4655        filler = f" {filler}" if filler else ""
    4656        with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT"
    4657        return f"TRUNCATE{filler} {with_count}"
    4658
    4659    def unixseconds_sql(self, expression: exp.UnixSeconds) -> str:
    4660        if self.SUPPORTS_UNIX_SECONDS:
    4661            return self.function_fallback_sql(expression)
    4662
    4663        start_ts = exp.cast(
    4664            exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ
    4665        )
    4666
    4667        return self.sql(
    4668            exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS"))
    4669        )
    4670
    4671    def arraysize_sql(self, expression: exp.ArraySize) -> str:
    4672        dim = expression.expression
    4673
    4674        # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension)
    4675        if dim and self.ARRAY_SIZE_DIM_REQUIRED is None:
    4676            if not (dim.is_int and dim.name == "1"):
    4677                self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH")
    4678            dim = None
    4679
    4680        # If dimension is required but not specified, default initialize it
    4681        if self.ARRAY_SIZE_DIM_REQUIRED and not dim:
    4682            dim = exp.Literal.number(1)
    4683
    4684        return self.func(self.ARRAY_SIZE_NAME, expression.this, dim)
    4685
    4686    def attach_sql(self, expression: exp.Attach) -> str:
    4687        this = self.sql(expression, "this")
    4688        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
    4689        expressions = self.expressions(expression)
    4690        expressions = f" ({expressions})" if expressions else ""
    4691
    4692        return f"ATTACH{exists_sql} {this}{expressions}"
    4693
    4694    def detach_sql(self, expression: exp.Detach) -> str:
    4695        this = self.sql(expression, "this")
    4696        exists_sql = " IF EXISTS" if expression.args.get("exists") else ""
    4697
    4698        return f"DETACH{exists_sql} {this}"
    4699
    4700    def attachoption_sql(self, expression: exp.AttachOption) -> str:
    4701        this = self.sql(expression, "this")
    4702        value = self.sql(expression, "expression")
    4703        value = f" {value}" if value else ""
    4704        return f"{this}{value}"
    4705
    4706    def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str:
    4707        this_sql = self.sql(expression, "this")
    4708        if isinstance(expression.this, exp.Table):
    4709            this_sql = f"TABLE {this_sql}"
    4710
    4711        return self.func(
    4712            "FEATURES_AT_TIME",
    4713            this_sql,
    4714            expression.args.get("time"),
    4715            expression.args.get("num_rows"),
    4716            expression.args.get("ignore_feature_nulls"),
    4717        )
    4718
    4719    def watermarkcolumnconstraint_sql(self, expression: exp.WatermarkColumnConstraint) -> str:
    4720        return (
    4721            f"WATERMARK FOR {self.sql(expression, 'this')} AS {self.sql(expression, 'expression')}"
    4722        )
    4723
    4724    def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str:
    4725        encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE"
    4726        encode = f"{encode} {self.sql(expression, 'this')}"
    4727
    4728        properties = expression.args.get("properties")
    4729        if properties:
    4730            encode = f"{encode} {self.properties(properties)}"
    4731
    4732        return encode
    4733
    4734    def includeproperty_sql(self, expression: exp.IncludeProperty) -> str:
    4735        this = self.sql(expression, "this")
    4736        include = f"INCLUDE {this}"
    4737
    4738        column_def = self.sql(expression, "column_def")
    4739        if column_def:
    4740            include = f"{include} {column_def}"
    4741
    4742        alias = self.sql(expression, "alias")
    4743        if alias:
    4744            include = f"{include} AS {alias}"
    4745
    4746        return include
    4747
    4748    def xmlelement_sql(self, expression: exp.XMLElement) -> str:
    4749        name = f"NAME {self.sql(expression, 'this')}"
    4750        return self.func("XMLELEMENT", name, *expression.expressions)
    4751
    4752    def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str:
    4753        partitions = self.expressions(expression, "partition_expressions")
    4754        create = self.expressions(expression, "create_expressions")
    4755        return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}"
    4756
    4757    def partitionbyrangepropertydynamic_sql(
    4758        self, expression: exp.PartitionByRangePropertyDynamic
    4759    ) -> str:
    4760        start = self.sql(expression, "start")
    4761        end = self.sql(expression, "end")
    4762
    4763        every = expression.args["every"]
    4764        if isinstance(every, exp.Interval) and every.this.is_string:
    4765            every.this.replace(exp.Literal.number(every.name))
    4766
    4767        return f"START {self.wrap(start)} END {self.wrap(end)} EVERY {self.wrap(self.sql(every))}"
    4768
    4769    def unpivotcolumns_sql(self, expression: exp.UnpivotColumns) -> str:
    4770        name = self.sql(expression, "this")
    4771        values = self.expressions(expression, flat=True)
    4772
    4773        return f"NAME {name} VALUE {values}"
    4774
    4775    def analyzesample_sql(self, expression: exp.AnalyzeSample) -> str:
    4776        kind = self.sql(expression, "kind")
    4777        sample = self.sql(expression, "sample")
    4778        return f"SAMPLE {sample} {kind}"
    4779
    4780    def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str:
    4781        kind = self.sql(expression, "kind")
    4782        option = self.sql(expression, "option")
    4783        option = f" {option}" if option else ""
    4784        this = self.sql(expression, "this")
    4785        this = f" {this}" if this else ""
    4786        columns = self.expressions(expression)
    4787        columns = f" {columns}" if columns else ""
    4788        return f"{kind}{option} STATISTICS{this}{columns}"
    4789
    4790    def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str:
    4791        this = self.sql(expression, "this")
    4792        columns = self.expressions(expression)
    4793        inner_expression = self.sql(expression, "expression")
    4794        inner_expression = f" {inner_expression}" if inner_expression else ""
    4795        update_options = self.sql(expression, "update_options")
    4796        update_options = f" {update_options} UPDATE" if update_options else ""
    4797        return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}"
    4798
    4799    def analyzedelete_sql(self, expression: exp.AnalyzeDelete) -> str:
    4800        kind = self.sql(expression, "kind")
    4801        kind = f" {kind}" if kind else ""
    4802        return f"DELETE{kind} STATISTICS"
    4803
    4804    def analyzelistchainedrows_sql(self, expression: exp.AnalyzeListChainedRows) -> str:
    4805        inner_expression = self.sql(expression, "expression")
    4806        return f"LIST CHAINED ROWS{inner_expression}"
    4807
    4808    def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str:
    4809        kind = self.sql(expression, "kind")
    4810        this = self.sql(expression, "this")
    4811        this = f" {this}" if this else ""
    4812        inner_expression = self.sql(expression, "expression")
    4813        return f"VALIDATE {kind}{this}{inner_expression}"
    4814
    4815    def analyze_sql(self, expression: exp.Analyze) -> str:
    4816        options = self.expressions(expression, key="options", sep=" ")
    4817        options = f" {options}" if options else ""
    4818        kind = self.sql(expression, "kind")
    4819        kind = f" {kind}" if kind else ""
    4820        this = self.sql(expression, "this")
    4821        this = f" {this}" if this else ""
    4822        mode = self.sql(expression, "mode")
    4823        mode = f" {mode}" if mode else ""
    4824        properties = self.sql(expression, "properties")
    4825        properties = f" {properties}" if properties else ""
    4826        partition = self.sql(expression, "partition")
    4827        partition = f" {partition}" if partition else ""
    4828        inner_expression = self.sql(expression, "expression")
    4829        inner_expression = f" {inner_expression}" if inner_expression else ""
    4830        return f"ANALYZE{options}{kind}{this}{partition}{mode}{inner_expression}{properties}"
    4831
    4832    def xmltable_sql(self, expression: exp.XMLTable) -> str:
    4833        this = self.sql(expression, "this")
    4834        namespaces = self.expressions(expression, key="namespaces")
    4835        namespaces = f"XMLNAMESPACES({namespaces}), " if namespaces else ""
    4836        passing = self.expressions(expression, key="passing")
    4837        passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else ""
    4838        columns = self.expressions(expression, key="columns")
    4839        columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else ""
    4840        by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else ""
    4841        return f"XMLTABLE({self.sep('')}{self.indent(namespaces + this + passing + by_ref + columns)}{self.seg(')', sep='')}"
    4842
    4843    def xmlnamespace_sql(self, expression: exp.XMLNamespace) -> str:
    4844        this = self.sql(expression, "this")
    4845        return this if isinstance(expression.this, exp.Alias) else f"DEFAULT {this}"
    4846
    4847    def export_sql(self, expression: exp.Export) -> str:
    4848        this = self.sql(expression, "this")
    4849        connection = self.sql(expression, "connection")
    4850        connection = f"WITH CONNECTION {connection} " if connection else ""
    4851        options = self.sql(expression, "options")
    4852        return f"EXPORT DATA {connection}{options} AS {this}"
    4853
    4854    def declare_sql(self, expression: exp.Declare) -> str:
    4855        return f"DECLARE {self.expressions(expression, flat=True)}"
    4856
    4857    def declareitem_sql(self, expression: exp.DeclareItem) -> str:
    4858        variable = self.sql(expression, "this")
    4859        default = self.sql(expression, "default")
    4860        default = f" = {default}" if default else ""
    4861
    4862        kind = self.sql(expression, "kind")
    4863        if isinstance(expression.args.get("kind"), exp.Schema):
    4864            kind = f"TABLE {kind}"
    4865
    4866        return f"{variable} AS {kind}{default}"
    4867
    4868    def recursivewithsearch_sql(self, expression: exp.RecursiveWithSearch) -> str:
    4869        kind = self.sql(expression, "kind")
    4870        this = self.sql(expression, "this")
    4871        set = self.sql(expression, "expression")
    4872        using = self.sql(expression, "using")
    4873        using = f" USING {using}" if using else ""
    4874
    4875        kind_sql = kind if kind == "CYCLE" else f"SEARCH {kind} FIRST BY"
    4876
    4877        return f"{kind_sql} {this} SET {set}{using}"
    4878
    4879    def parameterizedagg_sql(self, expression: exp.ParameterizedAgg) -> str:
    4880        params = self.expressions(expression, key="params", flat=True)
    4881        return self.func(expression.name, *expression.expressions) + f"({params})"
    4882
    4883    def anonymousaggfunc_sql(self, expression: exp.AnonymousAggFunc) -> str:
    4884        return self.func(expression.name, *expression.expressions)
    4885
    4886    def combinedaggfunc_sql(self, expression: exp.CombinedAggFunc) -> str:
    4887        return self.anonymousaggfunc_sql(expression)
    4888
    4889    def combinedparameterizedagg_sql(self, expression: exp.CombinedParameterizedAgg) -> str:
    4890        return self.parameterizedagg_sql(expression)
    4891
    4892    def show_sql(self, expression: exp.Show) -> str:
    4893        self.unsupported("Unsupported SHOW statement")
    4894        return ""
    4895
    4896    def put_sql(self, expression: exp.Put) -> str:
    4897        props = expression.args.get("properties")
    4898        props_sql = self.properties(props, prefix=" ", sep=" ", wrapped=False) if props else ""
    4899        this = self.sql(expression, "this")
    4900        target = self.sql(expression, "target")
    4901        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.CredentialsProperty: lambda self,
     137        e: f"CREDENTIALS=({self.expressions(e, 'expressions', sep=' ')})",
     138        exp.DateFormatColumnConstraint: lambda self, e: f"FORMAT {self.sql(e, 'this')}",
     139        exp.DefaultColumnConstraint: lambda self, e: f"DEFAULT {self.sql(e, 'this')}",
     140        exp.DynamicProperty: lambda *_: "DYNAMIC",
     141        exp.EmptyProperty: lambda *_: "EMPTY",
     142        exp.EncodeColumnConstraint: lambda self, e: f"ENCODE {self.sql(e, 'this')}",
     143        exp.EphemeralColumnConstraint: lambda self,
     144        e: f"EPHEMERAL{(' ' + self.sql(e, 'this')) if e.this else ''}",
     145        exp.ExcludeColumnConstraint: lambda self, e: f"EXCLUDE {self.sql(e, 'this').lstrip()}",
     146        exp.ExecuteAsProperty: lambda self, e: self.naked_property(e),
     147        exp.Except: lambda self, e: self.set_operations(e),
     148        exp.ExternalProperty: lambda *_: "EXTERNAL",
     149        exp.Floor: lambda self, e: self.ceil_floor(e),
     150        exp.GlobalProperty: lambda *_: "GLOBAL",
     151        exp.HeapProperty: lambda *_: "HEAP",
     152        exp.IcebergProperty: lambda *_: "ICEBERG",
     153        exp.InheritsProperty: lambda self, e: f"INHERITS ({self.expressions(e, flat=True)})",
     154        exp.InlineLengthColumnConstraint: lambda self, e: f"INLINE LENGTH {self.sql(e, 'this')}",
     155        exp.InputModelProperty: lambda self, e: f"INPUT{self.sql(e, 'this')}",
     156        exp.Intersect: lambda self, e: self.set_operations(e),
     157        exp.IntervalSpan: lambda self, e: f"{self.sql(e, 'this')} TO {self.sql(e, 'expression')}",
     158        exp.Int64: lambda self, e: self.sql(exp.cast(e.this, exp.DataType.Type.BIGINT)),
     159        exp.LanguageProperty: lambda self, e: self.naked_property(e),
     160        exp.LocationProperty: lambda self, e: self.naked_property(e),
     161        exp.LogProperty: lambda _, e: f"{'NO ' if e.args.get('no') else ''}LOG",
     162        exp.MaterializedProperty: lambda *_: "MATERIALIZED",
     163        exp.NonClusteredColumnConstraint: lambda self,
     164        e: f"NONCLUSTERED ({self.expressions(e, 'this', indent=False)})",
     165        exp.NoPrimaryIndexProperty: lambda *_: "NO PRIMARY INDEX",
     166        exp.NotForReplicationColumnConstraint: lambda *_: "NOT FOR REPLICATION",
     167        exp.OnCommitProperty: lambda _,
     168        e: f"ON COMMIT {'DELETE' if e.args.get('delete') else 'PRESERVE'} ROWS",
     169        exp.OnProperty: lambda self, e: f"ON {self.sql(e, 'this')}",
     170        exp.OnUpdateColumnConstraint: lambda self, e: f"ON UPDATE {self.sql(e, 'this')}",
     171        exp.Operator: lambda self, e: self.binary(e, ""),  # The operator is produced in `binary`
     172        exp.OutputModelProperty: lambda self, e: f"OUTPUT{self.sql(e, 'this')}",
     173        exp.PathColumnConstraint: lambda self, e: f"PATH {self.sql(e, 'this')}",
     174        exp.PivotAny: lambda self, e: f"ANY{self.sql(e, 'this')}",
     175        exp.ProjectionPolicyColumnConstraint: lambda self,
     176        e: f"PROJECTION POLICY {self.sql(e, 'this')}",
     177        exp.RemoteWithConnectionModelProperty: lambda self,
     178        e: f"REMOTE WITH CONNECTION {self.sql(e, 'this')}",
     179        exp.ReturnsProperty: lambda self, e: (
     180            "RETURNS NULL ON NULL INPUT" if e.args.get("null") else self.naked_property(e)
     181        ),
     182        exp.SampleProperty: lambda self, e: f"SAMPLE BY {self.sql(e, 'this')}",
     183        exp.SecureProperty: lambda *_: "SECURE",
     184        exp.SecurityProperty: lambda self, e: f"SECURITY {self.sql(e, 'this')}",
     185        exp.SetConfigProperty: lambda self, e: self.sql(e, "this"),
     186        exp.SetProperty: lambda _, e: f"{'MULTI' if e.args.get('multi') else ''}SET",
     187        exp.SettingsProperty: lambda self, e: f"SETTINGS{self.seg('')}{(self.expressions(e))}",
     188        exp.SharingProperty: lambda self, e: f"SHARING={self.sql(e, 'this')}",
     189        exp.SqlReadWriteProperty: lambda _, e: e.name,
     190        exp.SqlSecurityProperty: lambda _,
     191        e: f"SQL SECURITY {'DEFINER' if e.args.get('definer') else 'INVOKER'}",
     192        exp.StabilityProperty: lambda _, e: e.name,
     193        exp.Stream: lambda self, e: f"STREAM {self.sql(e, 'this')}",
     194        exp.StreamingTableProperty: lambda *_: "STREAMING",
     195        exp.StrictProperty: lambda *_: "STRICT",
     196        exp.SwapTable: lambda self, e: f"SWAP WITH {self.sql(e, 'this')}",
     197        exp.Tags: lambda self, e: f"TAG ({self.expressions(e, flat=True)})",
     198        exp.TemporaryProperty: lambda *_: "TEMPORARY",
     199        exp.TitleColumnConstraint: lambda self, e: f"TITLE {self.sql(e, 'this')}",
     200        exp.ToMap: lambda self, e: f"MAP {self.sql(e, 'this')}",
     201        exp.ToTableProperty: lambda self, e: f"TO {self.sql(e.this)}",
     202        exp.TransformModelProperty: lambda self, e: self.func("TRANSFORM", *e.expressions),
     203        exp.TransientProperty: lambda *_: "TRANSIENT",
     204        exp.Union: lambda self, e: self.set_operations(e),
     205        exp.UnloggedProperty: lambda *_: "UNLOGGED",
     206        exp.UsingTemplateProperty: lambda self, e: f"USING TEMPLATE {self.sql(e, 'this')}",
     207        exp.UsingData: lambda self, e: f"USING DATA {self.sql(e, 'this')}",
     208        exp.Uuid: lambda *_: "UUID()",
     209        exp.UppercaseColumnConstraint: lambda *_: "UPPERCASE",
     210        exp.VarMap: lambda self, e: self.func("MAP", e.args["keys"], e.args["values"]),
     211        exp.ViewAttributeProperty: lambda self, e: f"WITH {self.sql(e, 'this')}",
     212        exp.VolatileProperty: lambda *_: "VOLATILE",
     213        exp.WithJournalTableProperty: lambda self, e: f"WITH JOURNAL TABLE={self.sql(e, 'this')}",
     214        exp.WithProcedureOptions: lambda self, e: f"WITH {self.expressions(e, flat=True)}",
     215        exp.WithSchemaBindingProperty: lambda self, e: f"WITH SCHEMA {self.sql(e, 'this')}",
     216        exp.WithOperator: lambda self, e: f"{self.sql(e, 'this')} WITH {self.sql(e, 'op')}",
     217        exp.ForceProperty: lambda *_: "FORCE",
     218    }
     219
     220    # Whether null ordering is supported in order by
     221    # True: Full Support, None: No support, False: No support for certain cases
     222    # such as window specifications, aggregate functions etc
     223    NULL_ORDERING_SUPPORTED: t.Optional[bool] = True
     224
     225    # Whether ignore nulls is inside the agg or outside.
     226    # FIRST(x IGNORE NULLS) OVER vs FIRST (x) IGNORE NULLS OVER
     227    IGNORE_NULLS_IN_FUNC = False
     228
     229    # Whether locking reads (i.e. SELECT ... FOR UPDATE/SHARE) are supported
     230    LOCKING_READS_SUPPORTED = False
     231
     232    # Whether the EXCEPT and INTERSECT operations can return duplicates
     233    EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = True
     234
     235    # Wrap derived values in parens, usually standard but spark doesn't support it
     236    WRAP_DERIVED_VALUES = True
     237
     238    # Whether create function uses an AS before the RETURN
     239    CREATE_FUNCTION_RETURN_AS = True
     240
     241    # Whether MERGE ... WHEN MATCHED BY SOURCE is allowed
     242    MATCHED_BY_SOURCE = True
     243
     244    # Whether the INTERVAL expression works only with values like '1 day'
     245    SINGLE_STRING_INTERVAL = False
     246
     247    # Whether the plural form of date parts like day (i.e. "days") is supported in INTERVALs
     248    INTERVAL_ALLOWS_PLURAL_FORM = True
     249
     250    # Whether limit and fetch are supported (possible values: "ALL", "LIMIT", "FETCH")
     251    LIMIT_FETCH = "ALL"
     252
     253    # Whether limit and fetch allows expresions or just limits
     254    LIMIT_ONLY_LITERALS = False
     255
     256    # Whether a table is allowed to be renamed with a db
     257    RENAME_TABLE_WITH_DB = True
     258
     259    # The separator for grouping sets and rollups
     260    GROUPINGS_SEP = ","
     261
     262    # The string used for creating an index on a table
     263    INDEX_ON = "ON"
     264
     265    # Whether join hints should be generated
     266    JOIN_HINTS = True
     267
     268    # Whether table hints should be generated
     269    TABLE_HINTS = True
     270
     271    # Whether query hints should be generated
     272    QUERY_HINTS = True
     273
     274    # What kind of separator to use for query hints
     275    QUERY_HINT_SEP = ", "
     276
     277    # Whether comparing against booleans (e.g. x IS TRUE) is supported
     278    IS_BOOL_ALLOWED = True
     279
     280    # Whether to include the "SET" keyword in the "INSERT ... ON DUPLICATE KEY UPDATE" statement
     281    DUPLICATE_KEY_UPDATE_WITH_SET = True
     282
     283    # Whether to generate the limit as TOP <value> instead of LIMIT <value>
     284    LIMIT_IS_TOP = False
     285
     286    # Whether to generate INSERT INTO ... RETURNING or INSERT INTO RETURNING ...
     287    RETURNING_END = True
     288
     289    # Whether to generate an unquoted value for EXTRACT's date part argument
     290    EXTRACT_ALLOWS_QUOTES = True
     291
     292    # Whether TIMETZ / TIMESTAMPTZ will be generated using the "WITH TIME ZONE" syntax
     293    TZ_TO_WITH_TIME_ZONE = False
     294
     295    # Whether the NVL2 function is supported
     296    NVL2_SUPPORTED = True
     297
     298    # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax
     299    SELECT_KINDS: t.Tuple[str, ...] = ("STRUCT", "VALUE")
     300
     301    # Whether VALUES statements can be used as derived tables.
     302    # MySQL 5 and Redshift do not allow this, so when False, it will convert
     303    # SELECT * VALUES into SELECT UNION
     304    VALUES_AS_TABLE = True
     305
     306    # Whether the word COLUMN is included when adding a column with ALTER TABLE
     307    ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = True
     308
     309    # UNNEST WITH ORDINALITY (presto) instead of UNNEST WITH OFFSET (bigquery)
     310    UNNEST_WITH_ORDINALITY = True
     311
     312    # Whether FILTER (WHERE cond) can be used for conditional aggregation
     313    AGGREGATE_FILTER_SUPPORTED = True
     314
     315    # Whether JOIN sides (LEFT, RIGHT) are supported in conjunction with SEMI/ANTI join kinds
     316    SEMI_ANTI_JOIN_WITH_SIDE = True
     317
     318    # Whether to include the type of a computed column in the CREATE DDL
     319    COMPUTED_COLUMN_WITH_TYPE = True
     320
     321    # Whether CREATE TABLE .. COPY .. is supported. False means we'll generate CLONE instead of COPY
     322    SUPPORTS_TABLE_COPY = True
     323
     324    # Whether parentheses are required around the table sample's expression
     325    TABLESAMPLE_REQUIRES_PARENS = True
     326
     327    # Whether a table sample clause's size needs to be followed by the ROWS keyword
     328    TABLESAMPLE_SIZE_IS_ROWS = True
     329
     330    # The keyword(s) to use when generating a sample clause
     331    TABLESAMPLE_KEYWORDS = "TABLESAMPLE"
     332
     333    # Whether the TABLESAMPLE clause supports a method name, like BERNOULLI
     334    TABLESAMPLE_WITH_METHOD = True
     335
     336    # The keyword to use when specifying the seed of a sample clause
     337    TABLESAMPLE_SEED_KEYWORD = "SEED"
     338
     339    # Whether COLLATE is a function instead of a binary operator
     340    COLLATE_IS_FUNC = False
     341
     342    # Whether data types support additional specifiers like e.g. CHAR or BYTE (oracle)
     343    DATA_TYPE_SPECIFIERS_ALLOWED = False
     344
     345    # Whether conditions require booleans WHERE x = 0 vs WHERE x
     346    ENSURE_BOOLS = False
     347
     348    # Whether the "RECURSIVE" keyword is required when defining recursive CTEs
     349    CTE_RECURSIVE_KEYWORD_REQUIRED = True
     350
     351    # Whether CONCAT requires >1 arguments
     352    SUPPORTS_SINGLE_ARG_CONCAT = True
     353
     354    # Whether LAST_DAY function supports a date part argument
     355    LAST_DAY_SUPPORTS_DATE_PART = True
     356
     357    # Whether named columns are allowed in table aliases
     358    SUPPORTS_TABLE_ALIAS_COLUMNS = True
     359
     360    # Whether UNPIVOT aliases are Identifiers (False means they're Literals)
     361    UNPIVOT_ALIASES_ARE_IDENTIFIERS = True
     362
     363    # What delimiter to use for separating JSON key/value pairs
     364    JSON_KEY_VALUE_PAIR_SEP = ":"
     365
     366    # INSERT OVERWRITE TABLE x override
     367    INSERT_OVERWRITE = " OVERWRITE TABLE"
     368
     369    # Whether the SELECT .. INTO syntax is used instead of CTAS
     370    SUPPORTS_SELECT_INTO = False
     371
     372    # Whether UNLOGGED tables can be created
     373    SUPPORTS_UNLOGGED_TABLES = False
     374
     375    # Whether the CREATE TABLE LIKE statement is supported
     376    SUPPORTS_CREATE_TABLE_LIKE = True
     377
     378    # Whether the LikeProperty needs to be specified inside of the schema clause
     379    LIKE_PROPERTY_INSIDE_SCHEMA = False
     380
     381    # Whether DISTINCT can be followed by multiple args in an AggFunc. If not, it will be
     382    # transpiled into a series of CASE-WHEN-ELSE, ultimately using a tuple conseisting of the args
     383    MULTI_ARG_DISTINCT = True
     384
     385    # Whether the JSON extraction operators expect a value of type JSON
     386    JSON_TYPE_REQUIRED_FOR_EXTRACTION = False
     387
     388    # Whether bracketed keys like ["foo"] are supported in JSON paths
     389    JSON_PATH_BRACKETED_KEY_SUPPORTED = True
     390
     391    # Whether to escape keys using single quotes in JSON paths
     392    JSON_PATH_SINGLE_QUOTE_ESCAPE = False
     393
     394    # The JSONPathPart expressions supported by this dialect
     395    SUPPORTED_JSON_PATH_PARTS = ALL_JSON_PATH_PARTS.copy()
     396
     397    # Whether any(f(x) for x in array) can be implemented by this dialect
     398    CAN_IMPLEMENT_ARRAY_ANY = False
     399
     400    # Whether the function TO_NUMBER is supported
     401    SUPPORTS_TO_NUMBER = True
     402
     403    # Whether or not set op modifiers apply to the outer set op or select.
     404    # SELECT * FROM x UNION SELECT * FROM y LIMIT 1
     405    # True means limit 1 happens after the set op, False means it it happens on y.
     406    SET_OP_MODIFIERS = True
     407
     408    # Whether parameters from COPY statement are wrapped in parentheses
     409    COPY_PARAMS_ARE_WRAPPED = True
     410
     411    # Whether values of params are set with "=" token or empty space
     412    COPY_PARAMS_EQ_REQUIRED = False
     413
     414    # Whether COPY statement has INTO keyword
     415    COPY_HAS_INTO_KEYWORD = True
     416
     417    # Whether the conditional TRY(expression) function is supported
     418    TRY_SUPPORTED = True
     419
     420    # Whether the UESCAPE syntax in unicode strings is supported
     421    SUPPORTS_UESCAPE = True
     422
     423    # The keyword to use when generating a star projection with excluded columns
     424    STAR_EXCEPT = "EXCEPT"
     425
     426    # The HEX function name
     427    HEX_FUNC = "HEX"
     428
     429    # The keywords to use when prefixing & separating WITH based properties
     430    WITH_PROPERTIES_PREFIX = "WITH"
     431
     432    # Whether to quote the generated expression of exp.JsonPath
     433    QUOTE_JSON_PATH = True
     434
     435    # Whether the text pattern/fill (3rd) parameter of RPAD()/LPAD() is optional (defaults to space)
     436    PAD_FILL_PATTERN_IS_REQUIRED = False
     437
     438    # Whether a projection can explode into multiple rows, e.g. by unnesting an array.
     439    SUPPORTS_EXPLODING_PROJECTIONS = True
     440
     441    # Whether ARRAY_CONCAT can be generated with varlen args or if it should be reduced to 2-arg version
     442    ARRAY_CONCAT_IS_VAR_LEN = True
     443
     444    # Whether CONVERT_TIMEZONE() is supported; if not, it will be generated as exp.AtTimeZone
     445    SUPPORTS_CONVERT_TIMEZONE = False
     446
     447    # Whether MEDIAN(expr) is supported; if not, it will be generated as PERCENTILE_CONT(expr, 0.5)
     448    SUPPORTS_MEDIAN = True
     449
     450    # Whether UNIX_SECONDS(timestamp) is supported
     451    SUPPORTS_UNIX_SECONDS = False
     452
     453    # The name to generate for the JSONPath expression. If `None`, only `this` will be generated
     454    PARSE_JSON_NAME: t.Optional[str] = "PARSE_JSON"
     455
     456    # The function name of the exp.ArraySize expression
     457    ARRAY_SIZE_NAME: str = "ARRAY_LENGTH"
     458
     459    # The syntax to use when altering the type of a column
     460    ALTER_SET_TYPE = "SET DATA TYPE"
     461
     462    # Whether exp.ArraySize should generate the dimension arg too (valid for Postgres & DuckDB)
     463    # None -> Doesn't support it at all
     464    # False (DuckDB) -> Has backwards-compatible support, but preferably generated without
     465    # True (Postgres) -> Explicitly requires it
     466    ARRAY_SIZE_DIM_REQUIRED: t.Optional[bool] = None
     467
     468    TYPE_MAPPING = {
     469        exp.DataType.Type.DATETIME2: "TIMESTAMP",
     470        exp.DataType.Type.NCHAR: "CHAR",
     471        exp.DataType.Type.NVARCHAR: "VARCHAR",
     472        exp.DataType.Type.MEDIUMTEXT: "TEXT",
     473        exp.DataType.Type.LONGTEXT: "TEXT",
     474        exp.DataType.Type.TINYTEXT: "TEXT",
     475        exp.DataType.Type.BLOB: "VARBINARY",
     476        exp.DataType.Type.MEDIUMBLOB: "BLOB",
     477        exp.DataType.Type.LONGBLOB: "BLOB",
     478        exp.DataType.Type.TINYBLOB: "BLOB",
     479        exp.DataType.Type.INET: "INET",
     480        exp.DataType.Type.ROWVERSION: "VARBINARY",
     481        exp.DataType.Type.SMALLDATETIME: "TIMESTAMP",
     482    }
     483
     484    TIME_PART_SINGULARS = {
     485        "MICROSECONDS": "MICROSECOND",
     486        "SECONDS": "SECOND",
     487        "MINUTES": "MINUTE",
     488        "HOURS": "HOUR",
     489        "DAYS": "DAY",
     490        "WEEKS": "WEEK",
     491        "MONTHS": "MONTH",
     492        "QUARTERS": "QUARTER",
     493        "YEARS": "YEAR",
     494    }
     495
     496    AFTER_HAVING_MODIFIER_TRANSFORMS = {
     497        "cluster": lambda self, e: self.sql(e, "cluster"),
     498        "distribute": lambda self, e: self.sql(e, "distribute"),
     499        "sort": lambda self, e: self.sql(e, "sort"),
     500        "windows": lambda self, e: (
     501            self.seg("WINDOW ") + self.expressions(e, key="windows", flat=True)
     502            if e.args.get("windows")
     503            else ""
     504        ),
     505        "qualify": lambda self, e: self.sql(e, "qualify"),
     506    }
     507
     508    TOKEN_MAPPING: t.Dict[TokenType, str] = {}
     509
     510    STRUCT_DELIMITER = ("<", ">")
     511
     512    PARAMETER_TOKEN = "@"
     513    NAMED_PLACEHOLDER_TOKEN = ":"
     514
     515    EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: t.Set[str] = set()
     516
     517    PROPERTIES_LOCATION = {
     518        exp.AllowedValuesProperty: exp.Properties.Location.POST_SCHEMA,
     519        exp.AlgorithmProperty: exp.Properties.Location.POST_CREATE,
     520        exp.AutoIncrementProperty: exp.Properties.Location.POST_SCHEMA,
     521        exp.AutoRefreshProperty: exp.Properties.Location.POST_SCHEMA,
     522        exp.BackupProperty: exp.Properties.Location.POST_SCHEMA,
     523        exp.BlockCompressionProperty: exp.Properties.Location.POST_NAME,
     524        exp.CharacterSetProperty: exp.Properties.Location.POST_SCHEMA,
     525        exp.ChecksumProperty: exp.Properties.Location.POST_NAME,
     526        exp.CollateProperty: exp.Properties.Location.POST_SCHEMA,
     527        exp.CopyGrantsProperty: exp.Properties.Location.POST_SCHEMA,
     528        exp.Cluster: exp.Properties.Location.POST_SCHEMA,
     529        exp.ClusteredByProperty: exp.Properties.Location.POST_SCHEMA,
     530        exp.DistributedByProperty: exp.Properties.Location.POST_SCHEMA,
     531        exp.DuplicateKeyProperty: exp.Properties.Location.POST_SCHEMA,
     532        exp.DataBlocksizeProperty: exp.Properties.Location.POST_NAME,
     533        exp.DataDeletionProperty: exp.Properties.Location.POST_SCHEMA,
     534        exp.DefinerProperty: exp.Properties.Location.POST_CREATE,
     535        exp.DictRange: exp.Properties.Location.POST_SCHEMA,
     536        exp.DictProperty: exp.Properties.Location.POST_SCHEMA,
     537        exp.DynamicProperty: exp.Properties.Location.POST_CREATE,
     538        exp.DistKeyProperty: exp.Properties.Location.POST_SCHEMA,
     539        exp.DistStyleProperty: exp.Properties.Location.POST_SCHEMA,
     540        exp.EmptyProperty: exp.Properties.Location.POST_SCHEMA,
     541        exp.EncodeProperty: exp.Properties.Location.POST_EXPRESSION,
     542        exp.EngineProperty: exp.Properties.Location.POST_SCHEMA,
     543        exp.ExecuteAsProperty: exp.Properties.Location.POST_SCHEMA,
     544        exp.ExternalProperty: exp.Properties.Location.POST_CREATE,
     545        exp.FallbackProperty: exp.Properties.Location.POST_NAME,
     546        exp.FileFormatProperty: exp.Properties.Location.POST_WITH,
     547        exp.FreespaceProperty: exp.Properties.Location.POST_NAME,
     548        exp.GlobalProperty: exp.Properties.Location.POST_CREATE,
     549        exp.HeapProperty: exp.Properties.Location.POST_WITH,
     550        exp.InheritsProperty: exp.Properties.Location.POST_SCHEMA,
     551        exp.IcebergProperty: exp.Properties.Location.POST_CREATE,
     552        exp.IncludeProperty: exp.Properties.Location.POST_SCHEMA,
     553        exp.InputModelProperty: exp.Properties.Location.POST_SCHEMA,
     554        exp.IsolatedLoadingProperty: exp.Properties.Location.POST_NAME,
     555        exp.JournalProperty: exp.Properties.Location.POST_NAME,
     556        exp.LanguageProperty: exp.Properties.Location.POST_SCHEMA,
     557        exp.LikeProperty: exp.Properties.Location.POST_SCHEMA,
     558        exp.LocationProperty: exp.Properties.Location.POST_SCHEMA,
     559        exp.LockProperty: exp.Properties.Location.POST_SCHEMA,
     560        exp.LockingProperty: exp.Properties.Location.POST_ALIAS,
     561        exp.LogProperty: exp.Properties.Location.POST_NAME,
     562        exp.MaterializedProperty: exp.Properties.Location.POST_CREATE,
     563        exp.MergeBlockRatioProperty: exp.Properties.Location.POST_NAME,
     564        exp.NoPrimaryIndexProperty: exp.Properties.Location.POST_EXPRESSION,
     565        exp.OnProperty: exp.Properties.Location.POST_SCHEMA,
     566        exp.OnCommitProperty: exp.Properties.Location.POST_EXPRESSION,
     567        exp.Order: exp.Properties.Location.POST_SCHEMA,
     568        exp.OutputModelProperty: exp.Properties.Location.POST_SCHEMA,
     569        exp.PartitionedByProperty: exp.Properties.Location.POST_WITH,
     570        exp.PartitionedOfProperty: exp.Properties.Location.POST_SCHEMA,
     571        exp.PrimaryKey: exp.Properties.Location.POST_SCHEMA,
     572        exp.Property: exp.Properties.Location.POST_WITH,
     573        exp.RemoteWithConnectionModelProperty: exp.Properties.Location.POST_SCHEMA,
     574        exp.ReturnsProperty: exp.Properties.Location.POST_SCHEMA,
     575        exp.RowFormatProperty: exp.Properties.Location.POST_SCHEMA,
     576        exp.RowFormatDelimitedProperty: exp.Properties.Location.POST_SCHEMA,
     577        exp.RowFormatSerdeProperty: exp.Properties.Location.POST_SCHEMA,
     578        exp.SampleProperty: exp.Properties.Location.POST_SCHEMA,
     579        exp.SchemaCommentProperty: exp.Properties.Location.POST_SCHEMA,
     580        exp.SecureProperty: exp.Properties.Location.POST_CREATE,
     581        exp.SecurityProperty: exp.Properties.Location.POST_SCHEMA,
     582        exp.SerdeProperties: exp.Properties.Location.POST_SCHEMA,
     583        exp.Set: exp.Properties.Location.POST_SCHEMA,
     584        exp.SettingsProperty: exp.Properties.Location.POST_SCHEMA,
     585        exp.SetProperty: exp.Properties.Location.POST_CREATE,
     586        exp.SetConfigProperty: exp.Properties.Location.POST_SCHEMA,
     587        exp.SharingProperty: exp.Properties.Location.POST_EXPRESSION,
     588        exp.SequenceProperties: exp.Properties.Location.POST_EXPRESSION,
     589        exp.SortKeyProperty: exp.Properties.Location.POST_SCHEMA,
     590        exp.SqlReadWriteProperty: exp.Properties.Location.POST_SCHEMA,
     591        exp.SqlSecurityProperty: exp.Properties.Location.POST_CREATE,
     592        exp.StabilityProperty: exp.Properties.Location.POST_SCHEMA,
     593        exp.StorageHandlerProperty: exp.Properties.Location.POST_SCHEMA,
     594        exp.StreamingTableProperty: exp.Properties.Location.POST_CREATE,
     595        exp.StrictProperty: exp.Properties.Location.POST_SCHEMA,
     596        exp.Tags: exp.Properties.Location.POST_WITH,
     597        exp.TemporaryProperty: exp.Properties.Location.POST_CREATE,
     598        exp.ToTableProperty: exp.Properties.Location.POST_SCHEMA,
     599        exp.TransientProperty: exp.Properties.Location.POST_CREATE,
     600        exp.TransformModelProperty: exp.Properties.Location.POST_SCHEMA,
     601        exp.MergeTreeTTL: exp.Properties.Location.POST_SCHEMA,
     602        exp.UnloggedProperty: exp.Properties.Location.POST_CREATE,
     603        exp.UsingTemplateProperty: exp.Properties.Location.POST_SCHEMA,
     604        exp.ViewAttributeProperty: exp.Properties.Location.POST_SCHEMA,
     605        exp.VolatileProperty: exp.Properties.Location.POST_CREATE,
     606        exp.WithDataProperty: exp.Properties.Location.POST_EXPRESSION,
     607        exp.WithJournalTableProperty: exp.Properties.Location.POST_NAME,
     608        exp.WithProcedureOptions: exp.Properties.Location.POST_SCHEMA,
     609        exp.WithSchemaBindingProperty: exp.Properties.Location.POST_SCHEMA,
     610        exp.WithSystemVersioningProperty: exp.Properties.Location.POST_SCHEMA,
     611        exp.ForceProperty: exp.Properties.Location.POST_CREATE,
     612    }
     613
     614    # Keywords that can't be used as unquoted identifier names
     615    RESERVED_KEYWORDS: t.Set[str] = set()
     616
     617    # Expressions whose comments are separated from them for better formatting
     618    WITH_SEPARATED_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = (
     619        exp.Command,
     620        exp.Create,
     621        exp.Describe,
     622        exp.Delete,
     623        exp.Drop,
     624        exp.From,
     625        exp.Insert,
     626        exp.Join,
     627        exp.MultitableInserts,
     628        exp.Select,
     629        exp.SetOperation,
     630        exp.Update,
     631        exp.Where,
     632        exp.With,
     633    )
     634
     635    # Expressions that should not have their comments generated in maybe_comment
     636    EXCLUDE_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = (
     637        exp.Binary,
     638        exp.SetOperation,
     639    )
     640
     641    # Expressions that can remain unwrapped when appearing in the context of an INTERVAL
     642    UNWRAPPED_INTERVAL_VALUES: t.Tuple[t.Type[exp.Expression], ...] = (
     643        exp.Column,
     644        exp.Literal,
     645        exp.Neg,
     646        exp.Paren,
     647    )
     648
     649    PARAMETERIZABLE_TEXT_TYPES = {
     650        exp.DataType.Type.NVARCHAR,
     651        exp.DataType.Type.VARCHAR,
     652        exp.DataType.Type.CHAR,
     653        exp.DataType.Type.NCHAR,
     654    }
     655
     656    # Expressions that need to have all CTEs under them bubbled up to them
     657    EXPRESSIONS_WITHOUT_NESTED_CTES: t.Set[t.Type[exp.Expression]] = set()
     658
     659    SENTINEL_LINE_BREAK = "__SQLGLOT__LB__"
     660
     661    __slots__ = (
     662        "pretty",
     663        "identify",
     664        "normalize",
     665        "pad",
     666        "_indent",
     667        "normalize_functions",
     668        "unsupported_level",
     669        "max_unsupported",
     670        "leading_comma",
     671        "max_text_width",
     672        "comments",
     673        "dialect",
     674        "unsupported_messages",
     675        "_escaped_quote_end",
     676        "_escaped_identifier_end",
     677        "_next_name",
     678        "_identifier_start",
     679        "_identifier_end",
     680        "_quote_json_path_key_using_brackets",
     681    )
     682
     683    def __init__(
     684        self,
     685        pretty: t.Optional[bool] = None,
     686        identify: str | bool = False,
     687        normalize: bool = False,
     688        pad: int = 2,
     689        indent: int = 2,
     690        normalize_functions: t.Optional[str | bool] = None,
     691        unsupported_level: ErrorLevel = ErrorLevel.WARN,
     692        max_unsupported: int = 3,
     693        leading_comma: bool = False,
     694        max_text_width: int = 80,
     695        comments: bool = True,
     696        dialect: DialectType = None,
     697    ):
     698        import sqlglot
     699        from sqlglot.dialects import Dialect
     700
     701        self.pretty = pretty if pretty is not None else sqlglot.pretty
     702        self.identify = identify
     703        self.normalize = normalize
     704        self.pad = pad
     705        self._indent = indent
     706        self.unsupported_level = unsupported_level
     707        self.max_unsupported = max_unsupported
     708        self.leading_comma = leading_comma
     709        self.max_text_width = max_text_width
     710        self.comments = comments
     711        self.dialect = Dialect.get_or_raise(dialect)
     712
     713        # This is both a Dialect property and a Generator argument, so we prioritize the latter
     714        self.normalize_functions = (
     715            self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions
     716        )
     717
     718        self.unsupported_messages: t.List[str] = []
     719        self._escaped_quote_end: str = (
     720            self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END
     721        )
     722        self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2
     723
     724        self._next_name = name_sequence("_t")
     725
     726        self._identifier_start = self.dialect.IDENTIFIER_START
     727        self._identifier_end = self.dialect.IDENTIFIER_END
     728
     729        self._quote_json_path_key_using_brackets = True
     730
     731    def generate(self, expression: exp.Expression, copy: bool = True) -> str:
     732        """
     733        Generates the SQL string corresponding to the given syntax tree.
     734
     735        Args:
     736            expression: The syntax tree.
     737            copy: Whether to copy the expression. The generator performs mutations so
     738                it is safer to copy.
     739
     740        Returns:
     741            The SQL string corresponding to `expression`.
     742        """
     743        if copy:
     744            expression = expression.copy()
     745
     746        expression = self.preprocess(expression)
     747
     748        self.unsupported_messages = []
     749        sql = self.sql(expression).strip()
     750
     751        if self.pretty:
     752            sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n")
     753
     754        if self.unsupported_level == ErrorLevel.IGNORE:
     755            return sql
     756
     757        if self.unsupported_level == ErrorLevel.WARN:
     758            for msg in self.unsupported_messages:
     759                logger.warning(msg)
     760        elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages:
     761            raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported))
     762
     763        return sql
     764
     765    def preprocess(self, expression: exp.Expression) -> exp.Expression:
     766        """Apply generic preprocessing transformations to a given expression."""
     767        expression = self._move_ctes_to_top_level(expression)
     768
     769        if self.ENSURE_BOOLS:
     770            from sqlglot.transforms import ensure_bools
     771
     772            expression = ensure_bools(expression)
     773
     774        return expression
     775
     776    def _move_ctes_to_top_level(self, expression: E) -> E:
     777        if (
     778            not expression.parent
     779            and type(expression) in self.EXPRESSIONS_WITHOUT_NESTED_CTES
     780            and any(node.parent is not expression for node in expression.find_all(exp.With))
     781        ):
     782            from sqlglot.transforms import move_ctes_to_top_level
     783
     784            expression = move_ctes_to_top_level(expression)
     785        return expression
     786
     787    def unsupported(self, message: str) -> None:
     788        if self.unsupported_level == ErrorLevel.IMMEDIATE:
     789            raise UnsupportedError(message)
     790        self.unsupported_messages.append(message)
     791
     792    def sep(self, sep: str = " ") -> str:
     793        return f"{sep.strip()}\n" if self.pretty else sep
     794
     795    def seg(self, sql: str, sep: str = " ") -> str:
     796        return f"{self.sep(sep)}{sql}"
     797
     798    def pad_comment(self, comment: str) -> str:
     799        comment = " " + comment if comment[0].strip() else comment
     800        comment = comment + " " if comment[-1].strip() else comment
     801        return comment
     802
     803    def maybe_comment(
     804        self,
     805        sql: str,
     806        expression: t.Optional[exp.Expression] = None,
     807        comments: t.Optional[t.List[str]] = None,
     808        separated: bool = False,
     809    ) -> str:
     810        comments = (
     811            ((expression and expression.comments) if comments is None else comments)  # type: ignore
     812            if self.comments
     813            else None
     814        )
     815
     816        if not comments or isinstance(expression, self.EXCLUDE_COMMENTS):
     817            return sql
     818
     819        comments_sql = " ".join(
     820            f"/*{self.pad_comment(comment)}*/" for comment in comments if comment
     821        )
     822
     823        if not comments_sql:
     824            return sql
     825
     826        comments_sql = self._replace_line_breaks(comments_sql)
     827
     828        if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS):
     829            return (
     830                f"{self.sep()}{comments_sql}{sql}"
     831                if not sql or sql[0].isspace()
     832                else f"{comments_sql}{self.sep()}{sql}"
     833            )
     834
     835        return f"{sql} {comments_sql}"
     836
     837    def wrap(self, expression: exp.Expression | str) -> str:
     838        this_sql = (
     839            self.sql(expression)
     840            if isinstance(expression, exp.UNWRAPPED_QUERIES)
     841            else self.sql(expression, "this")
     842        )
     843        if not this_sql:
     844            return "()"
     845
     846        this_sql = self.indent(this_sql, level=1, pad=0)
     847        return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"
     848
     849    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
     850        original = self.identify
     851        self.identify = False
     852        result = func(*args, **kwargs)
     853        self.identify = original
     854        return result
     855
     856    def normalize_func(self, name: str) -> str:
     857        if self.normalize_functions == "upper" or self.normalize_functions is True:
     858            return name.upper()
     859        if self.normalize_functions == "lower":
     860            return name.lower()
     861        return name
     862
     863    def indent(
     864        self,
     865        sql: str,
     866        level: int = 0,
     867        pad: t.Optional[int] = None,
     868        skip_first: bool = False,
     869        skip_last: bool = False,
     870    ) -> str:
     871        if not self.pretty or not sql:
     872            return sql
     873
     874        pad = self.pad if pad is None else pad
     875        lines = sql.split("\n")
     876
     877        return "\n".join(
     878            (
     879                line
     880                if (skip_first and i == 0) or (skip_last and i == len(lines) - 1)
     881                else f"{' ' * (level * self._indent + pad)}{line}"
     882            )
     883            for i, line in enumerate(lines)
     884        )
     885
     886    def sql(
     887        self,
     888        expression: t.Optional[str | exp.Expression],
     889        key: t.Optional[str] = None,
     890        comment: bool = True,
     891    ) -> str:
     892        if not expression:
     893            return ""
     894
     895        if isinstance(expression, str):
     896            return expression
     897
     898        if key:
     899            value = expression.args.get(key)
     900            if value:
     901                return self.sql(value)
     902            return ""
     903
     904        transform = self.TRANSFORMS.get(expression.__class__)
     905
     906        if callable(transform):
     907            sql = transform(self, expression)
     908        elif isinstance(expression, exp.Expression):
     909            exp_handler_name = f"{expression.key}_sql"
     910
     911            if hasattr(self, exp_handler_name):
     912                sql = getattr(self, exp_handler_name)(expression)
     913            elif isinstance(expression, exp.Func):
     914                sql = self.function_fallback_sql(expression)
     915            elif isinstance(expression, exp.Property):
     916                sql = self.property_sql(expression)
     917            else:
     918                raise ValueError(f"Unsupported expression type {expression.__class__.__name__}")
     919        else:
     920            raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}")
     921
     922        return self.maybe_comment(sql, expression) if self.comments and comment else sql
     923
     924    def uncache_sql(self, expression: exp.Uncache) -> str:
     925        table = self.sql(expression, "this")
     926        exists_sql = " IF EXISTS" if expression.args.get("exists") else ""
     927        return f"UNCACHE TABLE{exists_sql} {table}"
     928
     929    def cache_sql(self, expression: exp.Cache) -> str:
     930        lazy = " LAZY" if expression.args.get("lazy") else ""
     931        table = self.sql(expression, "this")
     932        options = expression.args.get("options")
     933        options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else ""
     934        sql = self.sql(expression, "expression")
     935        sql = f" AS{self.sep()}{sql}" if sql else ""
     936        sql = f"CACHE{lazy} TABLE {table}{options}{sql}"
     937        return self.prepend_ctes(expression, sql)
     938
     939    def characterset_sql(self, expression: exp.CharacterSet) -> str:
     940        if isinstance(expression.parent, exp.Cast):
     941            return f"CHAR CHARACTER SET {self.sql(expression, 'this')}"
     942        default = "DEFAULT " if expression.args.get("default") else ""
     943        return f"{default}CHARACTER SET={self.sql(expression, 'this')}"
     944
     945    def column_parts(self, expression: exp.Column) -> str:
     946        return ".".join(
     947            self.sql(part)
     948            for part in (
     949                expression.args.get("catalog"),
     950                expression.args.get("db"),
     951                expression.args.get("table"),
     952                expression.args.get("this"),
     953            )
     954            if part
     955        )
     956
     957    def column_sql(self, expression: exp.Column) -> str:
     958        join_mark = " (+)" if expression.args.get("join_mark") else ""
     959
     960        if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS:
     961            join_mark = ""
     962            self.unsupported("Outer join syntax using the (+) operator is not supported.")
     963
     964        return f"{self.column_parts(expression)}{join_mark}"
     965
     966    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
     967        this = self.sql(expression, "this")
     968        this = f" {this}" if this else ""
     969        position = self.sql(expression, "position")
     970        return f"{position}{this}"
     971
     972    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
     973        column = self.sql(expression, "this")
     974        kind = self.sql(expression, "kind")
     975        constraints = self.expressions(expression, key="constraints", sep=" ", flat=True)
     976        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
     977        kind = f"{sep}{kind}" if kind else ""
     978        constraints = f" {constraints}" if constraints else ""
     979        position = self.sql(expression, "position")
     980        position = f" {position}" if position else ""
     981
     982        if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE:
     983            kind = ""
     984
     985        return f"{exists}{column}{kind}{constraints}{position}"
     986
     987    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
     988        this = self.sql(expression, "this")
     989        kind_sql = self.sql(expression, "kind").strip()
     990        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql
     991
     992    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
     993        this = self.sql(expression, "this")
     994        if expression.args.get("not_null"):
     995            persisted = " PERSISTED NOT NULL"
     996        elif expression.args.get("persisted"):
     997            persisted = " PERSISTED"
     998        else:
     999            persisted = ""
    1000        return f"AS {this}{persisted}"
    1001
    1002    def autoincrementcolumnconstraint_sql(self, _) -> str:
    1003        return self.token_sql(TokenType.AUTO_INCREMENT)
    1004
    1005    def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str:
    1006        if isinstance(expression.this, list):
    1007            this = self.wrap(self.expressions(expression, key="this", flat=True))
    1008        else:
    1009            this = self.sql(expression, "this")
    1010
    1011        return f"COMPRESS {this}"
    1012
    1013    def generatedasidentitycolumnconstraint_sql(
    1014        self, expression: exp.GeneratedAsIdentityColumnConstraint
    1015    ) -> str:
    1016        this = ""
    1017        if expression.this is not None:
    1018            on_null = " ON NULL" if expression.args.get("on_null") else ""
    1019            this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}"
    1020
    1021        start = expression.args.get("start")
    1022        start = f"START WITH {start}" if start else ""
    1023        increment = expression.args.get("increment")
    1024        increment = f" INCREMENT BY {increment}" if increment else ""
    1025        minvalue = expression.args.get("minvalue")
    1026        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    1027        maxvalue = expression.args.get("maxvalue")
    1028        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    1029        cycle = expression.args.get("cycle")
    1030        cycle_sql = ""
    1031
    1032        if cycle is not None:
    1033            cycle_sql = f"{' NO' if not cycle else ''} CYCLE"
    1034            cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql
    1035
    1036        sequence_opts = ""
    1037        if start or increment or cycle_sql:
    1038            sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}"
    1039            sequence_opts = f" ({sequence_opts.strip()})"
    1040
    1041        expr = self.sql(expression, "expression")
    1042        expr = f"({expr})" if expr else "IDENTITY"
    1043
    1044        return f"GENERATED{this} AS {expr}{sequence_opts}"
    1045
    1046    def generatedasrowcolumnconstraint_sql(
    1047        self, expression: exp.GeneratedAsRowColumnConstraint
    1048    ) -> str:
    1049        start = "START" if expression.args.get("start") else "END"
    1050        hidden = " HIDDEN" if expression.args.get("hidden") else ""
    1051        return f"GENERATED ALWAYS AS ROW {start}{hidden}"
    1052
    1053    def periodforsystemtimeconstraint_sql(
    1054        self, expression: exp.PeriodForSystemTimeConstraint
    1055    ) -> str:
    1056        return f"PERIOD FOR SYSTEM_TIME ({self.sql(expression, 'this')}, {self.sql(expression, 'expression')})"
    1057
    1058    def notnullcolumnconstraint_sql(self, expression: exp.NotNullColumnConstraint) -> str:
    1059        return f"{'' if expression.args.get('allow_null') else 'NOT '}NULL"
    1060
    1061    def transformcolumnconstraint_sql(self, expression: exp.TransformColumnConstraint) -> str:
    1062        return f"AS {self.sql(expression, 'this')}"
    1063
    1064    def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str:
    1065        desc = expression.args.get("desc")
    1066        if desc is not None:
    1067            return f"PRIMARY KEY{' DESC' if desc else ' ASC'}"
    1068        return "PRIMARY KEY"
    1069
    1070    def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str:
    1071        this = self.sql(expression, "this")
    1072        this = f" {this}" if this else ""
    1073        index_type = expression.args.get("index_type")
    1074        index_type = f" USING {index_type}" if index_type else ""
    1075        on_conflict = self.sql(expression, "on_conflict")
    1076        on_conflict = f" {on_conflict}" if on_conflict else ""
    1077        nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else ""
    1078        return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}"
    1079
    1080    def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str:
    1081        return self.sql(expression, "this")
    1082
    1083    def create_sql(self, expression: exp.Create) -> str:
    1084        kind = self.sql(expression, "kind")
    1085        kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind
    1086        properties = expression.args.get("properties")
    1087        properties_locs = self.locate_properties(properties) if properties else defaultdict()
    1088
    1089        this = self.createable_sql(expression, properties_locs)
    1090
    1091        properties_sql = ""
    1092        if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get(
    1093            exp.Properties.Location.POST_WITH
    1094        ):
    1095            properties_sql = self.sql(
    1096                exp.Properties(
    1097                    expressions=[
    1098                        *properties_locs[exp.Properties.Location.POST_SCHEMA],
    1099                        *properties_locs[exp.Properties.Location.POST_WITH],
    1100                    ]
    1101                )
    1102            )
    1103
    1104            if properties_locs.get(exp.Properties.Location.POST_SCHEMA):
    1105                properties_sql = self.sep() + properties_sql
    1106            elif not self.pretty:
    1107                # Standalone POST_WITH properties need a leading whitespace in non-pretty mode
    1108                properties_sql = f" {properties_sql}"
    1109
    1110        begin = " BEGIN" if expression.args.get("begin") else ""
    1111        end = " END" if expression.args.get("end") else ""
    1112
    1113        expression_sql = self.sql(expression, "expression")
    1114        if expression_sql:
    1115            expression_sql = f"{begin}{self.sep()}{expression_sql}{end}"
    1116
    1117            if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return):
    1118                postalias_props_sql = ""
    1119                if properties_locs.get(exp.Properties.Location.POST_ALIAS):
    1120                    postalias_props_sql = self.properties(
    1121                        exp.Properties(
    1122                            expressions=properties_locs[exp.Properties.Location.POST_ALIAS]
    1123                        ),
    1124                        wrapped=False,
    1125                    )
    1126                postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else ""
    1127                expression_sql = f" AS{postalias_props_sql}{expression_sql}"
    1128
    1129        postindex_props_sql = ""
    1130        if properties_locs.get(exp.Properties.Location.POST_INDEX):
    1131            postindex_props_sql = self.properties(
    1132                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]),
    1133                wrapped=False,
    1134                prefix=" ",
    1135            )
    1136
    1137        indexes = self.expressions(expression, key="indexes", indent=False, sep=" ")
    1138        indexes = f" {indexes}" if indexes else ""
    1139        index_sql = indexes + postindex_props_sql
    1140
    1141        replace = " OR REPLACE" if expression.args.get("replace") else ""
    1142        refresh = " OR REFRESH" if expression.args.get("refresh") else ""
    1143        unique = " UNIQUE" if expression.args.get("unique") else ""
    1144
    1145        clustered = expression.args.get("clustered")
    1146        if clustered is None:
    1147            clustered_sql = ""
    1148        elif clustered:
    1149            clustered_sql = " CLUSTERED COLUMNSTORE"
    1150        else:
    1151            clustered_sql = " NONCLUSTERED COLUMNSTORE"
    1152
    1153        postcreate_props_sql = ""
    1154        if properties_locs.get(exp.Properties.Location.POST_CREATE):
    1155            postcreate_props_sql = self.properties(
    1156                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]),
    1157                sep=" ",
    1158                prefix=" ",
    1159                wrapped=False,
    1160            )
    1161
    1162        modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql))
    1163
    1164        postexpression_props_sql = ""
    1165        if properties_locs.get(exp.Properties.Location.POST_EXPRESSION):
    1166            postexpression_props_sql = self.properties(
    1167                exp.Properties(
    1168                    expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION]
    1169                ),
    1170                sep=" ",
    1171                prefix=" ",
    1172                wrapped=False,
    1173            )
    1174
    1175        concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else ""
    1176        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
    1177        no_schema_binding = (
    1178            " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else ""
    1179        )
    1180
    1181        clone = self.sql(expression, "clone")
    1182        clone = f" {clone}" if clone else ""
    1183
    1184        if kind in self.EXPRESSION_PRECEDES_PROPERTIES_CREATABLES:
    1185            properties_expression = f"{expression_sql}{properties_sql}"
    1186        else:
    1187            properties_expression = f"{properties_sql}{expression_sql}"
    1188
    1189        expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_expression}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}"
    1190        return self.prepend_ctes(expression, expression_sql)
    1191
    1192    def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str:
    1193        start = self.sql(expression, "start")
    1194        start = f"START WITH {start}" if start else ""
    1195        increment = self.sql(expression, "increment")
    1196        increment = f" INCREMENT BY {increment}" if increment else ""
    1197        minvalue = self.sql(expression, "minvalue")
    1198        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    1199        maxvalue = self.sql(expression, "maxvalue")
    1200        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    1201        owned = self.sql(expression, "owned")
    1202        owned = f" OWNED BY {owned}" if owned else ""
    1203
    1204        cache = expression.args.get("cache")
    1205        if cache is None:
    1206            cache_str = ""
    1207        elif cache is True:
    1208            cache_str = " CACHE"
    1209        else:
    1210            cache_str = f" CACHE {cache}"
    1211
    1212        options = self.expressions(expression, key="options", flat=True, sep=" ")
    1213        options = f" {options}" if options else ""
    1214
    1215        return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip()
    1216
    1217    def clone_sql(self, expression: exp.Clone) -> str:
    1218        this = self.sql(expression, "this")
    1219        shallow = "SHALLOW " if expression.args.get("shallow") else ""
    1220        keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE"
    1221        return f"{shallow}{keyword} {this}"
    1222
    1223    def describe_sql(self, expression: exp.Describe) -> str:
    1224        style = expression.args.get("style")
    1225        style = f" {style}" if style else ""
    1226        partition = self.sql(expression, "partition")
    1227        partition = f" {partition}" if partition else ""
    1228        format = self.sql(expression, "format")
    1229        format = f" {format}" if format else ""
    1230
    1231        return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}"
    1232
    1233    def heredoc_sql(self, expression: exp.Heredoc) -> str:
    1234        tag = self.sql(expression, "tag")
    1235        return f"${tag}${self.sql(expression, 'this')}${tag}$"
    1236
    1237    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
    1238        with_ = self.sql(expression, "with")
    1239        if with_:
    1240            sql = f"{with_}{self.sep()}{sql}"
    1241        return sql
    1242
    1243    def with_sql(self, expression: exp.With) -> str:
    1244        sql = self.expressions(expression, flat=True)
    1245        recursive = (
    1246            "RECURSIVE "
    1247            if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive")
    1248            else ""
    1249        )
    1250        search = self.sql(expression, "search")
    1251        search = f" {search}" if search else ""
    1252
    1253        return f"WITH {recursive}{sql}{search}"
    1254
    1255    def cte_sql(self, expression: exp.CTE) -> str:
    1256        alias = expression.args.get("alias")
    1257        if alias:
    1258            alias.add_comments(expression.pop_comments())
    1259
    1260        alias_sql = self.sql(expression, "alias")
    1261
    1262        materialized = expression.args.get("materialized")
    1263        if materialized is False:
    1264            materialized = "NOT MATERIALIZED "
    1265        elif materialized:
    1266            materialized = "MATERIALIZED "
    1267
    1268        return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}"
    1269
    1270    def tablealias_sql(self, expression: exp.TableAlias) -> str:
    1271        alias = self.sql(expression, "this")
    1272        columns = self.expressions(expression, key="columns", flat=True)
    1273        columns = f"({columns})" if columns else ""
    1274
    1275        if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS:
    1276            columns = ""
    1277            self.unsupported("Named columns are not supported in table alias.")
    1278
    1279        if not alias and not self.dialect.UNNEST_COLUMN_ONLY:
    1280            alias = self._next_name()
    1281
    1282        return f"{alias}{columns}"
    1283
    1284    def bitstring_sql(self, expression: exp.BitString) -> str:
    1285        this = self.sql(expression, "this")
    1286        if self.dialect.BIT_START:
    1287            return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}"
    1288        return f"{int(this, 2)}"
    1289
    1290    def hexstring_sql(
    1291        self, expression: exp.HexString, binary_function_repr: t.Optional[str] = None
    1292    ) -> str:
    1293        this = self.sql(expression, "this")
    1294        is_integer_type = expression.args.get("is_integer")
    1295
    1296        if (is_integer_type and not self.dialect.HEX_STRING_IS_INTEGER_TYPE) or (
    1297            not self.dialect.HEX_START and not binary_function_repr
    1298        ):
    1299            # Integer representation will be returned if:
    1300            # - The read dialect treats the hex value as integer literal but not the write
    1301            # - The transpilation is not supported (write dialect hasn't set HEX_START or the param flag)
    1302            return f"{int(this, 16)}"
    1303
    1304        if not is_integer_type:
    1305            # Read dialect treats the hex value as BINARY/BLOB
    1306            if binary_function_repr:
    1307                # The write dialect supports the transpilation to its equivalent BINARY/BLOB
    1308                return self.func(binary_function_repr, exp.Literal.string(this))
    1309            if self.dialect.HEX_STRING_IS_INTEGER_TYPE:
    1310                # The write dialect does not support the transpilation, it'll treat the hex value as INTEGER
    1311                self.unsupported("Unsupported transpilation from BINARY/BLOB hex string")
    1312
    1313        return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"
    1314
    1315    def bytestring_sql(self, expression: exp.ByteString) -> str:
    1316        this = self.sql(expression, "this")
    1317        if self.dialect.BYTE_START:
    1318            return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}"
    1319        return this
    1320
    1321    def unicodestring_sql(self, expression: exp.UnicodeString) -> str:
    1322        this = self.sql(expression, "this")
    1323        escape = expression.args.get("escape")
    1324
    1325        if self.dialect.UNICODE_START:
    1326            escape_substitute = r"\\\1"
    1327            left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END
    1328        else:
    1329            escape_substitute = r"\\u\1"
    1330            left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END
    1331
    1332        if escape:
    1333            escape_pattern = re.compile(rf"{escape.name}(\d+)")
    1334            escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else ""
    1335        else:
    1336            escape_pattern = ESCAPED_UNICODE_RE
    1337            escape_sql = ""
    1338
    1339        if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE):
    1340            this = escape_pattern.sub(escape_substitute, this)
    1341
    1342        return f"{left_quote}{this}{right_quote}{escape_sql}"
    1343
    1344    def rawstring_sql(self, expression: exp.RawString) -> str:
    1345        string = self.escape_str(expression.this.replace("\\", "\\\\"), escape_backslash=False)
    1346        return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}"
    1347
    1348    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
    1349        this = self.sql(expression, "this")
    1350        specifier = self.sql(expression, "expression")
    1351        specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else ""
    1352        return f"{this}{specifier}"
    1353
    1354    def datatype_sql(self, expression: exp.DataType) -> str:
    1355        nested = ""
    1356        values = ""
    1357        interior = self.expressions(expression, flat=True)
    1358
    1359        type_value = expression.this
    1360        if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"):
    1361            type_sql = self.sql(expression, "kind")
    1362        else:
    1363            type_sql = (
    1364                self.TYPE_MAPPING.get(type_value, type_value.value)
    1365                if isinstance(type_value, exp.DataType.Type)
    1366                else type_value
    1367            )
    1368
    1369        if interior:
    1370            if expression.args.get("nested"):
    1371                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
    1372                if expression.args.get("values") is not None:
    1373                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
    1374                    values = self.expressions(expression, key="values", flat=True)
    1375                    values = f"{delimiters[0]}{values}{delimiters[1]}"
    1376            elif type_value == exp.DataType.Type.INTERVAL:
    1377                nested = f" {interior}"
    1378            else:
    1379                nested = f"({interior})"
    1380
    1381        type_sql = f"{type_sql}{nested}{values}"
    1382        if self.TZ_TO_WITH_TIME_ZONE and type_value in (
    1383            exp.DataType.Type.TIMETZ,
    1384            exp.DataType.Type.TIMESTAMPTZ,
    1385        ):
    1386            type_sql = f"{type_sql} WITH TIME ZONE"
    1387
    1388        return type_sql
    1389
    1390    def directory_sql(self, expression: exp.Directory) -> str:
    1391        local = "LOCAL " if expression.args.get("local") else ""
    1392        row_format = self.sql(expression, "row_format")
    1393        row_format = f" {row_format}" if row_format else ""
    1394        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"
    1395
    1396    def delete_sql(self, expression: exp.Delete) -> str:
    1397        this = self.sql(expression, "this")
    1398        this = f" FROM {this}" if this else ""
    1399        using = self.sql(expression, "using")
    1400        using = f" USING {using}" if using else ""
    1401        cluster = self.sql(expression, "cluster")
    1402        cluster = f" {cluster}" if cluster else ""
    1403        where = self.sql(expression, "where")
    1404        returning = self.sql(expression, "returning")
    1405        limit = self.sql(expression, "limit")
    1406        tables = self.expressions(expression, key="tables")
    1407        tables = f" {tables}" if tables else ""
    1408        if self.RETURNING_END:
    1409            expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}"
    1410        else:
    1411            expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}"
    1412        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")
    1413
    1414    def drop_sql(self, expression: exp.Drop) -> str:
    1415        this = self.sql(expression, "this")
    1416        expressions = self.expressions(expression, flat=True)
    1417        expressions = f" ({expressions})" if expressions else ""
    1418        kind = expression.args["kind"]
    1419        kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind
    1420        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    1421        concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else ""
    1422        on_cluster = self.sql(expression, "cluster")
    1423        on_cluster = f" {on_cluster}" if on_cluster else ""
    1424        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    1425        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    1426        cascade = " CASCADE" if expression.args.get("cascade") else ""
    1427        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
    1428        purge = " PURGE" if expression.args.get("purge") else ""
    1429        return f"DROP{temporary}{materialized} {kind}{concurrently_sql}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}"
    1430
    1431    def set_operation(self, expression: exp.SetOperation) -> str:
    1432        op_type = type(expression)
    1433        op_name = op_type.key.upper()
    1434
    1435        distinct = expression.args.get("distinct")
    1436        if (
    1437            distinct is False
    1438            and op_type in (exp.Except, exp.Intersect)
    1439            and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE
    1440        ):
    1441            self.unsupported(f"{op_name} ALL is not supported")
    1442
    1443        default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type]
    1444
    1445        if distinct is None:
    1446            distinct = default_distinct
    1447            if distinct is None:
    1448                self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified")
    1449
    1450        if distinct is default_distinct:
    1451            distinct_or_all = ""
    1452        else:
    1453            distinct_or_all = " DISTINCT" if distinct else " ALL"
    1454
    1455        side_kind = " ".join(filter(None, [expression.side, expression.kind]))
    1456        side_kind = f"{side_kind} " if side_kind else ""
    1457
    1458        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1459        on = self.expressions(expression, key="on", flat=True)
    1460        on = f" ON ({on})" if on else ""
    1461
    1462        return f"{side_kind}{op_name}{distinct_or_all}{by_name}{on}"
    1463
    1464    def set_operations(self, expression: exp.SetOperation) -> str:
    1465        if not self.SET_OP_MODIFIERS:
    1466            limit = expression.args.get("limit")
    1467            order = expression.args.get("order")
    1468
    1469            if limit or order:
    1470                select = self._move_ctes_to_top_level(
    1471                    exp.subquery(expression, "_l_0", copy=False).select("*", copy=False)
    1472                )
    1473
    1474                if limit:
    1475                    select = select.limit(limit.pop(), copy=False)
    1476                if order:
    1477                    select = select.order_by(order.pop(), copy=False)
    1478                return self.sql(select)
    1479
    1480        sqls: t.List[str] = []
    1481        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    1482
    1483        while stack:
    1484            node = stack.pop()
    1485
    1486            if isinstance(node, exp.SetOperation):
    1487                stack.append(node.expression)
    1488                stack.append(
    1489                    self.maybe_comment(
    1490                        self.set_operation(node), comments=node.comments, separated=True
    1491                    )
    1492                )
    1493                stack.append(node.this)
    1494            else:
    1495                sqls.append(self.sql(node))
    1496
    1497        this = self.sep().join(sqls)
    1498        this = self.query_modifiers(expression, this)
    1499        return self.prepend_ctes(expression, this)
    1500
    1501    def fetch_sql(self, expression: exp.Fetch) -> str:
    1502        direction = expression.args.get("direction")
    1503        direction = f" {direction}" if direction else ""
    1504        count = self.sql(expression, "count")
    1505        count = f" {count}" if count else ""
    1506        limit_options = self.sql(expression, "limit_options")
    1507        limit_options = f"{limit_options}" if limit_options else " ROWS ONLY"
    1508        return f"{self.seg('FETCH')}{direction}{count}{limit_options}"
    1509
    1510    def limitoptions_sql(self, expression: exp.LimitOptions) -> str:
    1511        percent = " PERCENT" if expression.args.get("percent") else ""
    1512        rows = " ROWS" if expression.args.get("rows") else ""
    1513        with_ties = " WITH TIES" if expression.args.get("with_ties") else ""
    1514        if not with_ties and rows:
    1515            with_ties = " ONLY"
    1516        return f"{percent}{rows}{with_ties}"
    1517
    1518    def filter_sql(self, expression: exp.Filter) -> str:
    1519        if self.AGGREGATE_FILTER_SUPPORTED:
    1520            this = self.sql(expression, "this")
    1521            where = self.sql(expression, "expression").strip()
    1522            return f"{this} FILTER({where})"
    1523
    1524        agg = expression.this
    1525        agg_arg = agg.this
    1526        cond = expression.expression.this
    1527        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
    1528        return self.sql(agg)
    1529
    1530    def hint_sql(self, expression: exp.Hint) -> str:
    1531        if not self.QUERY_HINTS:
    1532            self.unsupported("Hints are not supported")
    1533            return ""
    1534
    1535        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"
    1536
    1537    def indexparameters_sql(self, expression: exp.IndexParameters) -> str:
    1538        using = self.sql(expression, "using")
    1539        using = f" USING {using}" if using else ""
    1540        columns = self.expressions(expression, key="columns", flat=True)
    1541        columns = f"({columns})" if columns else ""
    1542        partition_by = self.expressions(expression, key="partition_by", flat=True)
    1543        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
    1544        where = self.sql(expression, "where")
    1545        include = self.expressions(expression, key="include", flat=True)
    1546        if include:
    1547            include = f" INCLUDE ({include})"
    1548        with_storage = self.expressions(expression, key="with_storage", flat=True)
    1549        with_storage = f" WITH ({with_storage})" if with_storage else ""
    1550        tablespace = self.sql(expression, "tablespace")
    1551        tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else ""
    1552        on = self.sql(expression, "on")
    1553        on = f" ON {on}" if on else ""
    1554
    1555        return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"
    1556
    1557    def index_sql(self, expression: exp.Index) -> str:
    1558        unique = "UNIQUE " if expression.args.get("unique") else ""
    1559        primary = "PRIMARY " if expression.args.get("primary") else ""
    1560        amp = "AMP " if expression.args.get("amp") else ""
    1561        name = self.sql(expression, "this")
    1562        name = f"{name} " if name else ""
    1563        table = self.sql(expression, "table")
    1564        table = f"{self.INDEX_ON} {table}" if table else ""
    1565
    1566        index = "INDEX " if not table else ""
    1567
    1568        params = self.sql(expression, "params")
    1569        return f"{unique}{primary}{amp}{index}{name}{table}{params}"
    1570
    1571    def identifier_sql(self, expression: exp.Identifier) -> str:
    1572        text = expression.name
    1573        lower = text.lower()
    1574        text = lower if self.normalize and not expression.quoted else text
    1575        text = text.replace(self._identifier_end, self._escaped_identifier_end)
    1576        if (
    1577            expression.quoted
    1578            or self.dialect.can_identify(text, self.identify)
    1579            or lower in self.RESERVED_KEYWORDS
    1580            or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
    1581        ):
    1582            text = f"{self._identifier_start}{text}{self._identifier_end}"
    1583        return text
    1584
    1585    def hex_sql(self, expression: exp.Hex) -> str:
    1586        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1587        if self.dialect.HEX_LOWERCASE:
    1588            text = self.func("LOWER", text)
    1589
    1590        return text
    1591
    1592    def lowerhex_sql(self, expression: exp.LowerHex) -> str:
    1593        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1594        if not self.dialect.HEX_LOWERCASE:
    1595            text = self.func("LOWER", text)
    1596        return text
    1597
    1598    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    1599        input_format = self.sql(expression, "input_format")
    1600        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    1601        output_format = self.sql(expression, "output_format")
    1602        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    1603        return self.sep().join((input_format, output_format))
    1604
    1605    def national_sql(self, expression: exp.National, prefix: str = "N") -> str:
    1606        string = self.sql(exp.Literal.string(expression.name))
    1607        return f"{prefix}{string}"
    1608
    1609    def partition_sql(self, expression: exp.Partition) -> str:
    1610        partition_keyword = "SUBPARTITION" if expression.args.get("subpartition") else "PARTITION"
    1611        return f"{partition_keyword}({self.expressions(expression, flat=True)})"
    1612
    1613    def properties_sql(self, expression: exp.Properties) -> str:
    1614        root_properties = []
    1615        with_properties = []
    1616
    1617        for p in expression.expressions:
    1618            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1619            if p_loc == exp.Properties.Location.POST_WITH:
    1620                with_properties.append(p)
    1621            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    1622                root_properties.append(p)
    1623
    1624        root_props = self.root_properties(exp.Properties(expressions=root_properties))
    1625        with_props = self.with_properties(exp.Properties(expressions=with_properties))
    1626
    1627        if root_props and with_props and not self.pretty:
    1628            with_props = " " + with_props
    1629
    1630        return root_props + with_props
    1631
    1632    def root_properties(self, properties: exp.Properties) -> str:
    1633        if properties.expressions:
    1634            return self.expressions(properties, indent=False, sep=" ")
    1635        return ""
    1636
    1637    def properties(
    1638        self,
    1639        properties: exp.Properties,
    1640        prefix: str = "",
    1641        sep: str = ", ",
    1642        suffix: str = "",
    1643        wrapped: bool = True,
    1644    ) -> str:
    1645        if properties.expressions:
    1646            expressions = self.expressions(properties, sep=sep, indent=False)
    1647            if expressions:
    1648                expressions = self.wrap(expressions) if wrapped else expressions
    1649                return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}"
    1650        return ""
    1651
    1652    def with_properties(self, properties: exp.Properties) -> str:
    1653        return self.properties(properties, prefix=self.seg(self.WITH_PROPERTIES_PREFIX, sep=""))
    1654
    1655    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
    1656        properties_locs = defaultdict(list)
    1657        for p in properties.expressions:
    1658            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1659            if p_loc != exp.Properties.Location.UNSUPPORTED:
    1660                properties_locs[p_loc].append(p)
    1661            else:
    1662                self.unsupported(f"Unsupported property {p.key}")
    1663
    1664        return properties_locs
    1665
    1666    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
    1667        if isinstance(expression.this, exp.Dot):
    1668            return self.sql(expression, "this")
    1669        return f"'{expression.name}'" if string_key else expression.name
    1670
    1671    def property_sql(self, expression: exp.Property) -> str:
    1672        property_cls = expression.__class__
    1673        if property_cls == exp.Property:
    1674            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
    1675
    1676        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    1677        if not property_name:
    1678            self.unsupported(f"Unsupported property {expression.key}")
    1679
    1680        return f"{property_name}={self.sql(expression, 'this')}"
    1681
    1682    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
    1683        if self.SUPPORTS_CREATE_TABLE_LIKE:
    1684            options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
    1685            options = f" {options}" if options else ""
    1686
    1687            like = f"LIKE {self.sql(expression, 'this')}{options}"
    1688            if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema):
    1689                like = f"({like})"
    1690
    1691            return like
    1692
    1693        if expression.expressions:
    1694            self.unsupported("Transpilation of LIKE property options is unsupported")
    1695
    1696        select = exp.select("*").from_(expression.this).limit(0)
    1697        return f"AS {self.sql(select)}"
    1698
    1699    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1700        no = "NO " if expression.args.get("no") else ""
    1701        protection = " PROTECTION" if expression.args.get("protection") else ""
    1702        return f"{no}FALLBACK{protection}"
    1703
    1704    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1705        no = "NO " if expression.args.get("no") else ""
    1706        local = expression.args.get("local")
    1707        local = f"{local} " if local else ""
    1708        dual = "DUAL " if expression.args.get("dual") else ""
    1709        before = "BEFORE " if expression.args.get("before") else ""
    1710        after = "AFTER " if expression.args.get("after") else ""
    1711        return f"{no}{local}{dual}{before}{after}JOURNAL"
    1712
    1713    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1714        freespace = self.sql(expression, "this")
    1715        percent = " PERCENT" if expression.args.get("percent") else ""
    1716        return f"FREESPACE={freespace}{percent}"
    1717
    1718    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1719        if expression.args.get("default"):
    1720            property = "DEFAULT"
    1721        elif expression.args.get("on"):
    1722            property = "ON"
    1723        else:
    1724            property = "OFF"
    1725        return f"CHECKSUM={property}"
    1726
    1727    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1728        if expression.args.get("no"):
    1729            return "NO MERGEBLOCKRATIO"
    1730        if expression.args.get("default"):
    1731            return "DEFAULT MERGEBLOCKRATIO"
    1732
    1733        percent = " PERCENT" if expression.args.get("percent") else ""
    1734        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"
    1735
    1736    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1737        default = expression.args.get("default")
    1738        minimum = expression.args.get("minimum")
    1739        maximum = expression.args.get("maximum")
    1740        if default or minimum or maximum:
    1741            if default:
    1742                prop = "DEFAULT"
    1743            elif minimum:
    1744                prop = "MINIMUM"
    1745            else:
    1746                prop = "MAXIMUM"
    1747            return f"{prop} DATABLOCKSIZE"
    1748        units = expression.args.get("units")
    1749        units = f" {units}" if units else ""
    1750        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"
    1751
    1752    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1753        autotemp = expression.args.get("autotemp")
    1754        always = expression.args.get("always")
    1755        default = expression.args.get("default")
    1756        manual = expression.args.get("manual")
    1757        never = expression.args.get("never")
    1758
    1759        if autotemp is not None:
    1760            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1761        elif always:
    1762            prop = "ALWAYS"
    1763        elif default:
    1764            prop = "DEFAULT"
    1765        elif manual:
    1766            prop = "MANUAL"
    1767        elif never:
    1768            prop = "NEVER"
    1769        return f"BLOCKCOMPRESSION={prop}"
    1770
    1771    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1772        no = expression.args.get("no")
    1773        no = " NO" if no else ""
    1774        concurrent = expression.args.get("concurrent")
    1775        concurrent = " CONCURRENT" if concurrent else ""
    1776        target = self.sql(expression, "target")
    1777        target = f" {target}" if target else ""
    1778        return f"WITH{no}{concurrent} ISOLATED LOADING{target}"
    1779
    1780    def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str:
    1781        if isinstance(expression.this, list):
    1782            return f"IN ({self.expressions(expression, key='this', flat=True)})"
    1783        if expression.this:
    1784            modulus = self.sql(expression, "this")
    1785            remainder = self.sql(expression, "expression")
    1786            return f"WITH (MODULUS {modulus}, REMAINDER {remainder})"
    1787
    1788        from_expressions = self.expressions(expression, key="from_expressions", flat=True)
    1789        to_expressions = self.expressions(expression, key="to_expressions", flat=True)
    1790        return f"FROM ({from_expressions}) TO ({to_expressions})"
    1791
    1792    def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str:
    1793        this = self.sql(expression, "this")
    1794
    1795        for_values_or_default = expression.expression
    1796        if isinstance(for_values_or_default, exp.PartitionBoundSpec):
    1797            for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}"
    1798        else:
    1799            for_values_or_default = " DEFAULT"
    1800
    1801        return f"PARTITION OF {this}{for_values_or_default}"
    1802
    1803    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1804        kind = expression.args.get("kind")
    1805        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1806        for_or_in = expression.args.get("for_or_in")
    1807        for_or_in = f" {for_or_in}" if for_or_in else ""
    1808        lock_type = expression.args.get("lock_type")
    1809        override = " OVERRIDE" if expression.args.get("override") else ""
    1810        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"
    1811
    1812    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1813        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1814        statistics = expression.args.get("statistics")
    1815        statistics_sql = ""
    1816        if statistics is not None:
    1817            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1818        return f"{data_sql}{statistics_sql}"
    1819
    1820    def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str:
    1821        this = self.sql(expression, "this")
    1822        this = f"HISTORY_TABLE={this}" if this else ""
    1823        data_consistency: t.Optional[str] = self.sql(expression, "data_consistency")
    1824        data_consistency = (
    1825            f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None
    1826        )
    1827        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    1828        retention_period = (
    1829            f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None
    1830        )
    1831
    1832        if this:
    1833            on_sql = self.func("ON", this, data_consistency, retention_period)
    1834        else:
    1835            on_sql = "ON" if expression.args.get("on") else "OFF"
    1836
    1837        sql = f"SYSTEM_VERSIONING={on_sql}"
    1838
    1839        return f"WITH({sql})" if expression.args.get("with") else sql
    1840
    1841    def insert_sql(self, expression: exp.Insert) -> str:
    1842        hint = self.sql(expression, "hint")
    1843        overwrite = expression.args.get("overwrite")
    1844
    1845        if isinstance(expression.this, exp.Directory):
    1846            this = " OVERWRITE" if overwrite else " INTO"
    1847        else:
    1848            this = self.INSERT_OVERWRITE if overwrite else " INTO"
    1849
    1850        stored = self.sql(expression, "stored")
    1851        stored = f" {stored}" if stored else ""
    1852        alternative = expression.args.get("alternative")
    1853        alternative = f" OR {alternative}" if alternative else ""
    1854        ignore = " IGNORE" if expression.args.get("ignore") else ""
    1855        is_function = expression.args.get("is_function")
    1856        if is_function:
    1857            this = f"{this} FUNCTION"
    1858        this = f"{this} {self.sql(expression, 'this')}"
    1859
    1860        exists = " IF EXISTS" if expression.args.get("exists") else ""
    1861        where = self.sql(expression, "where")
    1862        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
    1863        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
    1864        on_conflict = self.sql(expression, "conflict")
    1865        on_conflict = f" {on_conflict}" if on_conflict else ""
    1866        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1867        returning = self.sql(expression, "returning")
    1868
    1869        if self.RETURNING_END:
    1870            expression_sql = f"{expression_sql}{on_conflict}{returning}"
    1871        else:
    1872            expression_sql = f"{returning}{expression_sql}{on_conflict}"
    1873
    1874        partition_by = self.sql(expression, "partition")
    1875        partition_by = f" {partition_by}" if partition_by else ""
    1876        settings = self.sql(expression, "settings")
    1877        settings = f" {settings}" if settings else ""
    1878
    1879        source = self.sql(expression, "source")
    1880        source = f"TABLE {source}" if source else ""
    1881
    1882        sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}"
    1883        return self.prepend_ctes(expression, sql)
    1884
    1885    def introducer_sql(self, expression: exp.Introducer) -> str:
    1886        return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}"
    1887
    1888    def kill_sql(self, expression: exp.Kill) -> str:
    1889        kind = self.sql(expression, "kind")
    1890        kind = f" {kind}" if kind else ""
    1891        this = self.sql(expression, "this")
    1892        this = f" {this}" if this else ""
    1893        return f"KILL{kind}{this}"
    1894
    1895    def pseudotype_sql(self, expression: exp.PseudoType) -> str:
    1896        return expression.name
    1897
    1898    def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str:
    1899        return expression.name
    1900
    1901    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1902        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1903
    1904        constraint = self.sql(expression, "constraint")
    1905        constraint = f" ON CONSTRAINT {constraint}" if constraint else ""
    1906
    1907        conflict_keys = self.expressions(expression, key="conflict_keys", flat=True)
    1908        conflict_keys = f"({conflict_keys}) " if conflict_keys else " "
    1909        action = self.sql(expression, "action")
    1910
    1911        expressions = self.expressions(expression, flat=True)
    1912        if expressions:
    1913            set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
    1914            expressions = f" {set_keyword}{expressions}"
    1915
    1916        where = self.sql(expression, "where")
    1917        return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}"
    1918
    1919    def returning_sql(self, expression: exp.Returning) -> str:
    1920        return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}"
    1921
    1922    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1923        fields = self.sql(expression, "fields")
    1924        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1925        escaped = self.sql(expression, "escaped")
    1926        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1927        items = self.sql(expression, "collection_items")
    1928        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1929        keys = self.sql(expression, "map_keys")
    1930        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1931        lines = self.sql(expression, "lines")
    1932        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1933        null = self.sql(expression, "null")
    1934        null = f" NULL DEFINED AS {null}" if null else ""
    1935        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"
    1936
    1937    def withtablehint_sql(self, expression: exp.WithTableHint) -> str:
    1938        return f"WITH ({self.expressions(expression, flat=True)})"
    1939
    1940    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1941        this = f"{self.sql(expression, 'this')} INDEX"
    1942        target = self.sql(expression, "target")
    1943        target = f" FOR {target}" if target else ""
    1944        return f"{this}{target} ({self.expressions(expression, flat=True)})"
    1945
    1946    def historicaldata_sql(self, expression: exp.HistoricalData) -> str:
    1947        this = self.sql(expression, "this")
    1948        kind = self.sql(expression, "kind")
    1949        expr = self.sql(expression, "expression")
    1950        return f"{this} ({kind} => {expr})"
    1951
    1952    def table_parts(self, expression: exp.Table) -> str:
    1953        return ".".join(
    1954            self.sql(part)
    1955            for part in (
    1956                expression.args.get("catalog"),
    1957                expression.args.get("db"),
    1958                expression.args.get("this"),
    1959            )
    1960            if part is not None
    1961        )
    1962
    1963    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1964        table = self.table_parts(expression)
    1965        only = "ONLY " if expression.args.get("only") else ""
    1966        partition = self.sql(expression, "partition")
    1967        partition = f" {partition}" if partition else ""
    1968        version = self.sql(expression, "version")
    1969        version = f" {version}" if version else ""
    1970        alias = self.sql(expression, "alias")
    1971        alias = f"{sep}{alias}" if alias else ""
    1972
    1973        sample = self.sql(expression, "sample")
    1974        if self.dialect.ALIAS_POST_TABLESAMPLE:
    1975            sample_pre_alias = sample
    1976            sample_post_alias = ""
    1977        else:
    1978            sample_pre_alias = ""
    1979            sample_post_alias = sample
    1980
    1981        hints = self.expressions(expression, key="hints", sep=" ")
    1982        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
    1983        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    1984        joins = self.indent(
    1985            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
    1986        )
    1987        laterals = self.expressions(expression, key="laterals", sep="")
    1988
    1989        file_format = self.sql(expression, "format")
    1990        if file_format:
    1991            pattern = self.sql(expression, "pattern")
    1992            pattern = f", PATTERN => {pattern}" if pattern else ""
    1993            file_format = f" (FILE_FORMAT => {file_format}{pattern})"
    1994
    1995        ordinality = expression.args.get("ordinality") or ""
    1996        if ordinality:
    1997            ordinality = f" WITH ORDINALITY{alias}"
    1998            alias = ""
    1999
    2000        when = self.sql(expression, "when")
    2001        if when:
    2002            table = f"{table} {when}"
    2003
    2004        changes = self.sql(expression, "changes")
    2005        changes = f" {changes}" if changes else ""
    2006
    2007        rows_from = self.expressions(expression, key="rows_from")
    2008        if rows_from:
    2009            table = f"ROWS FROM {self.wrap(rows_from)}"
    2010
    2011        return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}"
    2012
    2013    def tablefromrows_sql(self, expression: exp.TableFromRows) -> str:
    2014        table = self.func("TABLE", expression.this)
    2015        alias = self.sql(expression, "alias")
    2016        alias = f" AS {alias}" if alias else ""
    2017        sample = self.sql(expression, "sample")
    2018        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    2019        joins = self.indent(
    2020            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
    2021        )
    2022        return f"{table}{alias}{pivots}{sample}{joins}"
    2023
    2024    def tablesample_sql(
    2025        self,
    2026        expression: exp.TableSample,
    2027        tablesample_keyword: t.Optional[str] = None,
    2028    ) -> str:
    2029        method = self.sql(expression, "method")
    2030        method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    2031        numerator = self.sql(expression, "bucket_numerator")
    2032        denominator = self.sql(expression, "bucket_denominator")
    2033        field = self.sql(expression, "bucket_field")
    2034        field = f" ON {field}" if field else ""
    2035        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    2036        seed = self.sql(expression, "seed")
    2037        seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else ""
    2038
    2039        size = self.sql(expression, "size")
    2040        if size and self.TABLESAMPLE_SIZE_IS_ROWS:
    2041            size = f"{size} ROWS"
    2042
    2043        percent = self.sql(expression, "percent")
    2044        if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT:
    2045            percent = f"{percent} PERCENT"
    2046
    2047        expr = f"{bucket}{percent}{size}"
    2048        if self.TABLESAMPLE_REQUIRES_PARENS:
    2049            expr = f"({expr})"
    2050
    2051        return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}"
    2052
    2053    def pivot_sql(self, expression: exp.Pivot) -> str:
    2054        expressions = self.expressions(expression, flat=True)
    2055        direction = "UNPIVOT" if expression.unpivot else "PIVOT"
    2056
    2057        group = self.sql(expression, "group")
    2058
    2059        if expression.this:
    2060            this = self.sql(expression, "this")
    2061            if not expressions:
    2062                return f"UNPIVOT {this}"
    2063
    2064            on = f"{self.seg('ON')} {expressions}"
    2065            into = self.sql(expression, "into")
    2066            into = f"{self.seg('INTO')} {into}" if into else ""
    2067            using = self.expressions(expression, key="using", flat=True)
    2068            using = f"{self.seg('USING')} {using}" if using else ""
    2069            return f"{direction} {this}{on}{into}{using}{group}"
    2070
    2071        alias = self.sql(expression, "alias")
    2072        alias = f" AS {alias}" if alias else ""
    2073
    2074        fields = self.expressions(
    2075            expression,
    2076            "fields",
    2077            sep=" ",
    2078            dynamic=True,
    2079            new_line=True,
    2080            skip_first=True,
    2081            skip_last=True,
    2082        )
    2083
    2084        include_nulls = expression.args.get("include_nulls")
    2085        if include_nulls is not None:
    2086            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
    2087        else:
    2088            nulls = ""
    2089
    2090        default_on_null = self.sql(expression, "default_on_null")
    2091        default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else ""
    2092        return f"{self.seg(direction)}{nulls}({expressions} FOR {fields}{default_on_null}{group}){alias}"
    2093
    2094    def version_sql(self, expression: exp.Version) -> str:
    2095        this = f"FOR {expression.name}"
    2096        kind = expression.text("kind")
    2097        expr = self.sql(expression, "expression")
    2098        return f"{this} {kind} {expr}"
    2099
    2100    def tuple_sql(self, expression: exp.Tuple) -> str:
    2101        return f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})"
    2102
    2103    def update_sql(self, expression: exp.Update) -> str:
    2104        this = self.sql(expression, "this")
    2105        set_sql = self.expressions(expression, flat=True)
    2106        from_sql = self.sql(expression, "from")
    2107        where_sql = self.sql(expression, "where")
    2108        returning = self.sql(expression, "returning")
    2109        order = self.sql(expression, "order")
    2110        limit = self.sql(expression, "limit")
    2111        if self.RETURNING_END:
    2112            expression_sql = f"{from_sql}{where_sql}{returning}"
    2113        else:
    2114            expression_sql = f"{returning}{from_sql}{where_sql}"
    2115        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
    2116        return self.prepend_ctes(expression, sql)
    2117
    2118    def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str:
    2119        values_as_table = values_as_table and self.VALUES_AS_TABLE
    2120
    2121        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
    2122        if values_as_table or not expression.find_ancestor(exp.From, exp.Join):
    2123            args = self.expressions(expression)
    2124            alias = self.sql(expression, "alias")
    2125            values = f"VALUES{self.seg('')}{args}"
    2126            values = (
    2127                f"({values})"
    2128                if self.WRAP_DERIVED_VALUES
    2129                and (alias or isinstance(expression.parent, (exp.From, exp.Table)))
    2130                else values
    2131            )
    2132            return f"{values} AS {alias}" if alias else values
    2133
    2134        # Converts `VALUES...` expression into a series of select unions.
    2135        alias_node = expression.args.get("alias")
    2136        column_names = alias_node and alias_node.columns
    2137
    2138        selects: t.List[exp.Query] = []
    2139
    2140        for i, tup in enumerate(expression.expressions):
    2141            row = tup.expressions
    2142
    2143            if i == 0 and column_names:
    2144                row = [
    2145                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
    2146                ]
    2147
    2148            selects.append(exp.Select(expressions=row))
    2149
    2150        if self.pretty:
    2151            # This may result in poor performance for large-cardinality `VALUES` tables, due to
    2152            # the deep nesting of the resulting exp.Unions. If this is a problem, either increase
    2153            # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`.
    2154            query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects)
    2155            return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False))
    2156
    2157        alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else ""
    2158        unions = " UNION ALL ".join(self.sql(select) for select in selects)
    2159        return f"({unions}){alias}"
    2160
    2161    def var_sql(self, expression: exp.Var) -> str:
    2162        return self.sql(expression, "this")
    2163
    2164    @unsupported_args("expressions")
    2165    def into_sql(self, expression: exp.Into) -> str:
    2166        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    2167        unlogged = " UNLOGGED" if expression.args.get("unlogged") else ""
    2168        return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"
    2169
    2170    def from_sql(self, expression: exp.From) -> str:
    2171        return f"{self.seg('FROM')} {self.sql(expression, 'this')}"
    2172
    2173    def groupingsets_sql(self, expression: exp.GroupingSets) -> str:
    2174        grouping_sets = self.expressions(expression, indent=False)
    2175        return f"GROUPING SETS {self.wrap(grouping_sets)}"
    2176
    2177    def rollup_sql(self, expression: exp.Rollup) -> str:
    2178        expressions = self.expressions(expression, indent=False)
    2179        return f"ROLLUP {self.wrap(expressions)}" if expressions else "WITH ROLLUP"
    2180
    2181    def cube_sql(self, expression: exp.Cube) -> str:
    2182        expressions = self.expressions(expression, indent=False)
    2183        return f"CUBE {self.wrap(expressions)}" if expressions else "WITH CUBE"
    2184
    2185    def group_sql(self, expression: exp.Group) -> str:
    2186        group_by_all = expression.args.get("all")
    2187        if group_by_all is True:
    2188            modifier = " ALL"
    2189        elif group_by_all is False:
    2190            modifier = " DISTINCT"
    2191        else:
    2192            modifier = ""
    2193
    2194        group_by = self.op_expressions(f"GROUP BY{modifier}", expression)
    2195
    2196        grouping_sets = self.expressions(expression, key="grouping_sets")
    2197        cube = self.expressions(expression, key="cube")
    2198        rollup = self.expressions(expression, key="rollup")
    2199
    2200        groupings = csv(
    2201            self.seg(grouping_sets) if grouping_sets else "",
    2202            self.seg(cube) if cube else "",
    2203            self.seg(rollup) if rollup else "",
    2204            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    2205            sep=self.GROUPINGS_SEP,
    2206        )
    2207
    2208        if (
    2209            expression.expressions
    2210            and groupings
    2211            and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP")
    2212        ):
    2213            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    2214
    2215        return f"{group_by}{groupings}"
    2216
    2217    def having_sql(self, expression: exp.Having) -> str:
    2218        this = self.indent(self.sql(expression, "this"))
    2219        return f"{self.seg('HAVING')}{self.sep()}{this}"
    2220
    2221    def connect_sql(self, expression: exp.Connect) -> str:
    2222        start = self.sql(expression, "start")
    2223        start = self.seg(f"START WITH {start}") if start else ""
    2224        nocycle = " NOCYCLE" if expression.args.get("nocycle") else ""
    2225        connect = self.sql(expression, "connect")
    2226        connect = self.seg(f"CONNECT BY{nocycle} {connect}")
    2227        return start + connect
    2228
    2229    def prior_sql(self, expression: exp.Prior) -> str:
    2230        return f"PRIOR {self.sql(expression, 'this')}"
    2231
    2232    def join_sql(self, expression: exp.Join) -> str:
    2233        if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"):
    2234            side = None
    2235        else:
    2236            side = expression.side
    2237
    2238        op_sql = " ".join(
    2239            op
    2240            for op in (
    2241                expression.method,
    2242                "GLOBAL" if expression.args.get("global") else None,
    2243                side,
    2244                expression.kind,
    2245                expression.hint if self.JOIN_HINTS else None,
    2246            )
    2247            if op
    2248        )
    2249        match_cond = self.sql(expression, "match_condition")
    2250        match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else ""
    2251        on_sql = self.sql(expression, "on")
    2252        using = expression.args.get("using")
    2253
    2254        if not on_sql and using:
    2255            on_sql = csv(*(self.sql(column) for column in using))
    2256
    2257        this = expression.this
    2258        this_sql = self.sql(this)
    2259
    2260        exprs = self.expressions(expression)
    2261        if exprs:
    2262            this_sql = f"{this_sql},{self.seg(exprs)}"
    2263
    2264        if on_sql:
    2265            on_sql = self.indent(on_sql, skip_first=True)
    2266            space = self.seg(" " * self.pad) if self.pretty else " "
    2267            if using:
    2268                on_sql = f"{space}USING ({on_sql})"
    2269            else:
    2270                on_sql = f"{space}ON {on_sql}"
    2271        elif not op_sql:
    2272            if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None:
    2273                return f" {this_sql}"
    2274
    2275            return f", {this_sql}"
    2276
    2277        if op_sql != "STRAIGHT_JOIN":
    2278            op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    2279
    2280        return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}"
    2281
    2282    def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->") -> str:
    2283        args = self.expressions(expression, flat=True)
    2284        args = f"({args})" if len(args.split(",")) > 1 else args
    2285        return f"{args} {arrow_sep} {self.sql(expression, 'this')}"
    2286
    2287    def lateral_op(self, expression: exp.Lateral) -> str:
    2288        cross_apply = expression.args.get("cross_apply")
    2289
    2290        # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/
    2291        if cross_apply is True:
    2292            op = "INNER JOIN "
    2293        elif cross_apply is False:
    2294            op = "LEFT JOIN "
    2295        else:
    2296            op = ""
    2297
    2298        return f"{op}LATERAL"
    2299
    2300    def lateral_sql(self, expression: exp.Lateral) -> str:
    2301        this = self.sql(expression, "this")
    2302
    2303        if expression.args.get("view"):
    2304            alias = expression.args["alias"]
    2305            columns = self.expressions(alias, key="columns", flat=True)
    2306            table = f" {alias.name}" if alias.name else ""
    2307            columns = f" AS {columns}" if columns else ""
    2308            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    2309            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    2310
    2311        alias = self.sql(expression, "alias")
    2312        alias = f" AS {alias}" if alias else ""
    2313
    2314        ordinality = expression.args.get("ordinality") or ""
    2315        if ordinality:
    2316            ordinality = f" WITH ORDINALITY{alias}"
    2317            alias = ""
    2318
    2319        return f"{self.lateral_op(expression)} {this}{alias}{ordinality}"
    2320
    2321    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    2322        this = self.sql(expression, "this")
    2323
    2324        args = [
    2325            self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e
    2326            for e in (expression.args.get(k) for k in ("offset", "expression"))
    2327            if e
    2328        ]
    2329
    2330        args_sql = ", ".join(self.sql(e) for e in args)
    2331        args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql
    2332        expressions = self.expressions(expression, flat=True)
    2333        limit_options = self.sql(expression, "limit_options")
    2334        expressions = f" BY {expressions}" if expressions else ""
    2335
    2336        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{limit_options}{expressions}"
    2337
    2338    def offset_sql(self, expression: exp.Offset) -> str:
    2339        this = self.sql(expression, "this")
    2340        value = expression.expression
    2341        value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value
    2342        expressions = self.expressions(expression, flat=True)
    2343        expressions = f" BY {expressions}" if expressions else ""
    2344        return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"
    2345
    2346    def setitem_sql(self, expression: exp.SetItem) -> str:
    2347        kind = self.sql(expression, "kind")
    2348        kind = f"{kind} " if kind else ""
    2349        this = self.sql(expression, "this")
    2350        expressions = self.expressions(expression)
    2351        collate = self.sql(expression, "collate")
    2352        collate = f" COLLATE {collate}" if collate else ""
    2353        global_ = "GLOBAL " if expression.args.get("global") else ""
    2354        return f"{global_}{kind}{this}{expressions}{collate}"
    2355
    2356    def set_sql(self, expression: exp.Set) -> str:
    2357        expressions = f" {self.expressions(expression, flat=True)}"
    2358        tag = " TAG" if expression.args.get("tag") else ""
    2359        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"
    2360
    2361    def pragma_sql(self, expression: exp.Pragma) -> str:
    2362        return f"PRAGMA {self.sql(expression, 'this')}"
    2363
    2364    def lock_sql(self, expression: exp.Lock) -> str:
    2365        if not self.LOCKING_READS_SUPPORTED:
    2366            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    2367            return ""
    2368
    2369        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    2370        expressions = self.expressions(expression, flat=True)
    2371        expressions = f" OF {expressions}" if expressions else ""
    2372        wait = expression.args.get("wait")
    2373
    2374        if wait is not None:
    2375            if isinstance(wait, exp.Literal):
    2376                wait = f" WAIT {self.sql(wait)}"
    2377            else:
    2378                wait = " NOWAIT" if wait else " SKIP LOCKED"
    2379
    2380        return f"{lock_type}{expressions}{wait or ''}"
    2381
    2382    def literal_sql(self, expression: exp.Literal) -> str:
    2383        text = expression.this or ""
    2384        if expression.is_string:
    2385            text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}"
    2386        return text
    2387
    2388    def escape_str(self, text: str, escape_backslash: bool = True) -> str:
    2389        if self.dialect.ESCAPED_SEQUENCES:
    2390            to_escaped = self.dialect.ESCAPED_SEQUENCES
    2391            text = "".join(
    2392                to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text
    2393            )
    2394
    2395        return self._replace_line_breaks(text).replace(
    2396            self.dialect.QUOTE_END, self._escaped_quote_end
    2397        )
    2398
    2399    def loaddata_sql(self, expression: exp.LoadData) -> str:
    2400        local = " LOCAL" if expression.args.get("local") else ""
    2401        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    2402        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    2403        this = f" INTO TABLE {self.sql(expression, 'this')}"
    2404        partition = self.sql(expression, "partition")
    2405        partition = f" {partition}" if partition else ""
    2406        input_format = self.sql(expression, "input_format")
    2407        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    2408        serde = self.sql(expression, "serde")
    2409        serde = f" SERDE {serde}" if serde else ""
    2410        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"
    2411
    2412    def null_sql(self, *_) -> str:
    2413        return "NULL"
    2414
    2415    def boolean_sql(self, expression: exp.Boolean) -> str:
    2416        return "TRUE" if expression.this else "FALSE"
    2417
    2418    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    2419        this = self.sql(expression, "this")
    2420        this = f"{this} " if this else this
    2421        siblings = "SIBLINGS " if expression.args.get("siblings") else ""
    2422        return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat)  # type: ignore
    2423
    2424    def withfill_sql(self, expression: exp.WithFill) -> str:
    2425        from_sql = self.sql(expression, "from")
    2426        from_sql = f" FROM {from_sql}" if from_sql else ""
    2427        to_sql = self.sql(expression, "to")
    2428        to_sql = f" TO {to_sql}" if to_sql else ""
    2429        step_sql = self.sql(expression, "step")
    2430        step_sql = f" STEP {step_sql}" if step_sql else ""
    2431        interpolated_values = [
    2432            f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}"
    2433            if isinstance(e, exp.Alias)
    2434            else self.sql(e, "this")
    2435            for e in expression.args.get("interpolate") or []
    2436        ]
    2437        interpolate = (
    2438            f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else ""
    2439        )
    2440        return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}"
    2441
    2442    def cluster_sql(self, expression: exp.Cluster) -> str:
    2443        return self.op_expressions("CLUSTER BY", expression)
    2444
    2445    def distribute_sql(self, expression: exp.Distribute) -> str:
    2446        return self.op_expressions("DISTRIBUTE BY", expression)
    2447
    2448    def sort_sql(self, expression: exp.Sort) -> str:
    2449        return self.op_expressions("SORT BY", expression)
    2450
    2451    def ordered_sql(self, expression: exp.Ordered) -> str:
    2452        desc = expression.args.get("desc")
    2453        asc = not desc
    2454
    2455        nulls_first = expression.args.get("nulls_first")
    2456        nulls_last = not nulls_first
    2457        nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large"
    2458        nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small"
    2459        nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last"
    2460
    2461        this = self.sql(expression, "this")
    2462
    2463        sort_order = " DESC" if desc else (" ASC" if desc is False else "")
    2464        nulls_sort_change = ""
    2465        if nulls_first and (
    2466            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
    2467        ):
    2468            nulls_sort_change = " NULLS FIRST"
    2469        elif (
    2470            nulls_last
    2471            and ((asc and nulls_are_small) or (desc and nulls_are_large))
    2472            and not nulls_are_last
    2473        ):
    2474            nulls_sort_change = " NULLS LAST"
    2475
    2476        # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it
    2477        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
    2478            window = expression.find_ancestor(exp.Window, exp.Select)
    2479            if isinstance(window, exp.Window) and window.args.get("spec"):
    2480                self.unsupported(
    2481                    f"'{nulls_sort_change.strip()}' translation not supported in window functions"
    2482                )
    2483                nulls_sort_change = ""
    2484            elif self.NULL_ORDERING_SUPPORTED is False and (
    2485                (asc and nulls_sort_change == " NULLS LAST")
    2486                or (desc and nulls_sort_change == " NULLS FIRST")
    2487            ):
    2488                # BigQuery does not allow these ordering/nulls combinations when used under
    2489                # an aggregation func or under a window containing one
    2490                ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select)
    2491
    2492                if isinstance(ancestor, exp.Window):
    2493                    ancestor = ancestor.this
    2494                if isinstance(ancestor, exp.AggFunc):
    2495                    self.unsupported(
    2496                        f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order"
    2497                    )
    2498                    nulls_sort_change = ""
    2499            elif self.NULL_ORDERING_SUPPORTED is None:
    2500                if expression.this.is_int:
    2501                    self.unsupported(
    2502                        f"'{nulls_sort_change.strip()}' translation not supported with positional ordering"
    2503                    )
    2504                elif not isinstance(expression.this, exp.Rand):
    2505                    null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else ""
    2506                    this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}"
    2507                nulls_sort_change = ""
    2508
    2509        with_fill = self.sql(expression, "with_fill")
    2510        with_fill = f" {with_fill}" if with_fill else ""
    2511
    2512        return f"{this}{sort_order}{nulls_sort_change}{with_fill}"
    2513
    2514    def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str:
    2515        window_frame = self.sql(expression, "window_frame")
    2516        window_frame = f"{window_frame} " if window_frame else ""
    2517
    2518        this = self.sql(expression, "this")
    2519
    2520        return f"{window_frame}{this}"
    2521
    2522    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    2523        partition = self.partition_by_sql(expression)
    2524        order = self.sql(expression, "order")
    2525        measures = self.expressions(expression, key="measures")
    2526        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    2527        rows = self.sql(expression, "rows")
    2528        rows = self.seg(rows) if rows else ""
    2529        after = self.sql(expression, "after")
    2530        after = self.seg(after) if after else ""
    2531        pattern = self.sql(expression, "pattern")
    2532        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    2533        definition_sqls = [
    2534            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    2535            for definition in expression.args.get("define", [])
    2536        ]
    2537        definitions = self.expressions(sqls=definition_sqls)
    2538        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    2539        body = "".join(
    2540            (
    2541                partition,
    2542                order,
    2543                measures,
    2544                rows,
    2545                after,
    2546                pattern,
    2547                define,
    2548            )
    2549        )
    2550        alias = self.sql(expression, "alias")
    2551        alias = f" {alias}" if alias else ""
    2552        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"
    2553
    2554    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    2555        limit = expression.args.get("limit")
    2556
    2557        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    2558            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
    2559        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    2560            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
    2561
    2562        return csv(
    2563            *sqls,
    2564            *[self.sql(join) for join in expression.args.get("joins") or []],
    2565            self.sql(expression, "match"),
    2566            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    2567            self.sql(expression, "prewhere"),
    2568            self.sql(expression, "where"),
    2569            self.sql(expression, "connect"),
    2570            self.sql(expression, "group"),
    2571            self.sql(expression, "having"),
    2572            *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()],
    2573            self.sql(expression, "order"),
    2574            *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit),
    2575            *self.after_limit_modifiers(expression),
    2576            self.options_modifier(expression),
    2577            sep="",
    2578        )
    2579
    2580    def options_modifier(self, expression: exp.Expression) -> str:
    2581        options = self.expressions(expression, key="options")
    2582        return f" {options}" if options else ""
    2583
    2584    def queryoption_sql(self, expression: exp.QueryOption) -> str:
    2585        self.unsupported("Unsupported query option.")
    2586        return ""
    2587
    2588    def offset_limit_modifiers(
    2589        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    2590    ) -> t.List[str]:
    2591        return [
    2592            self.sql(expression, "offset") if fetch else self.sql(limit),
    2593            self.sql(limit) if fetch else self.sql(expression, "offset"),
    2594        ]
    2595
    2596    def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]:
    2597        locks = self.expressions(expression, key="locks", sep=" ")
    2598        locks = f" {locks}" if locks else ""
    2599        return [locks, self.sql(expression, "sample")]
    2600
    2601    def select_sql(self, expression: exp.Select) -> str:
    2602        into = expression.args.get("into")
    2603        if not self.SUPPORTS_SELECT_INTO and into:
    2604            into.pop()
    2605
    2606        hint = self.sql(expression, "hint")
    2607        distinct = self.sql(expression, "distinct")
    2608        distinct = f" {distinct}" if distinct else ""
    2609        kind = self.sql(expression, "kind")
    2610
    2611        limit = expression.args.get("limit")
    2612        if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP:
    2613            top = self.limit_sql(limit, top=True)
    2614            limit.pop()
    2615        else:
    2616            top = ""
    2617
    2618        expressions = self.expressions(expression)
    2619
    2620        if kind:
    2621            if kind in self.SELECT_KINDS:
    2622                kind = f" AS {kind}"
    2623            else:
    2624                if kind == "STRUCT":
    2625                    expressions = self.expressions(
    2626                        sqls=[
    2627                            self.sql(
    2628                                exp.Struct(
    2629                                    expressions=[
    2630                                        exp.PropertyEQ(this=e.args.get("alias"), expression=e.this)
    2631                                        if isinstance(e, exp.Alias)
    2632                                        else e
    2633                                        for e in expression.expressions
    2634                                    ]
    2635                                )
    2636                            )
    2637                        ]
    2638                    )
    2639                kind = ""
    2640
    2641        operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ")
    2642        operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else ""
    2643
    2644        # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata
    2645        # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first.
    2646        top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}"
    2647        expressions = f"{self.sep()}{expressions}" if expressions else expressions
    2648        sql = self.query_modifiers(
    2649            expression,
    2650            f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}",
    2651            self.sql(expression, "into", comment=False),
    2652            self.sql(expression, "from", comment=False),
    2653        )
    2654
    2655        # If both the CTE and SELECT clauses have comments, generate the latter earlier
    2656        if expression.args.get("with"):
    2657            sql = self.maybe_comment(sql, expression)
    2658            expression.pop_comments()
    2659
    2660        sql = self.prepend_ctes(expression, sql)
    2661
    2662        if not self.SUPPORTS_SELECT_INTO and into:
    2663            if into.args.get("temporary"):
    2664                table_kind = " TEMPORARY"
    2665            elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"):
    2666                table_kind = " UNLOGGED"
    2667            else:
    2668                table_kind = ""
    2669            sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}"
    2670
    2671        return sql
    2672
    2673    def schema_sql(self, expression: exp.Schema) -> str:
    2674        this = self.sql(expression, "this")
    2675        sql = self.schema_columns_sql(expression)
    2676        return f"{this} {sql}" if this and sql else this or sql
    2677
    2678    def schema_columns_sql(self, expression: exp.Schema) -> str:
    2679        if expression.expressions:
    2680            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
    2681        return ""
    2682
    2683    def star_sql(self, expression: exp.Star) -> str:
    2684        except_ = self.expressions(expression, key="except", flat=True)
    2685        except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else ""
    2686        replace = self.expressions(expression, key="replace", flat=True)
    2687        replace = f"{self.seg('REPLACE')} ({replace})" if replace else ""
    2688        rename = self.expressions(expression, key="rename", flat=True)
    2689        rename = f"{self.seg('RENAME')} ({rename})" if rename else ""
    2690        return f"*{except_}{replace}{rename}"
    2691
    2692    def parameter_sql(self, expression: exp.Parameter) -> str:
    2693        this = self.sql(expression, "this")
    2694        return f"{self.PARAMETER_TOKEN}{this}"
    2695
    2696    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    2697        this = self.sql(expression, "this")
    2698        kind = expression.text("kind")
    2699        if kind:
    2700            kind = f"{kind}."
    2701        return f"@@{kind}{this}"
    2702
    2703    def placeholder_sql(self, expression: exp.Placeholder) -> str:
    2704        return f"{self.NAMED_PLACEHOLDER_TOKEN}{expression.name}" if expression.this else "?"
    2705
    2706    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    2707        alias = self.sql(expression, "alias")
    2708        alias = f"{sep}{alias}" if alias else ""
    2709        sample = self.sql(expression, "sample")
    2710        if self.dialect.ALIAS_POST_TABLESAMPLE and sample:
    2711            alias = f"{sample}{alias}"
    2712
    2713            # Set to None so it's not generated again by self.query_modifiers()
    2714            expression.set("sample", None)
    2715
    2716        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    2717        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    2718        return self.prepend_ctes(expression, sql)
    2719
    2720    def qualify_sql(self, expression: exp.Qualify) -> str:
    2721        this = self.indent(self.sql(expression, "this"))
    2722        return f"{self.seg('QUALIFY')}{self.sep()}{this}"
    2723
    2724    def unnest_sql(self, expression: exp.Unnest) -> str:
    2725        args = self.expressions(expression, flat=True)
    2726
    2727        alias = expression.args.get("alias")
    2728        offset = expression.args.get("offset")
    2729
    2730        if self.UNNEST_WITH_ORDINALITY:
    2731            if alias and isinstance(offset, exp.Expression):
    2732                alias.append("columns", offset)
    2733
    2734        if alias and self.dialect.UNNEST_COLUMN_ONLY:
    2735            columns = alias.columns
    2736            alias = self.sql(columns[0]) if columns else ""
    2737        else:
    2738            alias = self.sql(alias)
    2739
    2740        alias = f" AS {alias}" if alias else alias
    2741        if self.UNNEST_WITH_ORDINALITY:
    2742            suffix = f" WITH ORDINALITY{alias}" if offset else alias
    2743        else:
    2744            if isinstance(offset, exp.Expression):
    2745                suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}"
    2746            elif offset:
    2747                suffix = f"{alias} WITH OFFSET"
    2748            else:
    2749                suffix = alias
    2750
    2751        return f"UNNEST({args}){suffix}"
    2752
    2753    def prewhere_sql(self, expression: exp.PreWhere) -> str:
    2754        return ""
    2755
    2756    def where_sql(self, expression: exp.Where) -> str:
    2757        this = self.indent(self.sql(expression, "this"))
    2758        return f"{self.seg('WHERE')}{self.sep()}{this}"
    2759
    2760    def window_sql(self, expression: exp.Window) -> str:
    2761        this = self.sql(expression, "this")
    2762        partition = self.partition_by_sql(expression)
    2763        order = expression.args.get("order")
    2764        order = self.order_sql(order, flat=True) if order else ""
    2765        spec = self.sql(expression, "spec")
    2766        alias = self.sql(expression, "alias")
    2767        over = self.sql(expression, "over") or "OVER"
    2768
    2769        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    2770
    2771        first = expression.args.get("first")
    2772        if first is None:
    2773            first = ""
    2774        else:
    2775            first = "FIRST" if first else "LAST"
    2776
    2777        if not partition and not order and not spec and alias:
    2778            return f"{this} {alias}"
    2779
    2780        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
    2781        return f"{this} ({args})"
    2782
    2783    def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str:
    2784        partition = self.expressions(expression, key="partition_by", flat=True)
    2785        return f"PARTITION BY {partition}" if partition else ""
    2786
    2787    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    2788        kind = self.sql(expression, "kind")
    2789        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    2790        end = (
    2791            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    2792            or "CURRENT ROW"
    2793        )
    2794        return f"{kind} BETWEEN {start} AND {end}"
    2795
    2796    def withingroup_sql(self, expression: exp.WithinGroup) -> str:
    2797        this = self.sql(expression, "this")
    2798        expression_sql = self.sql(expression, "expression")[1:]  # order has a leading space
    2799        return f"{this} WITHIN GROUP ({expression_sql})"
    2800
    2801    def between_sql(self, expression: exp.Between) -> str:
    2802        this = self.sql(expression, "this")
    2803        low = self.sql(expression, "low")
    2804        high = self.sql(expression, "high")
    2805        return f"{this} BETWEEN {low} AND {high}"
    2806
    2807    def bracket_offset_expressions(
    2808        self, expression: exp.Bracket, index_offset: t.Optional[int] = None
    2809    ) -> t.List[exp.Expression]:
    2810        return apply_index_offset(
    2811            expression.this,
    2812            expression.expressions,
    2813            (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0),
    2814            dialect=self.dialect,
    2815        )
    2816
    2817    def bracket_sql(self, expression: exp.Bracket) -> str:
    2818        expressions = self.bracket_offset_expressions(expression)
    2819        expressions_sql = ", ".join(self.sql(e) for e in expressions)
    2820        return f"{self.sql(expression, 'this')}[{expressions_sql}]"
    2821
    2822    def all_sql(self, expression: exp.All) -> str:
    2823        return f"ALL {self.wrap(expression)}"
    2824
    2825    def any_sql(self, expression: exp.Any) -> str:
    2826        this = self.sql(expression, "this")
    2827        if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)):
    2828            if isinstance(expression.this, exp.UNWRAPPED_QUERIES):
    2829                this = self.wrap(this)
    2830            return f"ANY{this}"
    2831        return f"ANY {this}"
    2832
    2833    def exists_sql(self, expression: exp.Exists) -> str:
    2834        return f"EXISTS{self.wrap(expression)}"
    2835
    2836    def case_sql(self, expression: exp.Case) -> str:
    2837        this = self.sql(expression, "this")
    2838        statements = [f"CASE {this}" if this else "CASE"]
    2839
    2840        for e in expression.args["ifs"]:
    2841            statements.append(f"WHEN {self.sql(e, 'this')}")
    2842            statements.append(f"THEN {self.sql(e, 'true')}")
    2843
    2844        default = self.sql(expression, "default")
    2845
    2846        if default:
    2847            statements.append(f"ELSE {default}")
    2848
    2849        statements.append("END")
    2850
    2851        if self.pretty and self.too_wide(statements):
    2852            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    2853
    2854        return " ".join(statements)
    2855
    2856    def constraint_sql(self, expression: exp.Constraint) -> str:
    2857        this = self.sql(expression, "this")
    2858        expressions = self.expressions(expression, flat=True)
    2859        return f"CONSTRAINT {this} {expressions}"
    2860
    2861    def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str:
    2862        order = expression.args.get("order")
    2863        order = f" OVER ({self.order_sql(order, flat=True)})" if order else ""
    2864        return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}"
    2865
    2866    def extract_sql(self, expression: exp.Extract) -> str:
    2867        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
    2868        expression_sql = self.sql(expression, "expression")
    2869        return f"EXTRACT({this} FROM {expression_sql})"
    2870
    2871    def trim_sql(self, expression: exp.Trim) -> str:
    2872        trim_type = self.sql(expression, "position")
    2873
    2874        if trim_type == "LEADING":
    2875            func_name = "LTRIM"
    2876        elif trim_type == "TRAILING":
    2877            func_name = "RTRIM"
    2878        else:
    2879            func_name = "TRIM"
    2880
    2881        return self.func(func_name, expression.this, expression.expression)
    2882
    2883    def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]:
    2884        args = expression.expressions
    2885        if isinstance(expression, exp.ConcatWs):
    2886            args = args[1:]  # Skip the delimiter
    2887
    2888        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    2889            args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args]
    2890
    2891        if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"):
    2892            args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args]
    2893
    2894        return args
    2895
    2896    def concat_sql(self, expression: exp.Concat) -> str:
    2897        expressions = self.convert_concat_args(expression)
    2898
    2899        # Some dialects don't allow a single-argument CONCAT call
    2900        if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1:
    2901            return self.sql(expressions[0])
    2902
    2903        return self.func("CONCAT", *expressions)
    2904
    2905    def concatws_sql(self, expression: exp.ConcatWs) -> str:
    2906        return self.func(
    2907            "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression)
    2908        )
    2909
    2910    def check_sql(self, expression: exp.Check) -> str:
    2911        this = self.sql(expression, key="this")
    2912        return f"CHECK ({this})"
    2913
    2914    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    2915        expressions = self.expressions(expression, flat=True)
    2916        expressions = f" ({expressions})" if expressions else ""
    2917        reference = self.sql(expression, "reference")
    2918        reference = f" {reference}" if reference else ""
    2919        delete = self.sql(expression, "delete")
    2920        delete = f" ON DELETE {delete}" if delete else ""
    2921        update = self.sql(expression, "update")
    2922        update = f" ON UPDATE {update}" if update else ""
    2923        return f"FOREIGN KEY{expressions}{reference}{delete}{update}"
    2924
    2925    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    2926        expressions = self.expressions(expression, flat=True)
    2927        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2928        options = f" {options}" if options else ""
    2929        return f"PRIMARY KEY ({expressions}){options}"
    2930
    2931    def if_sql(self, expression: exp.If) -> str:
    2932        return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false")))
    2933
    2934    def matchagainst_sql(self, expression: exp.MatchAgainst) -> str:
    2935        modifier = expression.args.get("modifier")
    2936        modifier = f" {modifier}" if modifier else ""
    2937        return f"{self.func('MATCH', *expression.expressions)} AGAINST({self.sql(expression, 'this')}{modifier})"
    2938
    2939    def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str:
    2940        return f"{self.sql(expression, 'this')}{self.JSON_KEY_VALUE_PAIR_SEP} {self.sql(expression, 'expression')}"
    2941
    2942    def jsonpath_sql(self, expression: exp.JSONPath) -> str:
    2943        path = self.expressions(expression, sep="", flat=True).lstrip(".")
    2944
    2945        if expression.args.get("escape"):
    2946            path = self.escape_str(path)
    2947
    2948        if self.QUOTE_JSON_PATH:
    2949            path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"
    2950
    2951        return path
    2952
    2953    def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str:
    2954        if isinstance(expression, exp.JSONPathPart):
    2955            transform = self.TRANSFORMS.get(expression.__class__)
    2956            if not callable(transform):
    2957                self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}")
    2958                return ""
    2959
    2960            return transform(self, expression)
    2961
    2962        if isinstance(expression, int):
    2963            return str(expression)
    2964
    2965        if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE:
    2966            escaped = expression.replace("'", "\\'")
    2967            escaped = f"\\'{expression}\\'"
    2968        else:
    2969            escaped = expression.replace('"', '\\"')
    2970            escaped = f'"{escaped}"'
    2971
    2972        return escaped
    2973
    2974    def formatjson_sql(self, expression: exp.FormatJson) -> str:
    2975        return f"{self.sql(expression, 'this')} FORMAT JSON"
    2976
    2977    def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str:
    2978        null_handling = expression.args.get("null_handling")
    2979        null_handling = f" {null_handling}" if null_handling else ""
    2980
    2981        unique_keys = expression.args.get("unique_keys")
    2982        if unique_keys is not None:
    2983            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    2984        else:
    2985            unique_keys = ""
    2986
    2987        return_type = self.sql(expression, "return_type")
    2988        return_type = f" RETURNING {return_type}" if return_type else ""
    2989        encoding = self.sql(expression, "encoding")
    2990        encoding = f" ENCODING {encoding}" if encoding else ""
    2991
    2992        return self.func(
    2993            "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG",
    2994            *expression.expressions,
    2995            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
    2996        )
    2997
    2998    def jsonobjectagg_sql(self, expression: exp.JSONObjectAgg) -> str:
    2999        return self.jsonobject_sql(expression)
    3000
    3001    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
    3002        null_handling = expression.args.get("null_handling")
    3003        null_handling = f" {null_handling}" if null_handling else ""
    3004        return_type = self.sql(expression, "return_type")
    3005        return_type = f" RETURNING {return_type}" if return_type else ""
    3006        strict = " STRICT" if expression.args.get("strict") else ""
    3007        return self.func(
    3008            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
    3009        )
    3010
    3011    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
    3012        this = self.sql(expression, "this")
    3013        order = self.sql(expression, "order")
    3014        null_handling = expression.args.get("null_handling")
    3015        null_handling = f" {null_handling}" if null_handling else ""
    3016        return_type = self.sql(expression, "return_type")
    3017        return_type = f" RETURNING {return_type}" if return_type else ""
    3018        strict = " STRICT" if expression.args.get("strict") else ""
    3019        return self.func(
    3020            "JSON_ARRAYAGG",
    3021            this,
    3022            suffix=f"{order}{null_handling}{return_type}{strict})",
    3023        )
    3024
    3025    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
    3026        path = self.sql(expression, "path")
    3027        path = f" PATH {path}" if path else ""
    3028        nested_schema = self.sql(expression, "nested_schema")
    3029
    3030        if nested_schema:
    3031            return f"NESTED{path} {nested_schema}"
    3032
    3033        this = self.sql(expression, "this")
    3034        kind = self.sql(expression, "kind")
    3035        kind = f" {kind}" if kind else ""
    3036        return f"{this}{kind}{path}"
    3037
    3038    def jsonschema_sql(self, expression: exp.JSONSchema) -> str:
    3039        return self.func("COLUMNS", *expression.expressions)
    3040
    3041    def jsontable_sql(self, expression: exp.JSONTable) -> str:
    3042        this = self.sql(expression, "this")
    3043        path = self.sql(expression, "path")
    3044        path = f", {path}" if path else ""
    3045        error_handling = expression.args.get("error_handling")
    3046        error_handling = f" {error_handling}" if error_handling else ""
    3047        empty_handling = expression.args.get("empty_handling")
    3048        empty_handling = f" {empty_handling}" if empty_handling else ""
    3049        schema = self.sql(expression, "schema")
    3050        return self.func(
    3051            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
    3052        )
    3053
    3054    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    3055        this = self.sql(expression, "this")
    3056        kind = self.sql(expression, "kind")
    3057        path = self.sql(expression, "path")
    3058        path = f" {path}" if path else ""
    3059        as_json = " AS JSON" if expression.args.get("as_json") else ""
    3060        return f"{this} {kind}{path}{as_json}"
    3061
    3062    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    3063        this = self.sql(expression, "this")
    3064        path = self.sql(expression, "path")
    3065        path = f", {path}" if path else ""
    3066        expressions = self.expressions(expression)
    3067        with_ = (
    3068            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    3069            if expressions
    3070            else ""
    3071        )
    3072        return f"OPENJSON({this}{path}){with_}"
    3073
    3074    def in_sql(self, expression: exp.In) -> str:
    3075        query = expression.args.get("query")
    3076        unnest = expression.args.get("unnest")
    3077        field = expression.args.get("field")
    3078        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    3079
    3080        if query:
    3081            in_sql = self.sql(query)
    3082        elif unnest:
    3083            in_sql = self.in_unnest_op(unnest)
    3084        elif field:
    3085            in_sql = self.sql(field)
    3086        else:
    3087            in_sql = f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})"
    3088
    3089        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"
    3090
    3091    def in_unnest_op(self, unnest: exp.Unnest) -> str:
    3092        return f"(SELECT {self.sql(unnest)})"
    3093
    3094    def interval_sql(self, expression: exp.Interval) -> str:
    3095        unit = self.sql(expression, "unit")
    3096        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    3097            unit = self.TIME_PART_SINGULARS.get(unit, unit)
    3098        unit = f" {unit}" if unit else ""
    3099
    3100        if self.SINGLE_STRING_INTERVAL:
    3101            this = expression.this.name if expression.this else ""
    3102            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    3103
    3104        this = self.sql(expression, "this")
    3105        if this:
    3106            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    3107            this = f" {this}" if unwrapped else f" ({this})"
    3108
    3109        return f"INTERVAL{this}{unit}"
    3110
    3111    def return_sql(self, expression: exp.Return) -> str:
    3112        return f"RETURN {self.sql(expression, 'this')}"
    3113
    3114    def reference_sql(self, expression: exp.Reference) -> str:
    3115        this = self.sql(expression, "this")
    3116        expressions = self.expressions(expression, flat=True)
    3117        expressions = f"({expressions})" if expressions else ""
    3118        options = self.expressions(expression, key="options", flat=True, sep=" ")
    3119        options = f" {options}" if options else ""
    3120        return f"REFERENCES {this}{expressions}{options}"
    3121
    3122    def anonymous_sql(self, expression: exp.Anonymous) -> str:
    3123        # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive
    3124        parent = expression.parent
    3125        is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression
    3126        return self.func(
    3127            self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified
    3128        )
    3129
    3130    def paren_sql(self, expression: exp.Paren) -> str:
    3131        sql = self.seg(self.indent(self.sql(expression, "this")), sep="")
    3132        return f"({sql}{self.seg(')', sep='')}"
    3133
    3134    def neg_sql(self, expression: exp.Neg) -> str:
    3135        # This makes sure we don't convert "- - 5" to "--5", which is a comment
    3136        this_sql = self.sql(expression, "this")
    3137        sep = " " if this_sql[0] == "-" else ""
    3138        return f"-{sep}{this_sql}"
    3139
    3140    def not_sql(self, expression: exp.Not) -> str:
    3141        return f"NOT {self.sql(expression, 'this')}"
    3142
    3143    def alias_sql(self, expression: exp.Alias) -> str:
    3144        alias = self.sql(expression, "alias")
    3145        alias = f" AS {alias}" if alias else ""
    3146        return f"{self.sql(expression, 'this')}{alias}"
    3147
    3148    def pivotalias_sql(self, expression: exp.PivotAlias) -> str:
    3149        alias = expression.args["alias"]
    3150
    3151        parent = expression.parent
    3152        pivot = parent and parent.parent
    3153
    3154        if isinstance(pivot, exp.Pivot) and pivot.unpivot:
    3155            identifier_alias = isinstance(alias, exp.Identifier)
    3156            literal_alias = isinstance(alias, exp.Literal)
    3157
    3158            if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    3159                alias.replace(exp.Literal.string(alias.output_name))
    3160            elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    3161                alias.replace(exp.to_identifier(alias.output_name))
    3162
    3163        return self.alias_sql(expression)
    3164
    3165    def aliases_sql(self, expression: exp.Aliases) -> str:
    3166        return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})"
    3167
    3168    def atindex_sql(self, expression: exp.AtTimeZone) -> str:
    3169        this = self.sql(expression, "this")
    3170        index = self.sql(expression, "expression")
    3171        return f"{this} AT {index}"
    3172
    3173    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    3174        this = self.sql(expression, "this")
    3175        zone = self.sql(expression, "zone")
    3176        return f"{this} AT TIME ZONE {zone}"
    3177
    3178    def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str:
    3179        this = self.sql(expression, "this")
    3180        zone = self.sql(expression, "zone")
    3181        return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'"
    3182
    3183    def add_sql(self, expression: exp.Add) -> str:
    3184        return self.binary(expression, "+")
    3185
    3186    def and_sql(
    3187        self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None
    3188    ) -> str:
    3189        return self.connector_sql(expression, "AND", stack)
    3190
    3191    def or_sql(
    3192        self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None
    3193    ) -> str:
    3194        return self.connector_sql(expression, "OR", stack)
    3195
    3196    def xor_sql(
    3197        self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None
    3198    ) -> str:
    3199        return self.connector_sql(expression, "XOR", stack)
    3200
    3201    def connector_sql(
    3202        self,
    3203        expression: exp.Connector,
    3204        op: str,
    3205        stack: t.Optional[t.List[str | exp.Expression]] = None,
    3206    ) -> str:
    3207        if stack is not None:
    3208            if expression.expressions:
    3209                stack.append(self.expressions(expression, sep=f" {op} "))
    3210            else:
    3211                stack.append(expression.right)
    3212                if expression.comments and self.comments:
    3213                    for comment in expression.comments:
    3214                        if comment:
    3215                            op += f" /*{self.pad_comment(comment)}*/"
    3216                stack.extend((op, expression.left))
    3217            return op
    3218
    3219        stack = [expression]
    3220        sqls: t.List[str] = []
    3221        ops = set()
    3222
    3223        while stack:
    3224            node = stack.pop()
    3225            if isinstance(node, exp.Connector):
    3226                ops.add(getattr(self, f"{node.key}_sql")(node, stack))
    3227            else:
    3228                sql = self.sql(node)
    3229                if sqls and sqls[-1] in ops:
    3230                    sqls[-1] += f" {sql}"
    3231                else:
    3232                    sqls.append(sql)
    3233
    3234        sep = "\n" if self.pretty and self.too_wide(sqls) else " "
    3235        return sep.join(sqls)
    3236
    3237    def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str:
    3238        return self.binary(expression, "&")
    3239
    3240    def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str:
    3241        return self.binary(expression, "<<")
    3242
    3243    def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str:
    3244        return f"~{self.sql(expression, 'this')}"
    3245
    3246    def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str:
    3247        return self.binary(expression, "|")
    3248
    3249    def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str:
    3250        return self.binary(expression, ">>")
    3251
    3252    def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str:
    3253        return self.binary(expression, "^")
    3254
    3255    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    3256        format_sql = self.sql(expression, "format")
    3257        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    3258        to_sql = self.sql(expression, "to")
    3259        to_sql = f" {to_sql}" if to_sql else ""
    3260        action = self.sql(expression, "action")
    3261        action = f" {action}" if action else ""
    3262        default = self.sql(expression, "default")
    3263        default = f" DEFAULT {default} ON CONVERSION ERROR" if default else ""
    3264        return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{default}{format_sql}{action})"
    3265
    3266    def currentdate_sql(self, expression: exp.CurrentDate) -> str:
    3267        zone = self.sql(expression, "this")
    3268        return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE"
    3269
    3270    def collate_sql(self, expression: exp.Collate) -> str:
    3271        if self.COLLATE_IS_FUNC:
    3272            return self.function_fallback_sql(expression)
    3273        return self.binary(expression, "COLLATE")
    3274
    3275    def command_sql(self, expression: exp.Command) -> str:
    3276        return f"{self.sql(expression, 'this')} {expression.text('expression').strip()}"
    3277
    3278    def comment_sql(self, expression: exp.Comment) -> str:
    3279        this = self.sql(expression, "this")
    3280        kind = expression.args["kind"]
    3281        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    3282        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    3283        expression_sql = self.sql(expression, "expression")
    3284        return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"
    3285
    3286    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    3287        this = self.sql(expression, "this")
    3288        delete = " DELETE" if expression.args.get("delete") else ""
    3289        recompress = self.sql(expression, "recompress")
    3290        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    3291        to_disk = self.sql(expression, "to_disk")
    3292        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    3293        to_volume = self.sql(expression, "to_volume")
    3294        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    3295        return f"{this}{delete}{recompress}{to_disk}{to_volume}"
    3296
    3297    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    3298        where = self.sql(expression, "where")
    3299        group = self.sql(expression, "group")
    3300        aggregates = self.expressions(expression, key="aggregates")
    3301        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    3302
    3303        if not (where or group or aggregates) and len(expression.expressions) == 1:
    3304            return f"TTL {self.expressions(expression, flat=True)}"
    3305
    3306        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"
    3307
    3308    def transaction_sql(self, expression: exp.Transaction) -> str:
    3309        return "BEGIN"
    3310
    3311    def commit_sql(self, expression: exp.Commit) -> str:
    3312        chain = expression.args.get("chain")
    3313        if chain is not None:
    3314            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    3315
    3316        return f"COMMIT{chain or ''}"
    3317
    3318    def rollback_sql(self, expression: exp.Rollback) -> str:
    3319        savepoint = expression.args.get("savepoint")
    3320        savepoint = f" TO {savepoint}" if savepoint else ""
    3321        return f"ROLLBACK{savepoint}"
    3322
    3323    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    3324        this = self.sql(expression, "this")
    3325
    3326        dtype = self.sql(expression, "dtype")
    3327        if dtype:
    3328            collate = self.sql(expression, "collate")
    3329            collate = f" COLLATE {collate}" if collate else ""
    3330            using = self.sql(expression, "using")
    3331            using = f" USING {using}" if using else ""
    3332            return f"ALTER COLUMN {this} {self.ALTER_SET_TYPE} {dtype}{collate}{using}"
    3333
    3334        default = self.sql(expression, "default")
    3335        if default:
    3336            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    3337
    3338        comment = self.sql(expression, "comment")
    3339        if comment:
    3340            return f"ALTER COLUMN {this} COMMENT {comment}"
    3341
    3342        visible = expression.args.get("visible")
    3343        if visible:
    3344            return f"ALTER COLUMN {this} SET {visible}"
    3345
    3346        allow_null = expression.args.get("allow_null")
    3347        drop = expression.args.get("drop")
    3348
    3349        if not drop and not allow_null:
    3350            self.unsupported("Unsupported ALTER COLUMN syntax")
    3351
    3352        if allow_null is not None:
    3353            keyword = "DROP" if drop else "SET"
    3354            return f"ALTER COLUMN {this} {keyword} NOT NULL"
    3355
    3356        return f"ALTER COLUMN {this} DROP DEFAULT"
    3357
    3358    def alterindex_sql(self, expression: exp.AlterIndex) -> str:
    3359        this = self.sql(expression, "this")
    3360
    3361        visible = expression.args.get("visible")
    3362        visible_sql = "VISIBLE" if visible else "INVISIBLE"
    3363
    3364        return f"ALTER INDEX {this} {visible_sql}"
    3365
    3366    def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str:
    3367        this = self.sql(expression, "this")
    3368        if not isinstance(expression.this, exp.Var):
    3369            this = f"KEY DISTKEY {this}"
    3370        return f"ALTER DISTSTYLE {this}"
    3371
    3372    def altersortkey_sql(self, expression: exp.AlterSortKey) -> str:
    3373        compound = " COMPOUND" if expression.args.get("compound") else ""
    3374        this = self.sql(expression, "this")
    3375        expressions = self.expressions(expression, flat=True)
    3376        expressions = f"({expressions})" if expressions else ""
    3377        return f"ALTER{compound} SORTKEY {this or expressions}"
    3378
    3379    def alterrename_sql(self, expression: exp.AlterRename) -> str:
    3380        if not self.RENAME_TABLE_WITH_DB:
    3381            # Remove db from tables
    3382            expression = expression.transform(
    3383                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    3384            ).assert_is(exp.AlterRename)
    3385        this = self.sql(expression, "this")
    3386        return f"RENAME TO {this}"
    3387
    3388    def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
    3389        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3390        old_column = self.sql(expression, "this")
    3391        new_column = self.sql(expression, "to")
    3392        return f"RENAME COLUMN{exists} {old_column} TO {new_column}"
    3393
    3394    def alterset_sql(self, expression: exp.AlterSet) -> str:
    3395        exprs = self.expressions(expression, flat=True)
    3396        return f"SET {exprs}"
    3397
    3398    def alter_sql(self, expression: exp.Alter) -> str:
    3399        actions = expression.args["actions"]
    3400
    3401        if isinstance(actions[0], exp.ColumnDef):
    3402            actions = self.add_column_sql(expression)
    3403        elif isinstance(actions[0], exp.Schema):
    3404            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    3405        elif isinstance(actions[0], exp.Delete):
    3406            actions = self.expressions(expression, key="actions", flat=True)
    3407        elif isinstance(actions[0], exp.Query):
    3408            actions = "AS " + self.expressions(expression, key="actions")
    3409        else:
    3410            actions = self.expressions(expression, key="actions", flat=True)
    3411
    3412        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3413        on_cluster = self.sql(expression, "cluster")
    3414        on_cluster = f" {on_cluster}" if on_cluster else ""
    3415        only = " ONLY" if expression.args.get("only") else ""
    3416        options = self.expressions(expression, key="options")
    3417        options = f", {options}" if options else ""
    3418        kind = self.sql(expression, "kind")
    3419        not_valid = " NOT VALID" if expression.args.get("not_valid") else ""
    3420
    3421        return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions}{not_valid}{options}"
    3422
    3423    def add_column_sql(self, expression: exp.Alter) -> str:
    3424        if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD:
    3425            return self.expressions(
    3426                expression,
    3427                key="actions",
    3428                prefix="ADD COLUMN ",
    3429                skip_first=True,
    3430            )
    3431        return f"ADD {self.expressions(expression, key='actions', flat=True)}"
    3432
    3433    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    3434        expressions = self.expressions(expression)
    3435        exists = " IF EXISTS " if expression.args.get("exists") else " "
    3436        return f"DROP{exists}{expressions}"
    3437
    3438    def addconstraint_sql(self, expression: exp.AddConstraint) -> str:
    3439        return f"ADD {self.expressions(expression)}"
    3440
    3441    def distinct_sql(self, expression: exp.Distinct) -> str:
    3442        this = self.expressions(expression, flat=True)
    3443
    3444        if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1:
    3445            case = exp.case()
    3446            for arg in expression.expressions:
    3447                case = case.when(arg.is_(exp.null()), exp.null())
    3448            this = self.sql(case.else_(f"({this})"))
    3449
    3450        this = f" {this}" if this else ""
    3451
    3452        on = self.sql(expression, "on")
    3453        on = f" ON {on}" if on else ""
    3454        return f"DISTINCT{this}{on}"
    3455
    3456    def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str:
    3457        return self._embed_ignore_nulls(expression, "IGNORE NULLS")
    3458
    3459    def respectnulls_sql(self, expression: exp.RespectNulls) -> str:
    3460        return self._embed_ignore_nulls(expression, "RESPECT NULLS")
    3461
    3462    def havingmax_sql(self, expression: exp.HavingMax) -> str:
    3463        this_sql = self.sql(expression, "this")
    3464        expression_sql = self.sql(expression, "expression")
    3465        kind = "MAX" if expression.args.get("max") else "MIN"
    3466        return f"{this_sql} HAVING {kind} {expression_sql}"
    3467
    3468    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    3469        return self.sql(
    3470            exp.Cast(
    3471                this=exp.Div(this=expression.this, expression=expression.expression),
    3472                to=exp.DataType(this=exp.DataType.Type.INT),
    3473            )
    3474        )
    3475
    3476    def dpipe_sql(self, expression: exp.DPipe) -> str:
    3477        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    3478            return self.func(
    3479                "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten())
    3480            )
    3481        return self.binary(expression, "||")
    3482
    3483    def div_sql(self, expression: exp.Div) -> str:
    3484        l, r = expression.left, expression.right
    3485
    3486        if not self.dialect.SAFE_DIVISION and expression.args.get("safe"):
    3487            r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0)))
    3488
    3489        if self.dialect.TYPED_DIVISION and not expression.args.get("typed"):
    3490            if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES):
    3491                l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE))
    3492
    3493        elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"):
    3494            if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES):
    3495                return self.sql(
    3496                    exp.cast(
    3497                        l / r,
    3498                        to=exp.DataType.Type.BIGINT,
    3499                    )
    3500                )
    3501
    3502        return self.binary(expression, "/")
    3503
    3504    def safedivide_sql(self, expression: exp.SafeDivide) -> str:
    3505        n = exp._wrap(expression.this, exp.Binary)
    3506        d = exp._wrap(expression.expression, exp.Binary)
    3507        return self.sql(exp.If(this=d.neq(0), true=n / d, false=exp.Null()))
    3508
    3509    def overlaps_sql(self, expression: exp.Overlaps) -> str:
    3510        return self.binary(expression, "OVERLAPS")
    3511
    3512    def distance_sql(self, expression: exp.Distance) -> str:
    3513        return self.binary(expression, "<->")
    3514
    3515    def dot_sql(self, expression: exp.Dot) -> str:
    3516        return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}"
    3517
    3518    def eq_sql(self, expression: exp.EQ) -> str:
    3519        return self.binary(expression, "=")
    3520
    3521    def propertyeq_sql(self, expression: exp.PropertyEQ) -> str:
    3522        return self.binary(expression, ":=")
    3523
    3524    def escape_sql(self, expression: exp.Escape) -> str:
    3525        return self.binary(expression, "ESCAPE")
    3526
    3527    def glob_sql(self, expression: exp.Glob) -> str:
    3528        return self.binary(expression, "GLOB")
    3529
    3530    def gt_sql(self, expression: exp.GT) -> str:
    3531        return self.binary(expression, ">")
    3532
    3533    def gte_sql(self, expression: exp.GTE) -> str:
    3534        return self.binary(expression, ">=")
    3535
    3536    def ilike_sql(self, expression: exp.ILike) -> str:
    3537        return self.binary(expression, "ILIKE")
    3538
    3539    def ilikeany_sql(self, expression: exp.ILikeAny) -> str:
    3540        return self.binary(expression, "ILIKE ANY")
    3541
    3542    def is_sql(self, expression: exp.Is) -> str:
    3543        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    3544            return self.sql(
    3545                expression.this if expression.expression.this else exp.not_(expression.this)
    3546            )
    3547        return self.binary(expression, "IS")
    3548
    3549    def like_sql(self, expression: exp.Like) -> str:
    3550        return self.binary(expression, "LIKE")
    3551
    3552    def likeany_sql(self, expression: exp.LikeAny) -> str:
    3553        return self.binary(expression, "LIKE ANY")
    3554
    3555    def similarto_sql(self, expression: exp.SimilarTo) -> str:
    3556        return self.binary(expression, "SIMILAR TO")
    3557
    3558    def lt_sql(self, expression: exp.LT) -> str:
    3559        return self.binary(expression, "<")
    3560
    3561    def lte_sql(self, expression: exp.LTE) -> str:
    3562        return self.binary(expression, "<=")
    3563
    3564    def mod_sql(self, expression: exp.Mod) -> str:
    3565        return self.binary(expression, "%")
    3566
    3567    def mul_sql(self, expression: exp.Mul) -> str:
    3568        return self.binary(expression, "*")
    3569
    3570    def neq_sql(self, expression: exp.NEQ) -> str:
    3571        return self.binary(expression, "<>")
    3572
    3573    def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str:
    3574        return self.binary(expression, "IS NOT DISTINCT FROM")
    3575
    3576    def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str:
    3577        return self.binary(expression, "IS DISTINCT FROM")
    3578
    3579    def slice_sql(self, expression: exp.Slice) -> str:
    3580        return self.binary(expression, ":")
    3581
    3582    def sub_sql(self, expression: exp.Sub) -> str:
    3583        return self.binary(expression, "-")
    3584
    3585    def trycast_sql(self, expression: exp.TryCast) -> str:
    3586        return self.cast_sql(expression, safe_prefix="TRY_")
    3587
    3588    def jsoncast_sql(self, expression: exp.JSONCast) -> str:
    3589        return self.cast_sql(expression)
    3590
    3591    def try_sql(self, expression: exp.Try) -> str:
    3592        if not self.TRY_SUPPORTED:
    3593            self.unsupported("Unsupported TRY function")
    3594            return self.sql(expression, "this")
    3595
    3596        return self.func("TRY", expression.this)
    3597
    3598    def log_sql(self, expression: exp.Log) -> str:
    3599        this = expression.this
    3600        expr = expression.expression
    3601
    3602        if self.dialect.LOG_BASE_FIRST is False:
    3603            this, expr = expr, this
    3604        elif self.dialect.LOG_BASE_FIRST is None and expr:
    3605            if this.name in ("2", "10"):
    3606                return self.func(f"LOG{this.name}", expr)
    3607
    3608            self.unsupported(f"Unsupported logarithm with base {self.sql(this)}")
    3609
    3610        return self.func("LOG", this, expr)
    3611
    3612    def use_sql(self, expression: exp.Use) -> str:
    3613        kind = self.sql(expression, "kind")
    3614        kind = f" {kind}" if kind else ""
    3615        this = self.sql(expression, "this") or self.expressions(expression, flat=True)
    3616        this = f" {this}" if this else ""
    3617        return f"USE{kind}{this}"
    3618
    3619    def binary(self, expression: exp.Binary, op: str) -> str:
    3620        sqls: t.List[str] = []
    3621        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    3622        binary_type = type(expression)
    3623
    3624        while stack:
    3625            node = stack.pop()
    3626
    3627            if type(node) is binary_type:
    3628                op_func = node.args.get("operator")
    3629                if op_func:
    3630                    op = f"OPERATOR({self.sql(op_func)})"
    3631
    3632                stack.append(node.right)
    3633                stack.append(f" {self.maybe_comment(op, comments=node.comments)} ")
    3634                stack.append(node.left)
    3635            else:
    3636                sqls.append(self.sql(node))
    3637
    3638        return "".join(sqls)
    3639
    3640    def ceil_floor(self, expression: exp.Ceil | exp.Floor) -> str:
    3641        to_clause = self.sql(expression, "to")
    3642        if to_clause:
    3643            return f"{expression.sql_name()}({self.sql(expression, 'this')} TO {to_clause})"
    3644
    3645        return self.function_fallback_sql(expression)
    3646
    3647    def function_fallback_sql(self, expression: exp.Func) -> str:
    3648        args = []
    3649
    3650        for key in expression.arg_types:
    3651            arg_value = expression.args.get(key)
    3652
    3653            if isinstance(arg_value, list):
    3654                for value in arg_value:
    3655                    args.append(value)
    3656            elif arg_value is not None:
    3657                args.append(arg_value)
    3658
    3659        if self.dialect.PRESERVE_ORIGINAL_NAMES:
    3660            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
    3661        else:
    3662            name = expression.sql_name()
    3663
    3664        return self.func(name, *args)
    3665
    3666    def func(
    3667        self,
    3668        name: str,
    3669        *args: t.Optional[exp.Expression | str],
    3670        prefix: str = "(",
    3671        suffix: str = ")",
    3672        normalize: bool = True,
    3673    ) -> str:
    3674        name = self.normalize_func(name) if normalize else name
    3675        return f"{name}{prefix}{self.format_args(*args)}{suffix}"
    3676
    3677    def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str:
    3678        arg_sqls = tuple(
    3679            self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool)
    3680        )
    3681        if self.pretty and self.too_wide(arg_sqls):
    3682            return self.indent(
    3683                "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True
    3684            )
    3685        return sep.join(arg_sqls)
    3686
    3687    def too_wide(self, args: t.Iterable) -> bool:
    3688        return sum(len(arg) for arg in args) > self.max_text_width
    3689
    3690    def format_time(
    3691        self,
    3692        expression: exp.Expression,
    3693        inverse_time_mapping: t.Optional[t.Dict[str, str]] = None,
    3694        inverse_time_trie: t.Optional[t.Dict] = None,
    3695    ) -> t.Optional[str]:
    3696        return format_time(
    3697            self.sql(expression, "format"),
    3698            inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING,
    3699            inverse_time_trie or self.dialect.INVERSE_TIME_TRIE,
    3700        )
    3701
    3702    def expressions(
    3703        self,
    3704        expression: t.Optional[exp.Expression] = None,
    3705        key: t.Optional[str] = None,
    3706        sqls: t.Optional[t.Collection[str | exp.Expression]] = None,
    3707        flat: bool = False,
    3708        indent: bool = True,
    3709        skip_first: bool = False,
    3710        skip_last: bool = False,
    3711        sep: str = ", ",
    3712        prefix: str = "",
    3713        dynamic: bool = False,
    3714        new_line: bool = False,
    3715    ) -> str:
    3716        expressions = expression.args.get(key or "expressions") if expression else sqls
    3717
    3718        if not expressions:
    3719            return ""
    3720
    3721        if flat:
    3722            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
    3723
    3724        num_sqls = len(expressions)
    3725        result_sqls = []
    3726
    3727        for i, e in enumerate(expressions):
    3728            sql = self.sql(e, comment=False)
    3729            if not sql:
    3730                continue
    3731
    3732            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    3733
    3734            if self.pretty:
    3735                if self.leading_comma:
    3736                    result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}")
    3737                else:
    3738                    result_sqls.append(
    3739                        f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}"
    3740                    )
    3741            else:
    3742                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    3743
    3744        if self.pretty and (not dynamic or self.too_wide(result_sqls)):
    3745            if new_line:
    3746                result_sqls.insert(0, "")
    3747                result_sqls.append("")
    3748            result_sql = "\n".join(s.rstrip() for s in result_sqls)
    3749        else:
    3750            result_sql = "".join(result_sqls)
    3751
    3752        return (
    3753            self.indent(result_sql, skip_first=skip_first, skip_last=skip_last)
    3754            if indent
    3755            else result_sql
    3756        )
    3757
    3758    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    3759        flat = flat or isinstance(expression.parent, exp.Properties)
    3760        expressions_sql = self.expressions(expression, flat=flat)
    3761        if flat:
    3762            return f"{op} {expressions_sql}"
    3763        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"
    3764
    3765    def naked_property(self, expression: exp.Property) -> str:
    3766        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    3767        if not property_name:
    3768            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    3769        return f"{property_name} {self.sql(expression, 'this')}"
    3770
    3771    def tag_sql(self, expression: exp.Tag) -> str:
    3772        return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}"
    3773
    3774    def token_sql(self, token_type: TokenType) -> str:
    3775        return self.TOKEN_MAPPING.get(token_type, token_type.name)
    3776
    3777    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    3778        this = self.sql(expression, "this")
    3779        expressions = self.no_identify(self.expressions, expression)
    3780        expressions = (
    3781            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    3782        )
    3783        return f"{this}{expressions}" if expressions.strip() != "" else this
    3784
    3785    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    3786        this = self.sql(expression, "this")
    3787        expressions = self.expressions(expression, flat=True)
    3788        return f"{this}({expressions})"
    3789
    3790    def kwarg_sql(self, expression: exp.Kwarg) -> str:
    3791        return self.binary(expression, "=>")
    3792
    3793    def when_sql(self, expression: exp.When) -> str:
    3794        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    3795        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    3796        condition = self.sql(expression, "condition")
    3797        condition = f" AND {condition}" if condition else ""
    3798
    3799        then_expression = expression.args.get("then")
    3800        if isinstance(then_expression, exp.Insert):
    3801            this = self.sql(then_expression, "this")
    3802            this = f"INSERT {this}" if this else "INSERT"
    3803            then = self.sql(then_expression, "expression")
    3804            then = f"{this} VALUES {then}" if then else this
    3805        elif isinstance(then_expression, exp.Update):
    3806            if isinstance(then_expression.args.get("expressions"), exp.Star):
    3807                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    3808            else:
    3809                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    3810        else:
    3811            then = self.sql(then_expression)
    3812        return f"WHEN {matched}{source}{condition} THEN {then}"
    3813
    3814    def whens_sql(self, expression: exp.Whens) -> str:
    3815        return self.expressions(expression, sep=" ", indent=False)
    3816
    3817    def merge_sql(self, expression: exp.Merge) -> str:
    3818        table = expression.this
    3819        table_alias = ""
    3820
    3821        hints = table.args.get("hints")
    3822        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
    3823            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
    3824            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
    3825
    3826        this = self.sql(table)
    3827        using = f"USING {self.sql(expression, 'using')}"
    3828        on = f"ON {self.sql(expression, 'on')}"
    3829        whens = self.sql(expression, "whens")
    3830
    3831        returning = self.sql(expression, "returning")
    3832        if returning:
    3833            whens = f"{whens}{returning}"
    3834
    3835        sep = self.sep()
    3836
    3837        return self.prepend_ctes(
    3838            expression,
    3839            f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}",
    3840        )
    3841
    3842    @unsupported_args("format")
    3843    def tochar_sql(self, expression: exp.ToChar) -> str:
    3844        return self.sql(exp.cast(expression.this, exp.DataType.Type.TEXT))
    3845
    3846    def tonumber_sql(self, expression: exp.ToNumber) -> str:
    3847        if not self.SUPPORTS_TO_NUMBER:
    3848            self.unsupported("Unsupported TO_NUMBER function")
    3849            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3850
    3851        fmt = expression.args.get("format")
    3852        if not fmt:
    3853            self.unsupported("Conversion format is required for TO_NUMBER")
    3854            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3855
    3856        return self.func("TO_NUMBER", expression.this, fmt)
    3857
    3858    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    3859        this = self.sql(expression, "this")
    3860        kind = self.sql(expression, "kind")
    3861        settings_sql = self.expressions(expression, key="settings", sep=" ")
    3862        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    3863        return f"{this}({kind}{args})"
    3864
    3865    def dictrange_sql(self, expression: exp.DictRange) -> str:
    3866        this = self.sql(expression, "this")
    3867        max = self.sql(expression, "max")
    3868        min = self.sql(expression, "min")
    3869        return f"{this}(MIN {min} MAX {max})"
    3870
    3871    def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str:
    3872        return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}"
    3873
    3874    def duplicatekeyproperty_sql(self, expression: exp.DuplicateKeyProperty) -> str:
    3875        return f"DUPLICATE KEY ({self.expressions(expression, flat=True)})"
    3876
    3877    # https://docs.starrocks.io/docs/sql-reference/sql-statements/table_bucket_part_index/CREATE_TABLE/
    3878    def uniquekeyproperty_sql(self, expression: exp.UniqueKeyProperty) -> str:
    3879        return f"UNIQUE KEY ({self.expressions(expression, flat=True)})"
    3880
    3881    # https://docs.starrocks.io/docs/sql-reference/sql-statements/data-definition/CREATE_TABLE/#distribution_desc
    3882    def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str:
    3883        expressions = self.expressions(expression, flat=True)
    3884        expressions = f" {self.wrap(expressions)}" if expressions else ""
    3885        buckets = self.sql(expression, "buckets")
    3886        kind = self.sql(expression, "kind")
    3887        buckets = f" BUCKETS {buckets}" if buckets else ""
    3888        order = self.sql(expression, "order")
    3889        return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}"
    3890
    3891    def oncluster_sql(self, expression: exp.OnCluster) -> str:
    3892        return ""
    3893
    3894    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    3895        expressions = self.expressions(expression, key="expressions", flat=True)
    3896        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    3897        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    3898        buckets = self.sql(expression, "buckets")
    3899        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"
    3900
    3901    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    3902        this = self.sql(expression, "this")
    3903        having = self.sql(expression, "having")
    3904
    3905        if having:
    3906            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    3907
    3908        return self.func("ANY_VALUE", this)
    3909
    3910    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
    3911        transform = self.func("TRANSFORM", *expression.expressions)
    3912        row_format_before = self.sql(expression, "row_format_before")
    3913        row_format_before = f" {row_format_before}" if row_format_before else ""
    3914        record_writer = self.sql(expression, "record_writer")
    3915        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
    3916        using = f" USING {self.sql(expression, 'command_script')}"
    3917        schema = self.sql(expression, "schema")
    3918        schema = f" AS {schema}" if schema else ""
    3919        row_format_after = self.sql(expression, "row_format_after")
    3920        row_format_after = f" {row_format_after}" if row_format_after else ""
    3921        record_reader = self.sql(expression, "record_reader")
    3922        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
    3923        return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}"
    3924
    3925    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
    3926        key_block_size = self.sql(expression, "key_block_size")
    3927        if key_block_size:
    3928            return f"KEY_BLOCK_SIZE = {key_block_size}"
    3929
    3930        using = self.sql(expression, "using")
    3931        if using:
    3932            return f"USING {using}"
    3933
    3934        parser = self.sql(expression, "parser")
    3935        if parser:
    3936            return f"WITH PARSER {parser}"
    3937
    3938        comment = self.sql(expression, "comment")
    3939        if comment:
    3940            return f"COMMENT {comment}"
    3941
    3942        visible = expression.args.get("visible")
    3943        if visible is not None:
    3944            return "VISIBLE" if visible else "INVISIBLE"
    3945
    3946        engine_attr = self.sql(expression, "engine_attr")
    3947        if engine_attr:
    3948            return f"ENGINE_ATTRIBUTE = {engine_attr}"
    3949
    3950        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
    3951        if secondary_engine_attr:
    3952            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
    3953
    3954        self.unsupported("Unsupported index constraint option.")
    3955        return ""
    3956
    3957    def checkcolumnconstraint_sql(self, expression: exp.CheckColumnConstraint) -> str:
    3958        enforced = " ENFORCED" if expression.args.get("enforced") else ""
    3959        return f"CHECK ({self.sql(expression, 'this')}){enforced}"
    3960
    3961    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
    3962        kind = self.sql(expression, "kind")
    3963        kind = f"{kind} INDEX" if kind else "INDEX"
    3964        this = self.sql(expression, "this")
    3965        this = f" {this}" if this else ""
    3966        index_type = self.sql(expression, "index_type")
    3967        index_type = f" USING {index_type}" if index_type else ""
    3968        expressions = self.expressions(expression, flat=True)
    3969        expressions = f" ({expressions})" if expressions else ""
    3970        options = self.expressions(expression, key="options", sep=" ")
    3971        options = f" {options}" if options else ""
    3972        return f"{kind}{this}{index_type}{expressions}{options}"
    3973
    3974    def nvl2_sql(self, expression: exp.Nvl2) -> str:
    3975        if self.NVL2_SUPPORTED:
    3976            return self.function_fallback_sql(expression)
    3977
    3978        case = exp.Case().when(
    3979            expression.this.is_(exp.null()).not_(copy=False),
    3980            expression.args["true"],
    3981            copy=False,
    3982        )
    3983        else_cond = expression.args.get("false")
    3984        if else_cond:
    3985            case.else_(else_cond, copy=False)
    3986
    3987        return self.sql(case)
    3988
    3989    def comprehension_sql(self, expression: exp.Comprehension) -> str:
    3990        this = self.sql(expression, "this")
    3991        expr = self.sql(expression, "expression")
    3992        iterator = self.sql(expression, "iterator")
    3993        condition = self.sql(expression, "condition")
    3994        condition = f" IF {condition}" if condition else ""
    3995        return f"{this} FOR {expr} IN {iterator}{condition}"
    3996
    3997    def columnprefix_sql(self, expression: exp.ColumnPrefix) -> str:
    3998        return f"{self.sql(expression, 'this')}({self.sql(expression, 'expression')})"
    3999
    4000    def opclass_sql(self, expression: exp.Opclass) -> str:
    4001        return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}"
    4002
    4003    def predict_sql(self, expression: exp.Predict) -> str:
    4004        model = self.sql(expression, "this")
    4005        model = f"MODEL {model}"
    4006        table = self.sql(expression, "expression")
    4007        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
    4008        parameters = self.sql(expression, "params_struct")
    4009        return self.func("PREDICT", model, table, parameters or None)
    4010
    4011    def forin_sql(self, expression: exp.ForIn) -> str:
    4012        this = self.sql(expression, "this")
    4013        expression_sql = self.sql(expression, "expression")
    4014        return f"FOR {this} DO {expression_sql}"
    4015
    4016    def refresh_sql(self, expression: exp.Refresh) -> str:
    4017        this = self.sql(expression, "this")
    4018        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
    4019        return f"REFRESH {table}{this}"
    4020
    4021    def toarray_sql(self, expression: exp.ToArray) -> str:
    4022        arg = expression.this
    4023        if not arg.type:
    4024            from sqlglot.optimizer.annotate_types import annotate_types
    4025
    4026            arg = annotate_types(arg, dialect=self.dialect)
    4027
    4028        if arg.is_type(exp.DataType.Type.ARRAY):
    4029            return self.sql(arg)
    4030
    4031        cond_for_null = arg.is_(exp.null())
    4032        return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False)))
    4033
    4034    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
    4035        this = expression.this
    4036        time_format = self.format_time(expression)
    4037
    4038        if time_format:
    4039            return self.sql(
    4040                exp.cast(
    4041                    exp.StrToTime(this=this, format=expression.args["format"]),
    4042                    exp.DataType.Type.TIME,
    4043                )
    4044            )
    4045
    4046        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
    4047            return self.sql(this)
    4048
    4049        return self.sql(exp.cast(this, exp.DataType.Type.TIME))
    4050
    4051    def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str:
    4052        this = expression.this
    4053        if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP):
    4054            return self.sql(this)
    4055
    4056        return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect))
    4057
    4058    def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str:
    4059        this = expression.this
    4060        if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME):
    4061            return self.sql(this)
    4062
    4063        return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect))
    4064
    4065    def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:
    4066        this = expression.this
    4067        time_format = self.format_time(expression)
    4068
    4069        if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT):
    4070            return self.sql(
    4071                exp.cast(
    4072                    exp.StrToTime(this=this, format=expression.args["format"]),
    4073                    exp.DataType.Type.DATE,
    4074                )
    4075            )
    4076
    4077        if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE):
    4078            return self.sql(this)
    4079
    4080        return self.sql(exp.cast(this, exp.DataType.Type.DATE))
    4081
    4082    def unixdate_sql(self, expression: exp.UnixDate) -> str:
    4083        return self.sql(
    4084            exp.func(
    4085                "DATEDIFF",
    4086                expression.this,
    4087                exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE),
    4088                "day",
    4089            )
    4090        )
    4091
    4092    def lastday_sql(self, expression: exp.LastDay) -> str:
    4093        if self.LAST_DAY_SUPPORTS_DATE_PART:
    4094            return self.function_fallback_sql(expression)
    4095
    4096        unit = expression.text("unit")
    4097        if unit and unit != "MONTH":
    4098            self.unsupported("Date parts are not supported in LAST_DAY.")
    4099
    4100        return self.func("LAST_DAY", expression.this)
    4101
    4102    def dateadd_sql(self, expression: exp.DateAdd) -> str:
    4103        from sqlglot.dialects.dialect import unit_to_str
    4104
    4105        return self.func(
    4106            "DATE_ADD", expression.this, expression.expression, unit_to_str(expression)
    4107        )
    4108
    4109    def arrayany_sql(self, expression: exp.ArrayAny) -> str:
    4110        if self.CAN_IMPLEMENT_ARRAY_ANY:
    4111            filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression)
    4112            filtered_not_empty = exp.ArraySize(this=filtered).neq(0)
    4113            original_is_empty = exp.ArraySize(this=expression.this).eq(0)
    4114            return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty)))
    4115
    4116        from sqlglot.dialects import Dialect
    4117
    4118        # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect
    4119        if self.dialect.__class__ != Dialect:
    4120            self.unsupported("ARRAY_ANY is unsupported")
    4121
    4122        return self.function_fallback_sql(expression)
    4123
    4124    def struct_sql(self, expression: exp.Struct) -> str:
    4125        expression.set(
    4126            "expressions",
    4127            [
    4128                exp.alias_(e.expression, e.name if e.this.is_string else e.this)
    4129                if isinstance(e, exp.PropertyEQ)
    4130                else e
    4131                for e in expression.expressions
    4132            ],
    4133        )
    4134
    4135        return self.function_fallback_sql(expression)
    4136
    4137    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
    4138        low = self.sql(expression, "this")
    4139        high = self.sql(expression, "expression")
    4140
    4141        return f"{low} TO {high}"
    4142
    4143    def truncatetable_sql(self, expression: exp.TruncateTable) -> str:
    4144        target = "DATABASE" if expression.args.get("is_database") else "TABLE"
    4145        tables = f" {self.expressions(expression)}"
    4146
    4147        exists = " IF EXISTS" if expression.args.get("exists") else ""
    4148
    4149        on_cluster = self.sql(expression, "cluster")
    4150        on_cluster = f" {on_cluster}" if on_cluster else ""
    4151
    4152        identity = self.sql(expression, "identity")
    4153        identity = f" {identity} IDENTITY" if identity else ""
    4154
    4155        option = self.sql(expression, "option")
    4156        option = f" {option}" if option else ""
    4157
    4158        partition = self.sql(expression, "partition")
    4159        partition = f" {partition}" if partition else ""
    4160
    4161        return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"
    4162
    4163    # This transpiles T-SQL's CONVERT function
    4164    # https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16
    4165    def convert_sql(self, expression: exp.Convert) -> str:
    4166        to = expression.this
    4167        value = expression.expression
    4168        style = expression.args.get("style")
    4169        safe = expression.args.get("safe")
    4170        strict = expression.args.get("strict")
    4171
    4172        if not to or not value:
    4173            return ""
    4174
    4175        # Retrieve length of datatype and override to default if not specified
    4176        if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    4177            to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
    4178
    4179        transformed: t.Optional[exp.Expression] = None
    4180        cast = exp.Cast if strict else exp.TryCast
    4181
    4182        # Check whether a conversion with format (T-SQL calls this 'style') is applicable
    4183        if isinstance(style, exp.Literal) and style.is_int:
    4184            from sqlglot.dialects.tsql import TSQL
    4185
    4186            style_value = style.name
    4187            converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value)
    4188            if not converted_style:
    4189                self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}")
    4190
    4191            fmt = exp.Literal.string(converted_style)
    4192
    4193            if to.this == exp.DataType.Type.DATE:
    4194                transformed = exp.StrToDate(this=value, format=fmt)
    4195            elif to.this in (exp.DataType.Type.DATETIME, exp.DataType.Type.DATETIME2):
    4196                transformed = exp.StrToTime(this=value, format=fmt)
    4197            elif to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    4198                transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe)
    4199            elif to.this == exp.DataType.Type.TEXT:
    4200                transformed = exp.TimeToStr(this=value, format=fmt)
    4201
    4202        if not transformed:
    4203            transformed = cast(this=value, to=to, safe=safe)
    4204
    4205        return self.sql(transformed)
    4206
    4207    def _jsonpathkey_sql(self, expression: exp.JSONPathKey) -> str:
    4208        this = expression.this
    4209        if isinstance(this, exp.JSONPathWildcard):
    4210            this = self.json_path_part(this)
    4211            return f".{this}" if this else ""
    4212
    4213        if exp.SAFE_IDENTIFIER_RE.match(this):
    4214            return f".{this}"
    4215
    4216        this = self.json_path_part(this)
    4217        return (
    4218            f"[{this}]"
    4219            if self._quote_json_path_key_using_brackets and self.JSON_PATH_BRACKETED_KEY_SUPPORTED
    4220            else f".{this}"
    4221        )
    4222
    4223    def _jsonpathsubscript_sql(self, expression: exp.JSONPathSubscript) -> str:
    4224        this = self.json_path_part(expression.this)
    4225        return f"[{this}]" if this else ""
    4226
    4227    def _simplify_unless_literal(self, expression: E) -> E:
    4228        if not isinstance(expression, exp.Literal):
    4229            from sqlglot.optimizer.simplify import simplify
    4230
    4231            expression = simplify(expression, dialect=self.dialect)
    4232
    4233        return expression
    4234
    4235    def _embed_ignore_nulls(self, expression: exp.IgnoreNulls | exp.RespectNulls, text: str) -> str:
    4236        if self.IGNORE_NULLS_IN_FUNC and not expression.meta.get("inline"):
    4237            # The first modifier here will be the one closest to the AggFunc's arg
    4238            mods = sorted(
    4239                expression.find_all(exp.HavingMax, exp.Order, exp.Limit),
    4240                key=lambda x: 0
    4241                if isinstance(x, exp.HavingMax)
    4242                else (1 if isinstance(x, exp.Order) else 2),
    4243            )
    4244
    4245            if mods:
    4246                mod = mods[0]
    4247                this = expression.__class__(this=mod.this.copy())
    4248                this.meta["inline"] = True
    4249                mod.this.replace(this)
    4250                return self.sql(expression.this)
    4251
    4252            agg_func = expression.find(exp.AggFunc)
    4253
    4254            if agg_func:
    4255                return self.sql(agg_func)[:-1] + f" {text})"
    4256
    4257        return f"{self.sql(expression, 'this')} {text}"
    4258
    4259    def _replace_line_breaks(self, string: str) -> str:
    4260        """We don't want to extra indent line breaks so we temporarily replace them with sentinels."""
    4261        if self.pretty:
    4262            return string.replace("\n", self.SENTINEL_LINE_BREAK)
    4263        return string
    4264
    4265    def copyparameter_sql(self, expression: exp.CopyParameter) -> str:
    4266        option = self.sql(expression, "this")
    4267
    4268        if expression.expressions:
    4269            upper = option.upper()
    4270
    4271            # Snowflake FILE_FORMAT options are separated by whitespace
    4272            sep = " " if upper == "FILE_FORMAT" else ", "
    4273
    4274            # Databricks copy/format options do not set their list of values with EQ
    4275            op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = "
    4276            values = self.expressions(expression, flat=True, sep=sep)
    4277            return f"{option}{op}({values})"
    4278
    4279        value = self.sql(expression, "expression")
    4280
    4281        if not value:
    4282            return option
    4283
    4284        op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " "
    4285
    4286        return f"{option}{op}{value}"
    4287
    4288    def credentials_sql(self, expression: exp.Credentials) -> str:
    4289        cred_expr = expression.args.get("credentials")
    4290        if isinstance(cred_expr, exp.Literal):
    4291            # Redshift case: CREDENTIALS <string>
    4292            credentials = self.sql(expression, "credentials")
    4293            credentials = f"CREDENTIALS {credentials}" if credentials else ""
    4294        else:
    4295            # Snowflake case: CREDENTIALS = (...)
    4296            credentials = self.expressions(expression, key="credentials", flat=True, sep=" ")
    4297            credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else ""
    4298
    4299        storage = self.sql(expression, "storage")
    4300        storage = f"STORAGE_INTEGRATION = {storage}" if storage else ""
    4301
    4302        encryption = self.expressions(expression, key="encryption", flat=True, sep=" ")
    4303        encryption = f" ENCRYPTION = ({encryption})" if encryption else ""
    4304
    4305        iam_role = self.sql(expression, "iam_role")
    4306        iam_role = f"IAM_ROLE {iam_role}" if iam_role else ""
    4307
    4308        region = self.sql(expression, "region")
    4309        region = f" REGION {region}" if region else ""
    4310
    4311        return f"{credentials}{storage}{encryption}{iam_role}{region}"
    4312
    4313    def copy_sql(self, expression: exp.Copy) -> str:
    4314        this = self.sql(expression, "this")
    4315        this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}"
    4316
    4317        credentials = self.sql(expression, "credentials")
    4318        credentials = self.seg(credentials) if credentials else ""
    4319        kind = self.seg("FROM" if expression.args.get("kind") else "TO")
    4320        files = self.expressions(expression, key="files", flat=True)
    4321
    4322        sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " "
    4323        params = self.expressions(
    4324            expression,
    4325            key="params",
    4326            sep=sep,
    4327            new_line=True,
    4328            skip_last=True,
    4329            skip_first=True,
    4330            indent=self.COPY_PARAMS_ARE_WRAPPED,
    4331        )
    4332
    4333        if params:
    4334            if self.COPY_PARAMS_ARE_WRAPPED:
    4335                params = f" WITH ({params})"
    4336            elif not self.pretty:
    4337                params = f" {params}"
    4338
    4339        return f"COPY{this}{kind} {files}{credentials}{params}"
    4340
    4341    def semicolon_sql(self, expression: exp.Semicolon) -> str:
    4342        return ""
    4343
    4344    def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str:
    4345        on_sql = "ON" if expression.args.get("on") else "OFF"
    4346        filter_col: t.Optional[str] = self.sql(expression, "filter_column")
    4347        filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None
    4348        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    4349        retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None
    4350
    4351        if filter_col or retention_period:
    4352            on_sql = self.func("ON", filter_col, retention_period)
    4353
    4354        return f"DATA_DELETION={on_sql}"
    4355
    4356    def maskingpolicycolumnconstraint_sql(
    4357        self, expression: exp.MaskingPolicyColumnConstraint
    4358    ) -> str:
    4359        this = self.sql(expression, "this")
    4360        expressions = self.expressions(expression, flat=True)
    4361        expressions = f" USING ({expressions})" if expressions else ""
    4362        return f"MASKING POLICY {this}{expressions}"
    4363
    4364    def gapfill_sql(self, expression: exp.GapFill) -> str:
    4365        this = self.sql(expression, "this")
    4366        this = f"TABLE {this}"
    4367        return self.func("GAP_FILL", this, *[v for k, v in expression.args.items() if k != "this"])
    4368
    4369    def scope_resolution(self, rhs: str, scope_name: str) -> str:
    4370        return self.func("SCOPE_RESOLUTION", scope_name or None, rhs)
    4371
    4372    def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str:
    4373        this = self.sql(expression, "this")
    4374        expr = expression.expression
    4375
    4376        if isinstance(expr, exp.Func):
    4377            # T-SQL's CLR functions are case sensitive
    4378            expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})"
    4379        else:
    4380            expr = self.sql(expression, "expression")
    4381
    4382        return self.scope_resolution(expr, this)
    4383
    4384    def parsejson_sql(self, expression: exp.ParseJSON) -> str:
    4385        if self.PARSE_JSON_NAME is None:
    4386            return self.sql(expression.this)
    4387
    4388        return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression)
    4389
    4390    def rand_sql(self, expression: exp.Rand) -> str:
    4391        lower = self.sql(expression, "lower")
    4392        upper = self.sql(expression, "upper")
    4393
    4394        if lower and upper:
    4395            return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}"
    4396        return self.func("RAND", expression.this)
    4397
    4398    def changes_sql(self, expression: exp.Changes) -> str:
    4399        information = self.sql(expression, "information")
    4400        information = f"INFORMATION => {information}"
    4401        at_before = self.sql(expression, "at_before")
    4402        at_before = f"{self.seg('')}{at_before}" if at_before else ""
    4403        end = self.sql(expression, "end")
    4404        end = f"{self.seg('')}{end}" if end else ""
    4405
    4406        return f"CHANGES ({information}){at_before}{end}"
    4407
    4408    def pad_sql(self, expression: exp.Pad) -> str:
    4409        prefix = "L" if expression.args.get("is_left") else "R"
    4410
    4411        fill_pattern = self.sql(expression, "fill_pattern") or None
    4412        if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED:
    4413            fill_pattern = "' '"
    4414
    4415        return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)
    4416
    4417    def summarize_sql(self, expression: exp.Summarize) -> str:
    4418        table = " TABLE" if expression.args.get("table") else ""
    4419        return f"SUMMARIZE{table} {self.sql(expression.this)}"
    4420
    4421    def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str:
    4422        generate_series = exp.GenerateSeries(**expression.args)
    4423
    4424        parent = expression.parent
    4425        if isinstance(parent, (exp.Alias, exp.TableAlias)):
    4426            parent = parent.parent
    4427
    4428        if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)):
    4429            return self.sql(exp.Unnest(expressions=[generate_series]))
    4430
    4431        if isinstance(parent, exp.Select):
    4432            self.unsupported("GenerateSeries projection unnesting is not supported.")
    4433
    4434        return self.sql(generate_series)
    4435
    4436    def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str:
    4437        exprs = expression.expressions
    4438        if not self.ARRAY_CONCAT_IS_VAR_LEN:
    4439            rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs)
    4440        else:
    4441            rhs = self.expressions(expression)
    4442
    4443        return self.func(name, expression.this, rhs or None)
    4444
    4445    def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str:
    4446        if self.SUPPORTS_CONVERT_TIMEZONE:
    4447            return self.function_fallback_sql(expression)
    4448
    4449        source_tz = expression.args.get("source_tz")
    4450        target_tz = expression.args.get("target_tz")
    4451        timestamp = expression.args.get("timestamp")
    4452
    4453        if source_tz and timestamp:
    4454            timestamp = exp.AtTimeZone(
    4455                this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz
    4456            )
    4457
    4458        expr = exp.AtTimeZone(this=timestamp, zone=target_tz)
    4459
    4460        return self.sql(expr)
    4461
    4462    def json_sql(self, expression: exp.JSON) -> str:
    4463        this = self.sql(expression, "this")
    4464        this = f" {this}" if this else ""
    4465
    4466        _with = expression.args.get("with")
    4467
    4468        if _with is None:
    4469            with_sql = ""
    4470        elif not _with:
    4471            with_sql = " WITHOUT"
    4472        else:
    4473            with_sql = " WITH"
    4474
    4475        unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else ""
    4476
    4477        return f"JSON{this}{with_sql}{unique_sql}"
    4478
    4479    def jsonvalue_sql(self, expression: exp.JSONValue) -> str:
    4480        def _generate_on_options(arg: t.Any) -> str:
    4481            return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}"
    4482
    4483        path = self.sql(expression, "path")
    4484        returning = self.sql(expression, "returning")
    4485        returning = f" RETURNING {returning}" if returning else ""
    4486
    4487        on_condition = self.sql(expression, "on_condition")
    4488        on_condition = f" {on_condition}" if on_condition else ""
    4489
    4490        return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}")
    4491
    4492    def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str:
    4493        else_ = "ELSE " if expression.args.get("else_") else ""
    4494        condition = self.sql(expression, "expression")
    4495        condition = f"WHEN {condition} THEN " if condition else else_
    4496        insert = self.sql(expression, "this")[len("INSERT") :].strip()
    4497        return f"{condition}{insert}"
    4498
    4499    def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str:
    4500        kind = self.sql(expression, "kind")
    4501        expressions = self.seg(self.expressions(expression, sep=" "))
    4502        res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}"
    4503        return res
    4504
    4505    def oncondition_sql(self, expression: exp.OnCondition) -> str:
    4506        # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR"
    4507        empty = expression.args.get("empty")
    4508        empty = (
    4509            f"DEFAULT {empty} ON EMPTY"
    4510            if isinstance(empty, exp.Expression)
    4511            else self.sql(expression, "empty")
    4512        )
    4513
    4514        error = expression.args.get("error")
    4515        error = (
    4516            f"DEFAULT {error} ON ERROR"
    4517            if isinstance(error, exp.Expression)
    4518            else self.sql(expression, "error")
    4519        )
    4520
    4521        if error and empty:
    4522            error = (
    4523                f"{empty} {error}"
    4524                if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR
    4525                else f"{error} {empty}"
    4526            )
    4527            empty = ""
    4528
    4529        null = self.sql(expression, "null")
    4530
    4531        return f"{empty}{error}{null}"
    4532
    4533    def jsonextractquote_sql(self, expression: exp.JSONExtractQuote) -> str:
    4534        scalar = " ON SCALAR STRING" if expression.args.get("scalar") else ""
    4535        return f"{self.sql(expression, 'option')} QUOTES{scalar}"
    4536
    4537    def jsonexists_sql(self, expression: exp.JSONExists) -> str:
    4538        this = self.sql(expression, "this")
    4539        path = self.sql(expression, "path")
    4540
    4541        passing = self.expressions(expression, "passing")
    4542        passing = f" PASSING {passing}" if passing else ""
    4543
    4544        on_condition = self.sql(expression, "on_condition")
    4545        on_condition = f" {on_condition}" if on_condition else ""
    4546
    4547        path = f"{path}{passing}{on_condition}"
    4548
    4549        return self.func("JSON_EXISTS", this, path)
    4550
    4551    def arrayagg_sql(self, expression: exp.ArrayAgg) -> str:
    4552        array_agg = self.function_fallback_sql(expression)
    4553
    4554        # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls
    4555        # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB)
    4556        if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"):
    4557            parent = expression.parent
    4558            if isinstance(parent, exp.Filter):
    4559                parent_cond = parent.expression.this
    4560                parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_()))
    4561            else:
    4562                this = expression.this
    4563                # Do not add the filter if the input is not a column (e.g. literal, struct etc)
    4564                if this.find(exp.Column):
    4565                    # DISTINCT is already present in the agg function, do not propagate it to FILTER as well
    4566                    this_sql = (
    4567                        self.expressions(this)
    4568                        if isinstance(this, exp.Distinct)
    4569                        else self.sql(expression, "this")
    4570                    )
    4571
    4572                    array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)"
    4573
    4574        return array_agg
    4575
    4576    def apply_sql(self, expression: exp.Apply) -> str:
    4577        this = self.sql(expression, "this")
    4578        expr = self.sql(expression, "expression")
    4579
    4580        return f"{this} APPLY({expr})"
    4581
    4582    def grant_sql(self, expression: exp.Grant) -> str:
    4583        privileges_sql = self.expressions(expression, key="privileges", flat=True)
    4584
    4585        kind = self.sql(expression, "kind")
    4586        kind = f" {kind}" if kind else ""
    4587
    4588        securable = self.sql(expression, "securable")
    4589        securable = f" {securable}" if securable else ""
    4590
    4591        principals = self.expressions(expression, key="principals", flat=True)
    4592
    4593        grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else ""
    4594
    4595        return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}"
    4596
    4597    def grantprivilege_sql(self, expression: exp.GrantPrivilege):
    4598        this = self.sql(expression, "this")
    4599        columns = self.expressions(expression, flat=True)
    4600        columns = f"({columns})" if columns else ""
    4601
    4602        return f"{this}{columns}"
    4603
    4604    def grantprincipal_sql(self, expression: exp.GrantPrincipal):
    4605        this = self.sql(expression, "this")
    4606
    4607        kind = self.sql(expression, "kind")
    4608        kind = f"{kind} " if kind else ""
    4609
    4610        return f"{kind}{this}"
    4611
    4612    def columns_sql(self, expression: exp.Columns):
    4613        func = self.function_fallback_sql(expression)
    4614        if expression.args.get("unpack"):
    4615            func = f"*{func}"
    4616
    4617        return func
    4618
    4619    def overlay_sql(self, expression: exp.Overlay):
    4620        this = self.sql(expression, "this")
    4621        expr = self.sql(expression, "expression")
    4622        from_sql = self.sql(expression, "from")
    4623        for_sql = self.sql(expression, "for")
    4624        for_sql = f" FOR {for_sql}" if for_sql else ""
    4625
    4626        return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})"
    4627
    4628    @unsupported_args("format")
    4629    def todouble_sql(self, expression: exp.ToDouble) -> str:
    4630        return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    4631
    4632    def string_sql(self, expression: exp.String) -> str:
    4633        this = expression.this
    4634        zone = expression.args.get("zone")
    4635
    4636        if zone:
    4637            # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>)
    4638            # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC
    4639            # set for source_tz to transpile the time conversion before the STRING cast
    4640            this = exp.ConvertTimezone(
    4641                source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this
    4642            )
    4643
    4644        return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR))
    4645
    4646    def median_sql(self, expression: exp.Median):
    4647        if not self.SUPPORTS_MEDIAN:
    4648            return self.sql(
    4649                exp.PercentileCont(this=expression.this, expression=exp.Literal.number(0.5))
    4650            )
    4651
    4652        return self.function_fallback_sql(expression)
    4653
    4654    def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str:
    4655        filler = self.sql(expression, "this")
    4656        filler = f" {filler}" if filler else ""
    4657        with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT"
    4658        return f"TRUNCATE{filler} {with_count}"
    4659
    4660    def unixseconds_sql(self, expression: exp.UnixSeconds) -> str:
    4661        if self.SUPPORTS_UNIX_SECONDS:
    4662            return self.function_fallback_sql(expression)
    4663
    4664        start_ts = exp.cast(
    4665            exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ
    4666        )
    4667
    4668        return self.sql(
    4669            exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS"))
    4670        )
    4671
    4672    def arraysize_sql(self, expression: exp.ArraySize) -> str:
    4673        dim = expression.expression
    4674
    4675        # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension)
    4676        if dim and self.ARRAY_SIZE_DIM_REQUIRED is None:
    4677            if not (dim.is_int and dim.name == "1"):
    4678                self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH")
    4679            dim = None
    4680
    4681        # If dimension is required but not specified, default initialize it
    4682        if self.ARRAY_SIZE_DIM_REQUIRED and not dim:
    4683            dim = exp.Literal.number(1)
    4684
    4685        return self.func(self.ARRAY_SIZE_NAME, expression.this, dim)
    4686
    4687    def attach_sql(self, expression: exp.Attach) -> str:
    4688        this = self.sql(expression, "this")
    4689        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
    4690        expressions = self.expressions(expression)
    4691        expressions = f" ({expressions})" if expressions else ""
    4692
    4693        return f"ATTACH{exists_sql} {this}{expressions}"
    4694
    4695    def detach_sql(self, expression: exp.Detach) -> str:
    4696        this = self.sql(expression, "this")
    4697        exists_sql = " IF EXISTS" if expression.args.get("exists") else ""
    4698
    4699        return f"DETACH{exists_sql} {this}"
    4700
    4701    def attachoption_sql(self, expression: exp.AttachOption) -> str:
    4702        this = self.sql(expression, "this")
    4703        value = self.sql(expression, "expression")
    4704        value = f" {value}" if value else ""
    4705        return f"{this}{value}"
    4706
    4707    def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str:
    4708        this_sql = self.sql(expression, "this")
    4709        if isinstance(expression.this, exp.Table):
    4710            this_sql = f"TABLE {this_sql}"
    4711
    4712        return self.func(
    4713            "FEATURES_AT_TIME",
    4714            this_sql,
    4715            expression.args.get("time"),
    4716            expression.args.get("num_rows"),
    4717            expression.args.get("ignore_feature_nulls"),
    4718        )
    4719
    4720    def watermarkcolumnconstraint_sql(self, expression: exp.WatermarkColumnConstraint) -> str:
    4721        return (
    4722            f"WATERMARK FOR {self.sql(expression, 'this')} AS {self.sql(expression, 'expression')}"
    4723        )
    4724
    4725    def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str:
    4726        encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE"
    4727        encode = f"{encode} {self.sql(expression, 'this')}"
    4728
    4729        properties = expression.args.get("properties")
    4730        if properties:
    4731            encode = f"{encode} {self.properties(properties)}"
    4732
    4733        return encode
    4734
    4735    def includeproperty_sql(self, expression: exp.IncludeProperty) -> str:
    4736        this = self.sql(expression, "this")
    4737        include = f"INCLUDE {this}"
    4738
    4739        column_def = self.sql(expression, "column_def")
    4740        if column_def:
    4741            include = f"{include} {column_def}"
    4742
    4743        alias = self.sql(expression, "alias")
    4744        if alias:
    4745            include = f"{include} AS {alias}"
    4746
    4747        return include
    4748
    4749    def xmlelement_sql(self, expression: exp.XMLElement) -> str:
    4750        name = f"NAME {self.sql(expression, 'this')}"
    4751        return self.func("XMLELEMENT", name, *expression.expressions)
    4752
    4753    def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str:
    4754        partitions = self.expressions(expression, "partition_expressions")
    4755        create = self.expressions(expression, "create_expressions")
    4756        return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}"
    4757
    4758    def partitionbyrangepropertydynamic_sql(
    4759        self, expression: exp.PartitionByRangePropertyDynamic
    4760    ) -> str:
    4761        start = self.sql(expression, "start")
    4762        end = self.sql(expression, "end")
    4763
    4764        every = expression.args["every"]
    4765        if isinstance(every, exp.Interval) and every.this.is_string:
    4766            every.this.replace(exp.Literal.number(every.name))
    4767
    4768        return f"START {self.wrap(start)} END {self.wrap(end)} EVERY {self.wrap(self.sql(every))}"
    4769
    4770    def unpivotcolumns_sql(self, expression: exp.UnpivotColumns) -> str:
    4771        name = self.sql(expression, "this")
    4772        values = self.expressions(expression, flat=True)
    4773
    4774        return f"NAME {name} VALUE {values}"
    4775
    4776    def analyzesample_sql(self, expression: exp.AnalyzeSample) -> str:
    4777        kind = self.sql(expression, "kind")
    4778        sample = self.sql(expression, "sample")
    4779        return f"SAMPLE {sample} {kind}"
    4780
    4781    def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str:
    4782        kind = self.sql(expression, "kind")
    4783        option = self.sql(expression, "option")
    4784        option = f" {option}" if option else ""
    4785        this = self.sql(expression, "this")
    4786        this = f" {this}" if this else ""
    4787        columns = self.expressions(expression)
    4788        columns = f" {columns}" if columns else ""
    4789        return f"{kind}{option} STATISTICS{this}{columns}"
    4790
    4791    def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str:
    4792        this = self.sql(expression, "this")
    4793        columns = self.expressions(expression)
    4794        inner_expression = self.sql(expression, "expression")
    4795        inner_expression = f" {inner_expression}" if inner_expression else ""
    4796        update_options = self.sql(expression, "update_options")
    4797        update_options = f" {update_options} UPDATE" if update_options else ""
    4798        return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}"
    4799
    4800    def analyzedelete_sql(self, expression: exp.AnalyzeDelete) -> str:
    4801        kind = self.sql(expression, "kind")
    4802        kind = f" {kind}" if kind else ""
    4803        return f"DELETE{kind} STATISTICS"
    4804
    4805    def analyzelistchainedrows_sql(self, expression: exp.AnalyzeListChainedRows) -> str:
    4806        inner_expression = self.sql(expression, "expression")
    4807        return f"LIST CHAINED ROWS{inner_expression}"
    4808
    4809    def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str:
    4810        kind = self.sql(expression, "kind")
    4811        this = self.sql(expression, "this")
    4812        this = f" {this}" if this else ""
    4813        inner_expression = self.sql(expression, "expression")
    4814        return f"VALIDATE {kind}{this}{inner_expression}"
    4815
    4816    def analyze_sql(self, expression: exp.Analyze) -> str:
    4817        options = self.expressions(expression, key="options", sep=" ")
    4818        options = f" {options}" if options else ""
    4819        kind = self.sql(expression, "kind")
    4820        kind = f" {kind}" if kind else ""
    4821        this = self.sql(expression, "this")
    4822        this = f" {this}" if this else ""
    4823        mode = self.sql(expression, "mode")
    4824        mode = f" {mode}" if mode else ""
    4825        properties = self.sql(expression, "properties")
    4826        properties = f" {properties}" if properties else ""
    4827        partition = self.sql(expression, "partition")
    4828        partition = f" {partition}" if partition else ""
    4829        inner_expression = self.sql(expression, "expression")
    4830        inner_expression = f" {inner_expression}" if inner_expression else ""
    4831        return f"ANALYZE{options}{kind}{this}{partition}{mode}{inner_expression}{properties}"
    4832
    4833    def xmltable_sql(self, expression: exp.XMLTable) -> str:
    4834        this = self.sql(expression, "this")
    4835        namespaces = self.expressions(expression, key="namespaces")
    4836        namespaces = f"XMLNAMESPACES({namespaces}), " if namespaces else ""
    4837        passing = self.expressions(expression, key="passing")
    4838        passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else ""
    4839        columns = self.expressions(expression, key="columns")
    4840        columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else ""
    4841        by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else ""
    4842        return f"XMLTABLE({self.sep('')}{self.indent(namespaces + this + passing + by_ref + columns)}{self.seg(')', sep='')}"
    4843
    4844    def xmlnamespace_sql(self, expression: exp.XMLNamespace) -> str:
    4845        this = self.sql(expression, "this")
    4846        return this if isinstance(expression.this, exp.Alias) else f"DEFAULT {this}"
    4847
    4848    def export_sql(self, expression: exp.Export) -> str:
    4849        this = self.sql(expression, "this")
    4850        connection = self.sql(expression, "connection")
    4851        connection = f"WITH CONNECTION {connection} " if connection else ""
    4852        options = self.sql(expression, "options")
    4853        return f"EXPORT DATA {connection}{options} AS {this}"
    4854
    4855    def declare_sql(self, expression: exp.Declare) -> str:
    4856        return f"DECLARE {self.expressions(expression, flat=True)}"
    4857
    4858    def declareitem_sql(self, expression: exp.DeclareItem) -> str:
    4859        variable = self.sql(expression, "this")
    4860        default = self.sql(expression, "default")
    4861        default = f" = {default}" if default else ""
    4862
    4863        kind = self.sql(expression, "kind")
    4864        if isinstance(expression.args.get("kind"), exp.Schema):
    4865            kind = f"TABLE {kind}"
    4866
    4867        return f"{variable} AS {kind}{default}"
    4868
    4869    def recursivewithsearch_sql(self, expression: exp.RecursiveWithSearch) -> str:
    4870        kind = self.sql(expression, "kind")
    4871        this = self.sql(expression, "this")
    4872        set = self.sql(expression, "expression")
    4873        using = self.sql(expression, "using")
    4874        using = f" USING {using}" if using else ""
    4875
    4876        kind_sql = kind if kind == "CYCLE" else f"SEARCH {kind} FIRST BY"
    4877
    4878        return f"{kind_sql} {this} SET {set}{using}"
    4879
    4880    def parameterizedagg_sql(self, expression: exp.ParameterizedAgg) -> str:
    4881        params = self.expressions(expression, key="params", flat=True)
    4882        return self.func(expression.name, *expression.expressions) + f"({params})"
    4883
    4884    def anonymousaggfunc_sql(self, expression: exp.AnonymousAggFunc) -> str:
    4885        return self.func(expression.name, *expression.expressions)
    4886
    4887    def combinedaggfunc_sql(self, expression: exp.CombinedAggFunc) -> str:
    4888        return self.anonymousaggfunc_sql(expression)
    4889
    4890    def combinedparameterizedagg_sql(self, expression: exp.CombinedParameterizedAgg) -> str:
    4891        return self.parameterizedagg_sql(expression)
    4892
    4893    def show_sql(self, expression: exp.Show) -> str:
    4894        self.unsupported("Unsupported SHOW statement")
    4895        return ""
    4896
    4897    def put_sql(self, expression: exp.Put) -> str:
    4898        props = expression.args.get("properties")
    4899        props_sql = self.properties(props, prefix=" ", sep=" ", wrapped=False) if props else ""
    4900        this = self.sql(expression, "this")
    4901        target = self.sql(expression, "target")
    4902        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

    683    def __init__(
    684        self,
    685        pretty: t.Optional[bool] = None,
    686        identify: str | bool = False,
    687        normalize: bool = False,
    688        pad: int = 2,
    689        indent: int = 2,
    690        normalize_functions: t.Optional[str | bool] = None,
    691        unsupported_level: ErrorLevel = ErrorLevel.WARN,
    692        max_unsupported: int = 3,
    693        leading_comma: bool = False,
    694        max_text_width: int = 80,
    695        comments: bool = True,
    696        dialect: DialectType = None,
    697    ):
    698        import sqlglot
    699        from sqlglot.dialects import Dialect
    700
    701        self.pretty = pretty if pretty is not None else sqlglot.pretty
    702        self.identify = identify
    703        self.normalize = normalize
    704        self.pad = pad
    705        self._indent = indent
    706        self.unsupported_level = unsupported_level
    707        self.max_unsupported = max_unsupported
    708        self.leading_comma = leading_comma
    709        self.max_text_width = max_text_width
    710        self.comments = comments
    711        self.dialect = Dialect.get_or_raise(dialect)
    712
    713        # This is both a Dialect property and a Generator argument, so we prioritize the latter
    714        self.normalize_functions = (
    715            self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions
    716        )
    717
    718        self.unsupported_messages: t.List[str] = []
    719        self._escaped_quote_end: str = (
    720            self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END
    721        )
    722        self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2
    723
    724        self._next_name = name_sequence("_t")
    725
    726        self._identifier_start = self.dialect.IDENTIFIER_START
    727        self._identifier_end = self.dialect.IDENTIFIER_END
    728
    729        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.CredentialsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DateFormatColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DefaultColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DynamicProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EmptyProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EncodeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.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.UsingTemplateProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UsingData'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Uuid'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VarMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ViewAttributeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithProcedureOptions'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithSchemaBindingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithOperator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ForceProperty'>: <function Generator.<lambda>>}
NULL_ORDERING_SUPPORTED: Optional[bool] = True
IGNORE_NULLS_IN_FUNC = False
LOCKING_READS_SUPPORTED = False
EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = True
WRAP_DERIVED_VALUES = True
CREATE_FUNCTION_RETURN_AS = True
MATCHED_BY_SOURCE = True
SINGLE_STRING_INTERVAL = False
INTERVAL_ALLOWS_PLURAL_FORM = True
LIMIT_FETCH = 'ALL'
LIMIT_ONLY_LITERALS = False
RENAME_TABLE_WITH_DB = True
GROUPINGS_SEP = ','
INDEX_ON = 'ON'
JOIN_HINTS = True
TABLE_HINTS = True
QUERY_HINTS = True
QUERY_HINT_SEP = ', '
IS_BOOL_ALLOWED = True
DUPLICATE_KEY_UPDATE_WITH_SET = True
LIMIT_IS_TOP = False
RETURNING_END = True
EXTRACT_ALLOWS_QUOTES = True
TZ_TO_WITH_TIME_ZONE = False
NVL2_SUPPORTED = True
SELECT_KINDS: Tuple[str, ...] = ('STRUCT', 'VALUE')
VALUES_AS_TABLE = True
ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = True
UNNEST_WITH_ORDINALITY = True
AGGREGATE_FILTER_SUPPORTED = True
SEMI_ANTI_JOIN_WITH_SIDE = True
COMPUTED_COLUMN_WITH_TYPE = True
SUPPORTS_TABLE_COPY = True
TABLESAMPLE_REQUIRES_PARENS = True
TABLESAMPLE_SIZE_IS_ROWS = True
TABLESAMPLE_KEYWORDS = 'TABLESAMPLE'
TABLESAMPLE_WITH_METHOD = True
TABLESAMPLE_SEED_KEYWORD = 'SEED'
COLLATE_IS_FUNC = False
DATA_TYPE_SPECIFIERS_ALLOWED = False
ENSURE_BOOLS = False
CTE_RECURSIVE_KEYWORD_REQUIRED = True
SUPPORTS_SINGLE_ARG_CONCAT = True
LAST_DAY_SUPPORTS_DATE_PART = True
SUPPORTS_TABLE_ALIAS_COLUMNS = True
UNPIVOT_ALIASES_ARE_IDENTIFIERS = True
JSON_KEY_VALUE_PAIR_SEP = ':'
INSERT_OVERWRITE = ' OVERWRITE TABLE'
SUPPORTS_SELECT_INTO = False
SUPPORTS_UNLOGGED_TABLES = False
SUPPORTS_CREATE_TABLE_LIKE = True
LIKE_PROPERTY_INSIDE_SCHEMA = False
MULTI_ARG_DISTINCT = True
JSON_TYPE_REQUIRED_FOR_EXTRACTION = False
JSON_PATH_BRACKETED_KEY_SUPPORTED = True
JSON_PATH_SINGLE_QUOTE_ESCAPE = False
SUPPORTED_JSON_PATH_PARTS = {<class 'sqlglot.expressions.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.UsingTemplateProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ViewAttributeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.VolatileProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.WithDataProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.WithProcedureOptions'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.WithSchemaBindingProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.WithSystemVersioningProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ForceProperty'>: <Location.POST_CREATE: 'POST_CREATE'>}
RESERVED_KEYWORDS: Set[str] = set()
WITH_SEPARATED_COMMENTS: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Command'>, <class 'sqlglot.expressions.Create'>, <class 'sqlglot.expressions.Describe'>, <class 'sqlglot.expressions.Delete'>, <class 'sqlglot.expressions.Drop'>, <class 'sqlglot.expressions.From'>, <class 'sqlglot.expressions.Insert'>, <class 'sqlglot.expressions.Join'>, <class 'sqlglot.expressions.MultitableInserts'>, <class 'sqlglot.expressions.Select'>, <class 'sqlglot.expressions.SetOperation'>, <class 'sqlglot.expressions.Update'>, <class 'sqlglot.expressions.Where'>, <class 'sqlglot.expressions.With'>)
EXCLUDE_COMMENTS: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Binary'>, <class 'sqlglot.expressions.SetOperation'>)
UNWRAPPED_INTERVAL_VALUES: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Column'>, <class 'sqlglot.expressions.Literal'>, <class 'sqlglot.expressions.Neg'>, <class 'sqlglot.expressions.Paren'>)
PARAMETERIZABLE_TEXT_TYPES = {<Type.NVARCHAR: 'NVARCHAR'>, <Type.CHAR: 'CHAR'>, <Type.NCHAR: 'NCHAR'>, <Type.VARCHAR: 'VARCHAR'>}
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

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

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

Apply generic preprocessing transformations to a given expression.

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

    787    def unsupported(self, message: str) -> None:
    788        if self.unsupported_level == ErrorLevel.IMMEDIATE:
    789            raise UnsupportedError(message)
    790        self.unsupported_messages.append(message)

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

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

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

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

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

    798    def pad_comment(self, comment: str) -> str:
    799        comment = " " + comment if comment[0].strip() else comment
    800        comment = comment + " " if comment[-1].strip() else comment
    801        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

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

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

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

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

    849    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
    850        original = self.identify
    851        self.identify = False
    852        result = func(*args, **kwargs)
    853        self.identify = original
    854        return result

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

    856    def normalize_func(self, name: str) -> str:
    857        if self.normalize_functions == "upper" or self.normalize_functions is True:
    858            return name.upper()
    859        if self.normalize_functions == "lower":
    860            return name.lower()
    861        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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    966    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
    967        this = self.sql(expression, "this")
    968        this = f" {this}" if this else ""
    969        position = self.sql(expression, "position")
    970        return f"{position}{this}"

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

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

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

    987    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
    988        this = self.sql(expression, "this")
    989        kind_sql = self.sql(expression, "kind").strip()
    990        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql

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

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

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

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

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

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

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

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

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

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

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

    1053    def periodforsystemtimeconstraint_sql(
    1054        self, expression: exp.PeriodForSystemTimeConstraint
    1055    ) -> str:
    1056        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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    1237    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
    1238        with_ = self.sql(expression, "with")
    1239        if with_:
    1240            sql = f"{with_}{self.sep()}{sql}"
    1241        return sql

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

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

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

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

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

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

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

    1284    def bitstring_sql(self, expression: exp.BitString) -> str:
    1285        this = self.sql(expression, "this")
    1286        if self.dialect.BIT_START:
    1287            return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}"
    1288        return f"{int(this, 2)}"

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

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

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

    1315    def bytestring_sql(self, expression: exp.ByteString) -> str:
    1316        this = self.sql(expression, "this")
    1317        if self.dialect.BYTE_START:
    1318            return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}"
    1319        return this

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

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

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

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

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

    1348    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
    1349        this = self.sql(expression, "this")
    1350        specifier = self.sql(expression, "expression")
    1351        specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else ""
    1352        return f"{this}{specifier}"

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

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

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

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

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

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

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

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

    1431    def set_operation(self, expression: exp.SetOperation) -> str:
    1432        op_type = type(expression)
    1433        op_name = op_type.key.upper()
    1434
    1435        distinct = expression.args.get("distinct")
    1436        if (
    1437            distinct is False
    1438            and op_type in (exp.Except, exp.Intersect)
    1439            and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE
    1440        ):
    1441            self.unsupported(f"{op_name} ALL is not supported")
    1442
    1443        default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type]
    1444
    1445        if distinct is None:
    1446            distinct = default_distinct
    1447            if distinct is None:
    1448                self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified")
    1449
    1450        if distinct is default_distinct:
    1451            distinct_or_all = ""
    1452        else:
    1453            distinct_or_all = " DISTINCT" if distinct else " ALL"
    1454
    1455        side_kind = " ".join(filter(None, [expression.side, expression.kind]))
    1456        side_kind = f"{side_kind} " if side_kind else ""
    1457
    1458        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1459        on = self.expressions(expression, key="on", flat=True)
    1460        on = f" ON ({on})" if on else ""
    1461
    1462        return f"{side_kind}{op_name}{distinct_or_all}{by_name}{on}"

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

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

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

    1501    def fetch_sql(self, expression: exp.Fetch) -> str:
    1502        direction = expression.args.get("direction")
    1503        direction = f" {direction}" if direction else ""
    1504        count = self.sql(expression, "count")
    1505        count = f" {count}" if count else ""
    1506        limit_options = self.sql(expression, "limit_options")
    1507        limit_options = f"{limit_options}" if limit_options else " ROWS ONLY"
    1508        return f"{self.seg('FETCH')}{direction}{count}{limit_options}"

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

    1510    def limitoptions_sql(self, expression: exp.LimitOptions) -> str:
    1511        percent = " PERCENT" if expression.args.get("percent") else ""
    1512        rows = " ROWS" if expression.args.get("rows") else ""
    1513        with_ties = " WITH TIES" if expression.args.get("with_ties") else ""
    1514        if not with_ties and rows:
    1515            with_ties = " ONLY"
    1516        return f"{percent}{rows}{with_ties}"

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

    1518    def filter_sql(self, expression: exp.Filter) -> str:
    1519        if self.AGGREGATE_FILTER_SUPPORTED:
    1520            this = self.sql(expression, "this")
    1521            where = self.sql(expression, "expression").strip()
    1522            return f"{this} FILTER({where})"
    1523
    1524        agg = expression.this
    1525        agg_arg = agg.this
    1526        cond = expression.expression.this
    1527        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
    1528        return self.sql(agg)

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

    1530    def hint_sql(self, expression: exp.Hint) -> str:
    1531        if not self.QUERY_HINTS:
    1532            self.unsupported("Hints are not supported")
    1533            return ""
    1534
    1535        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"

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

    1537    def indexparameters_sql(self, expression: exp.IndexParameters) -> str:
    1538        using = self.sql(expression, "using")
    1539        using = f" USING {using}" if using else ""
    1540        columns = self.expressions(expression, key="columns", flat=True)
    1541        columns = f"({columns})" if columns else ""
    1542        partition_by = self.expressions(expression, key="partition_by", flat=True)
    1543        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
    1544        where = self.sql(expression, "where")
    1545        include = self.expressions(expression, key="include", flat=True)
    1546        if include:
    1547            include = f" INCLUDE ({include})"
    1548        with_storage = self.expressions(expression, key="with_storage", flat=True)
    1549        with_storage = f" WITH ({with_storage})" if with_storage else ""
    1550        tablespace = self.sql(expression, "tablespace")
    1551        tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else ""
    1552        on = self.sql(expression, "on")
    1553        on = f" ON {on}" if on else ""
    1554
    1555        return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"

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

    1557    def index_sql(self, expression: exp.Index) -> str:
    1558        unique = "UNIQUE " if expression.args.get("unique") else ""
    1559        primary = "PRIMARY " if expression.args.get("primary") else ""
    1560        amp = "AMP " if expression.args.get("amp") else ""
    1561        name = self.sql(expression, "this")
    1562        name = f"{name} " if name else ""
    1563        table = self.sql(expression, "table")
    1564        table = f"{self.INDEX_ON} {table}" if table else ""
    1565
    1566        index = "INDEX " if not table else ""
    1567
    1568        params = self.sql(expression, "params")
    1569        return f"{unique}{primary}{amp}{index}{name}{table}{params}"

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

    1571    def identifier_sql(self, expression: exp.Identifier) -> str:
    1572        text = expression.name
    1573        lower = text.lower()
    1574        text = lower if self.normalize and not expression.quoted else text
    1575        text = text.replace(self._identifier_end, self._escaped_identifier_end)
    1576        if (
    1577            expression.quoted
    1578            or self.dialect.can_identify(text, self.identify)
    1579            or lower in self.RESERVED_KEYWORDS
    1580            or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
    1581        ):
    1582            text = f"{self._identifier_start}{text}{self._identifier_end}"
    1583        return text

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

    1585    def hex_sql(self, expression: exp.Hex) -> str:
    1586        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1587        if self.dialect.HEX_LOWERCASE:
    1588            text = self.func("LOWER", text)
    1589
    1590        return text

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

    1592    def lowerhex_sql(self, expression: exp.LowerHex) -> str:
    1593        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1594        if not self.dialect.HEX_LOWERCASE:
    1595            text = self.func("LOWER", text)
    1596        return text

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

    1598    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    1599        input_format = self.sql(expression, "input_format")
    1600        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    1601        output_format = self.sql(expression, "output_format")
    1602        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    1603        return self.sep().join((input_format, output_format))

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

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

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

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

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

    1613    def properties_sql(self, expression: exp.Properties) -> str:
    1614        root_properties = []
    1615        with_properties = []
    1616
    1617        for p in expression.expressions:
    1618            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1619            if p_loc == exp.Properties.Location.POST_WITH:
    1620                with_properties.append(p)
    1621            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    1622                root_properties.append(p)
    1623
    1624        root_props = self.root_properties(exp.Properties(expressions=root_properties))
    1625        with_props = self.with_properties(exp.Properties(expressions=with_properties))
    1626
    1627        if root_props and with_props and not self.pretty:
    1628            with_props = " " + with_props
    1629
    1630        return root_props + with_props

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

    1632    def root_properties(self, properties: exp.Properties) -> str:
    1633        if properties.expressions:
    1634            return self.expressions(properties, indent=False, sep=" ")
    1635        return ""

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

    1637    def properties(
    1638        self,
    1639        properties: exp.Properties,
    1640        prefix: str = "",
    1641        sep: str = ", ",
    1642        suffix: str = "",
    1643        wrapped: bool = True,
    1644    ) -> str:
    1645        if properties.expressions:
    1646            expressions = self.expressions(properties, sep=sep, indent=False)
    1647            if expressions:
    1648                expressions = self.wrap(expressions) if wrapped else expressions
    1649                return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}"
    1650        return ""

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

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

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

    1655    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
    1656        properties_locs = defaultdict(list)
    1657        for p in properties.expressions:
    1658            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1659            if p_loc != exp.Properties.Location.UNSUPPORTED:
    1660                properties_locs[p_loc].append(p)
    1661            else:
    1662                self.unsupported(f"Unsupported property {p.key}")
    1663
    1664        return properties_locs

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

    1666    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
    1667        if isinstance(expression.this, exp.Dot):
    1668            return self.sql(expression, "this")
    1669        return f"'{expression.name}'" if string_key else expression.name

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

    1671    def property_sql(self, expression: exp.Property) -> str:
    1672        property_cls = expression.__class__
    1673        if property_cls == exp.Property:
    1674            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
    1675
    1676        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    1677        if not property_name:
    1678            self.unsupported(f"Unsupported property {expression.key}")
    1679
    1680        return f"{property_name}={self.sql(expression, 'this')}"

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

    1682    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
    1683        if self.SUPPORTS_CREATE_TABLE_LIKE:
    1684            options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
    1685            options = f" {options}" if options else ""
    1686
    1687            like = f"LIKE {self.sql(expression, 'this')}{options}"
    1688            if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema):
    1689                like = f"({like})"
    1690
    1691            return like
    1692
    1693        if expression.expressions:
    1694            self.unsupported("Transpilation of LIKE property options is unsupported")
    1695
    1696        select = exp.select("*").from_(expression.this).limit(0)
    1697        return f"AS {self.sql(select)}"

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

    1699    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1700        no = "NO " if expression.args.get("no") else ""
    1701        protection = " PROTECTION" if expression.args.get("protection") else ""
    1702        return f"{no}FALLBACK{protection}"

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

    1704    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1705        no = "NO " if expression.args.get("no") else ""
    1706        local = expression.args.get("local")
    1707        local = f"{local} " if local else ""
    1708        dual = "DUAL " if expression.args.get("dual") else ""
    1709        before = "BEFORE " if expression.args.get("before") else ""
    1710        after = "AFTER " if expression.args.get("after") else ""
    1711        return f"{no}{local}{dual}{before}{after}JOURNAL"

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

    1713    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1714        freespace = self.sql(expression, "this")
    1715        percent = " PERCENT" if expression.args.get("percent") else ""
    1716        return f"FREESPACE={freespace}{percent}"

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

    1718    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1719        if expression.args.get("default"):
    1720            property = "DEFAULT"
    1721        elif expression.args.get("on"):
    1722            property = "ON"
    1723        else:
    1724            property = "OFF"
    1725        return f"CHECKSUM={property}"

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

    1727    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1728        if expression.args.get("no"):
    1729            return "NO MERGEBLOCKRATIO"
    1730        if expression.args.get("default"):
    1731            return "DEFAULT MERGEBLOCKRATIO"
    1732
    1733        percent = " PERCENT" if expression.args.get("percent") else ""
    1734        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"

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

    1736    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1737        default = expression.args.get("default")
    1738        minimum = expression.args.get("minimum")
    1739        maximum = expression.args.get("maximum")
    1740        if default or minimum or maximum:
    1741            if default:
    1742                prop = "DEFAULT"
    1743            elif minimum:
    1744                prop = "MINIMUM"
    1745            else:
    1746                prop = "MAXIMUM"
    1747            return f"{prop} DATABLOCKSIZE"
    1748        units = expression.args.get("units")
    1749        units = f" {units}" if units else ""
    1750        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"

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

    1752    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1753        autotemp = expression.args.get("autotemp")
    1754        always = expression.args.get("always")
    1755        default = expression.args.get("default")
    1756        manual = expression.args.get("manual")
    1757        never = expression.args.get("never")
    1758
    1759        if autotemp is not None:
    1760            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1761        elif always:
    1762            prop = "ALWAYS"
    1763        elif default:
    1764            prop = "DEFAULT"
    1765        elif manual:
    1766            prop = "MANUAL"
    1767        elif never:
    1768            prop = "NEVER"
    1769        return f"BLOCKCOMPRESSION={prop}"

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

    1771    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1772        no = expression.args.get("no")
    1773        no = " NO" if no else ""
    1774        concurrent = expression.args.get("concurrent")
    1775        concurrent = " CONCURRENT" if concurrent else ""
    1776        target = self.sql(expression, "target")
    1777        target = f" {target}" if target else ""
    1778        return f"WITH{no}{concurrent} ISOLATED LOADING{target}"

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

    1780    def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str:
    1781        if isinstance(expression.this, list):
    1782            return f"IN ({self.expressions(expression, key='this', flat=True)})"
    1783        if expression.this:
    1784            modulus = self.sql(expression, "this")
    1785            remainder = self.sql(expression, "expression")
    1786            return f"WITH (MODULUS {modulus}, REMAINDER {remainder})"
    1787
    1788        from_expressions = self.expressions(expression, key="from_expressions", flat=True)
    1789        to_expressions = self.expressions(expression, key="to_expressions", flat=True)
    1790        return f"FROM ({from_expressions}) TO ({to_expressions})"

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

    1792    def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str:
    1793        this = self.sql(expression, "this")
    1794
    1795        for_values_or_default = expression.expression
    1796        if isinstance(for_values_or_default, exp.PartitionBoundSpec):
    1797            for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}"
    1798        else:
    1799            for_values_or_default = " DEFAULT"
    1800
    1801        return f"PARTITION OF {this}{for_values_or_default}"

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

    1803    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1804        kind = expression.args.get("kind")
    1805        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1806        for_or_in = expression.args.get("for_or_in")
    1807        for_or_in = f" {for_or_in}" if for_or_in else ""
    1808        lock_type = expression.args.get("lock_type")
    1809        override = " OVERRIDE" if expression.args.get("override") else ""
    1810        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"

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

    1812    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1813        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1814        statistics = expression.args.get("statistics")
    1815        statistics_sql = ""
    1816        if statistics is not None:
    1817            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1818        return f"{data_sql}{statistics_sql}"

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

    1820    def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str:
    1821        this = self.sql(expression, "this")
    1822        this = f"HISTORY_TABLE={this}" if this else ""
    1823        data_consistency: t.Optional[str] = self.sql(expression, "data_consistency")
    1824        data_consistency = (
    1825            f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None
    1826        )
    1827        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    1828        retention_period = (
    1829            f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None
    1830        )
    1831
    1832        if this:
    1833            on_sql = self.func("ON", this, data_consistency, retention_period)
    1834        else:
    1835            on_sql = "ON" if expression.args.get("on") else "OFF"
    1836
    1837        sql = f"SYSTEM_VERSIONING={on_sql}"
    1838
    1839        return f"WITH({sql})" if expression.args.get("with") else sql

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

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

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

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

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

    1888    def kill_sql(self, expression: exp.Kill) -> str:
    1889        kind = self.sql(expression, "kind")
    1890        kind = f" {kind}" if kind else ""
    1891        this = self.sql(expression, "this")
    1892        this = f" {this}" if this else ""
    1893        return f"KILL{kind}{this}"

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

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

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

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

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

    1901    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1902        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1903
    1904        constraint = self.sql(expression, "constraint")
    1905        constraint = f" ON CONSTRAINT {constraint}" if constraint else ""
    1906
    1907        conflict_keys = self.expressions(expression, key="conflict_keys", flat=True)
    1908        conflict_keys = f"({conflict_keys}) " if conflict_keys else " "
    1909        action = self.sql(expression, "action")
    1910
    1911        expressions = self.expressions(expression, flat=True)
    1912        if expressions:
    1913            set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
    1914            expressions = f" {set_keyword}{expressions}"
    1915
    1916        where = self.sql(expression, "where")
    1917        return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}"

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

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

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

    1922    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1923        fields = self.sql(expression, "fields")
    1924        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1925        escaped = self.sql(expression, "escaped")
    1926        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1927        items = self.sql(expression, "collection_items")
    1928        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1929        keys = self.sql(expression, "map_keys")
    1930        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1931        lines = self.sql(expression, "lines")
    1932        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1933        null = self.sql(expression, "null")
    1934        null = f" NULL DEFINED AS {null}" if null else ""
    1935        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"

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

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

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

    1940    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1941        this = f"{self.sql(expression, 'this')} INDEX"
    1942        target = self.sql(expression, "target")
    1943        target = f" FOR {target}" if target else ""
    1944        return f"{this}{target} ({self.expressions(expression, flat=True)})"

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

    1946    def historicaldata_sql(self, expression: exp.HistoricalData) -> str:
    1947        this = self.sql(expression, "this")
    1948        kind = self.sql(expression, "kind")
    1949        expr = self.sql(expression, "expression")
    1950        return f"{this} ({kind} => {expr})"

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

    1952    def table_parts(self, expression: exp.Table) -> str:
    1953        return ".".join(
    1954            self.sql(part)
    1955            for part in (
    1956                expression.args.get("catalog"),
    1957                expression.args.get("db"),
    1958                expression.args.get("this"),
    1959            )
    1960            if part is not None
    1961        )

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

    1963    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1964        table = self.table_parts(expression)
    1965        only = "ONLY " if expression.args.get("only") else ""
    1966        partition = self.sql(expression, "partition")
    1967        partition = f" {partition}" if partition else ""
    1968        version = self.sql(expression, "version")
    1969        version = f" {version}" if version else ""
    1970        alias = self.sql(expression, "alias")
    1971        alias = f"{sep}{alias}" if alias else ""
    1972
    1973        sample = self.sql(expression, "sample")
    1974        if self.dialect.ALIAS_POST_TABLESAMPLE:
    1975            sample_pre_alias = sample
    1976            sample_post_alias = ""
    1977        else:
    1978            sample_pre_alias = ""
    1979            sample_post_alias = sample
    1980
    1981        hints = self.expressions(expression, key="hints", sep=" ")
    1982        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
    1983        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    1984        joins = self.indent(
    1985            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
    1986        )
    1987        laterals = self.expressions(expression, key="laterals", sep="")
    1988
    1989        file_format = self.sql(expression, "format")
    1990        if file_format:
    1991            pattern = self.sql(expression, "pattern")
    1992            pattern = f", PATTERN => {pattern}" if pattern else ""
    1993            file_format = f" (FILE_FORMAT => {file_format}{pattern})"
    1994
    1995        ordinality = expression.args.get("ordinality") or ""
    1996        if ordinality:
    1997            ordinality = f" WITH ORDINALITY{alias}"
    1998            alias = ""
    1999
    2000        when = self.sql(expression, "when")
    2001        if when:
    2002            table = f"{table} {when}"
    2003
    2004        changes = self.sql(expression, "changes")
    2005        changes = f" {changes}" if changes else ""
    2006
    2007        rows_from = self.expressions(expression, key="rows_from")
    2008        if rows_from:
    2009            table = f"ROWS FROM {self.wrap(rows_from)}"
    2010
    2011        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

    2013    def tablefromrows_sql(self, expression: exp.TableFromRows) -> str:
    2014        table = self.func("TABLE", expression.this)
    2015        alias = self.sql(expression, "alias")
    2016        alias = f" AS {alias}" if alias else ""
    2017        sample = self.sql(expression, "sample")
    2018        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    2019        joins = self.indent(
    2020            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
    2021        )
    2022        return f"{table}{alias}{pivots}{sample}{joins}"

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

    2024    def tablesample_sql(
    2025        self,
    2026        expression: exp.TableSample,
    2027        tablesample_keyword: t.Optional[str] = None,
    2028    ) -> str:
    2029        method = self.sql(expression, "method")
    2030        method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    2031        numerator = self.sql(expression, "bucket_numerator")
    2032        denominator = self.sql(expression, "bucket_denominator")
    2033        field = self.sql(expression, "bucket_field")
    2034        field = f" ON {field}" if field else ""
    2035        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    2036        seed = self.sql(expression, "seed")
    2037        seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else ""
    2038
    2039        size = self.sql(expression, "size")
    2040        if size and self.TABLESAMPLE_SIZE_IS_ROWS:
    2041            size = f"{size} ROWS"
    2042
    2043        percent = self.sql(expression, "percent")
    2044        if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT:
    2045            percent = f"{percent} PERCENT"
    2046
    2047        expr = f"{bucket}{percent}{size}"
    2048        if self.TABLESAMPLE_REQUIRES_PARENS:
    2049            expr = f"({expr})"
    2050
    2051        return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}"

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

    2053    def pivot_sql(self, expression: exp.Pivot) -> str:
    2054        expressions = self.expressions(expression, flat=True)
    2055        direction = "UNPIVOT" if expression.unpivot else "PIVOT"
    2056
    2057        group = self.sql(expression, "group")
    2058
    2059        if expression.this:
    2060            this = self.sql(expression, "this")
    2061            if not expressions:
    2062                return f"UNPIVOT {this}"
    2063
    2064            on = f"{self.seg('ON')} {expressions}"
    2065            into = self.sql(expression, "into")
    2066            into = f"{self.seg('INTO')} {into}" if into else ""
    2067            using = self.expressions(expression, key="using", flat=True)
    2068            using = f"{self.seg('USING')} {using}" if using else ""
    2069            return f"{direction} {this}{on}{into}{using}{group}"
    2070
    2071        alias = self.sql(expression, "alias")
    2072        alias = f" AS {alias}" if alias else ""
    2073
    2074        fields = self.expressions(
    2075            expression,
    2076            "fields",
    2077            sep=" ",
    2078            dynamic=True,
    2079            new_line=True,
    2080            skip_first=True,
    2081            skip_last=True,
    2082        )
    2083
    2084        include_nulls = expression.args.get("include_nulls")
    2085        if include_nulls is not None:
    2086            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
    2087        else:
    2088            nulls = ""
    2089
    2090        default_on_null = self.sql(expression, "default_on_null")
    2091        default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else ""
    2092        return f"{self.seg(direction)}{nulls}({expressions} FOR {fields}{default_on_null}{group}){alias}"

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

    2094    def version_sql(self, expression: exp.Version) -> str:
    2095        this = f"FOR {expression.name}"
    2096        kind = expression.text("kind")
    2097        expr = self.sql(expression, "expression")
    2098        return f"{this} {kind} {expr}"

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

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

    2103    def update_sql(self, expression: exp.Update) -> str:
    2104        this = self.sql(expression, "this")
    2105        set_sql = self.expressions(expression, flat=True)
    2106        from_sql = self.sql(expression, "from")
    2107        where_sql = self.sql(expression, "where")
    2108        returning = self.sql(expression, "returning")
    2109        order = self.sql(expression, "order")
    2110        limit = self.sql(expression, "limit")
    2111        if self.RETURNING_END:
    2112            expression_sql = f"{from_sql}{where_sql}{returning}"
    2113        else:
    2114            expression_sql = f"{returning}{from_sql}{where_sql}"
    2115        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
    2116        return self.prepend_ctes(expression, sql)

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

    2118    def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str:
    2119        values_as_table = values_as_table and self.VALUES_AS_TABLE
    2120
    2121        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
    2122        if values_as_table or not expression.find_ancestor(exp.From, exp.Join):
    2123            args = self.expressions(expression)
    2124            alias = self.sql(expression, "alias")
    2125            values = f"VALUES{self.seg('')}{args}"
    2126            values = (
    2127                f"({values})"
    2128                if self.WRAP_DERIVED_VALUES
    2129                and (alias or isinstance(expression.parent, (exp.From, exp.Table)))
    2130                else values
    2131            )
    2132            return f"{values} AS {alias}" if alias else values
    2133
    2134        # Converts `VALUES...` expression into a series of select unions.
    2135        alias_node = expression.args.get("alias")
    2136        column_names = alias_node and alias_node.columns
    2137
    2138        selects: t.List[exp.Query] = []
    2139
    2140        for i, tup in enumerate(expression.expressions):
    2141            row = tup.expressions
    2142
    2143            if i == 0 and column_names:
    2144                row = [
    2145                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
    2146                ]
    2147
    2148            selects.append(exp.Select(expressions=row))
    2149
    2150        if self.pretty:
    2151            # This may result in poor performance for large-cardinality `VALUES` tables, due to
    2152            # the deep nesting of the resulting exp.Unions. If this is a problem, either increase
    2153            # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`.
    2154            query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects)
    2155            return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False))
    2156
    2157        alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else ""
    2158        unions = " UNION ALL ".join(self.sql(select) for select in selects)
    2159        return f"({unions}){alias}"

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

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

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

    2164    @unsupported_args("expressions")
    2165    def into_sql(self, expression: exp.Into) -> str:
    2166        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    2167        unlogged = " UNLOGGED" if expression.args.get("unlogged") else ""
    2168        return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"

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

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

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

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

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

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

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

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

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

    2185    def group_sql(self, expression: exp.Group) -> str:
    2186        group_by_all = expression.args.get("all")
    2187        if group_by_all is True:
    2188            modifier = " ALL"
    2189        elif group_by_all is False:
    2190            modifier = " DISTINCT"
    2191        else:
    2192            modifier = ""
    2193
    2194        group_by = self.op_expressions(f"GROUP BY{modifier}", expression)
    2195
    2196        grouping_sets = self.expressions(expression, key="grouping_sets")
    2197        cube = self.expressions(expression, key="cube")
    2198        rollup = self.expressions(expression, key="rollup")
    2199
    2200        groupings = csv(
    2201            self.seg(grouping_sets) if grouping_sets else "",
    2202            self.seg(cube) if cube else "",
    2203            self.seg(rollup) if rollup else "",
    2204            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    2205            sep=self.GROUPINGS_SEP,
    2206        )
    2207
    2208        if (
    2209            expression.expressions
    2210            and groupings
    2211            and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP")
    2212        ):
    2213            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    2214
    2215        return f"{group_by}{groupings}"

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

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

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

    2221    def connect_sql(self, expression: exp.Connect) -> str:
    2222        start = self.sql(expression, "start")
    2223        start = self.seg(f"START WITH {start}") if start else ""
    2224        nocycle = " NOCYCLE" if expression.args.get("nocycle") else ""
    2225        connect = self.sql(expression, "connect")
    2226        connect = self.seg(f"CONNECT BY{nocycle} {connect}")
    2227        return start + connect

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

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

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

    2232    def join_sql(self, expression: exp.Join) -> str:
    2233        if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"):
    2234            side = None
    2235        else:
    2236            side = expression.side
    2237
    2238        op_sql = " ".join(
    2239            op
    2240            for op in (
    2241                expression.method,
    2242                "GLOBAL" if expression.args.get("global") else None,
    2243                side,
    2244                expression.kind,
    2245                expression.hint if self.JOIN_HINTS else None,
    2246            )
    2247            if op
    2248        )
    2249        match_cond = self.sql(expression, "match_condition")
    2250        match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else ""
    2251        on_sql = self.sql(expression, "on")
    2252        using = expression.args.get("using")
    2253
    2254        if not on_sql and using:
    2255            on_sql = csv(*(self.sql(column) for column in using))
    2256
    2257        this = expression.this
    2258        this_sql = self.sql(this)
    2259
    2260        exprs = self.expressions(expression)
    2261        if exprs:
    2262            this_sql = f"{this_sql},{self.seg(exprs)}"
    2263
    2264        if on_sql:
    2265            on_sql = self.indent(on_sql, skip_first=True)
    2266            space = self.seg(" " * self.pad) if self.pretty else " "
    2267            if using:
    2268                on_sql = f"{space}USING ({on_sql})"
    2269            else:
    2270                on_sql = f"{space}ON {on_sql}"
    2271        elif not op_sql:
    2272            if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None:
    2273                return f" {this_sql}"
    2274
    2275            return f", {this_sql}"
    2276
    2277        if op_sql != "STRAIGHT_JOIN":
    2278            op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    2279
    2280        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

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

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

    2287    def lateral_op(self, expression: exp.Lateral) -> str:
    2288        cross_apply = expression.args.get("cross_apply")
    2289
    2290        # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/
    2291        if cross_apply is True:
    2292            op = "INNER JOIN "
    2293        elif cross_apply is False:
    2294            op = "LEFT JOIN "
    2295        else:
    2296            op = ""
    2297
    2298        return f"{op}LATERAL"

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

    2300    def lateral_sql(self, expression: exp.Lateral) -> str:
    2301        this = self.sql(expression, "this")
    2302
    2303        if expression.args.get("view"):
    2304            alias = expression.args["alias"]
    2305            columns = self.expressions(alias, key="columns", flat=True)
    2306            table = f" {alias.name}" if alias.name else ""
    2307            columns = f" AS {columns}" if columns else ""
    2308            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    2309            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    2310
    2311        alias = self.sql(expression, "alias")
    2312        alias = f" AS {alias}" if alias else ""
    2313
    2314        ordinality = expression.args.get("ordinality") or ""
    2315        if ordinality:
    2316            ordinality = f" WITH ORDINALITY{alias}"
    2317            alias = ""
    2318
    2319        return f"{self.lateral_op(expression)} {this}{alias}{ordinality}"

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

    2321    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    2322        this = self.sql(expression, "this")
    2323
    2324        args = [
    2325            self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e
    2326            for e in (expression.args.get(k) for k in ("offset", "expression"))
    2327            if e
    2328        ]
    2329
    2330        args_sql = ", ".join(self.sql(e) for e in args)
    2331        args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql
    2332        expressions = self.expressions(expression, flat=True)
    2333        limit_options = self.sql(expression, "limit_options")
    2334        expressions = f" BY {expressions}" if expressions else ""
    2335
    2336        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

    2338    def offset_sql(self, expression: exp.Offset) -> str:
    2339        this = self.sql(expression, "this")
    2340        value = expression.expression
    2341        value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value
    2342        expressions = self.expressions(expression, flat=True)
    2343        expressions = f" BY {expressions}" if expressions else ""
    2344        return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"

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

    2346    def setitem_sql(self, expression: exp.SetItem) -> str:
    2347        kind = self.sql(expression, "kind")
    2348        kind = f"{kind} " if kind else ""
    2349        this = self.sql(expression, "this")
    2350        expressions = self.expressions(expression)
    2351        collate = self.sql(expression, "collate")
    2352        collate = f" COLLATE {collate}" if collate else ""
    2353        global_ = "GLOBAL " if expression.args.get("global") else ""
    2354        return f"{global_}{kind}{this}{expressions}{collate}"

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

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

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

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

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

    2364    def lock_sql(self, expression: exp.Lock) -> str:
    2365        if not self.LOCKING_READS_SUPPORTED:
    2366            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    2367            return ""
    2368
    2369        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    2370        expressions = self.expressions(expression, flat=True)
    2371        expressions = f" OF {expressions}" if expressions else ""
    2372        wait = expression.args.get("wait")
    2373
    2374        if wait is not None:
    2375            if isinstance(wait, exp.Literal):
    2376                wait = f" WAIT {self.sql(wait)}"
    2377            else:
    2378                wait = " NOWAIT" if wait else " SKIP LOCKED"
    2379
    2380        return f"{lock_type}{expressions}{wait or ''}"

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

    2382    def literal_sql(self, expression: exp.Literal) -> str:
    2383        text = expression.this or ""
    2384        if expression.is_string:
    2385            text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}"
    2386        return text

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

    2388    def escape_str(self, text: str, escape_backslash: bool = True) -> str:
    2389        if self.dialect.ESCAPED_SEQUENCES:
    2390            to_escaped = self.dialect.ESCAPED_SEQUENCES
    2391            text = "".join(
    2392                to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text
    2393            )
    2394
    2395        return self._replace_line_breaks(text).replace(
    2396            self.dialect.QUOTE_END, self._escaped_quote_end
    2397        )

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

    2399    def loaddata_sql(self, expression: exp.LoadData) -> str:
    2400        local = " LOCAL" if expression.args.get("local") else ""
    2401        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    2402        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    2403        this = f" INTO TABLE {self.sql(expression, 'this')}"
    2404        partition = self.sql(expression, "partition")
    2405        partition = f" {partition}" if partition else ""
    2406        input_format = self.sql(expression, "input_format")
    2407        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    2408        serde = self.sql(expression, "serde")
    2409        serde = f" SERDE {serde}" if serde else ""
    2410        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"

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

    2412    def null_sql(self, *_) -> str:
    2413        return "NULL"

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

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

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

    2418    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    2419        this = self.sql(expression, "this")
    2420        this = f"{this} " if this else this
    2421        siblings = "SIBLINGS " if expression.args.get("siblings") else ""
    2422        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

    2424    def withfill_sql(self, expression: exp.WithFill) -> str:
    2425        from_sql = self.sql(expression, "from")
    2426        from_sql = f" FROM {from_sql}" if from_sql else ""
    2427        to_sql = self.sql(expression, "to")
    2428        to_sql = f" TO {to_sql}" if to_sql else ""
    2429        step_sql = self.sql(expression, "step")
    2430        step_sql = f" STEP {step_sql}" if step_sql else ""
    2431        interpolated_values = [
    2432            f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}"
    2433            if isinstance(e, exp.Alias)
    2434            else self.sql(e, "this")
    2435            for e in expression.args.get("interpolate") or []
    2436        ]
    2437        interpolate = (
    2438            f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else ""
    2439        )
    2440        return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}"

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

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

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

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

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

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

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

    2451    def ordered_sql(self, expression: exp.Ordered) -> str:
    2452        desc = expression.args.get("desc")
    2453        asc = not desc
    2454
    2455        nulls_first = expression.args.get("nulls_first")
    2456        nulls_last = not nulls_first
    2457        nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large"
    2458        nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small"
    2459        nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last"
    2460
    2461        this = self.sql(expression, "this")
    2462
    2463        sort_order = " DESC" if desc else (" ASC" if desc is False else "")
    2464        nulls_sort_change = ""
    2465        if nulls_first and (
    2466            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
    2467        ):
    2468            nulls_sort_change = " NULLS FIRST"
    2469        elif (
    2470            nulls_last
    2471            and ((asc and nulls_are_small) or (desc and nulls_are_large))
    2472            and not nulls_are_last
    2473        ):
    2474            nulls_sort_change = " NULLS LAST"
    2475
    2476        # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it
    2477        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
    2478            window = expression.find_ancestor(exp.Window, exp.Select)
    2479            if isinstance(window, exp.Window) and window.args.get("spec"):
    2480                self.unsupported(
    2481                    f"'{nulls_sort_change.strip()}' translation not supported in window functions"
    2482                )
    2483                nulls_sort_change = ""
    2484            elif self.NULL_ORDERING_SUPPORTED is False and (
    2485                (asc and nulls_sort_change == " NULLS LAST")
    2486                or (desc and nulls_sort_change == " NULLS FIRST")
    2487            ):
    2488                # BigQuery does not allow these ordering/nulls combinations when used under
    2489                # an aggregation func or under a window containing one
    2490                ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select)
    2491
    2492                if isinstance(ancestor, exp.Window):
    2493                    ancestor = ancestor.this
    2494                if isinstance(ancestor, exp.AggFunc):
    2495                    self.unsupported(
    2496                        f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order"
    2497                    )
    2498                    nulls_sort_change = ""
    2499            elif self.NULL_ORDERING_SUPPORTED is None:
    2500                if expression.this.is_int:
    2501                    self.unsupported(
    2502                        f"'{nulls_sort_change.strip()}' translation not supported with positional ordering"
    2503                    )
    2504                elif not isinstance(expression.this, exp.Rand):
    2505                    null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else ""
    2506                    this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}"
    2507                nulls_sort_change = ""
    2508
    2509        with_fill = self.sql(expression, "with_fill")
    2510        with_fill = f" {with_fill}" if with_fill else ""
    2511
    2512        return f"{this}{sort_order}{nulls_sort_change}{with_fill}"

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

    2514    def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str:
    2515        window_frame = self.sql(expression, "window_frame")
    2516        window_frame = f"{window_frame} " if window_frame else ""
    2517
    2518        this = self.sql(expression, "this")
    2519
    2520        return f"{window_frame}{this}"

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

    2522    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    2523        partition = self.partition_by_sql(expression)
    2524        order = self.sql(expression, "order")
    2525        measures = self.expressions(expression, key="measures")
    2526        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    2527        rows = self.sql(expression, "rows")
    2528        rows = self.seg(rows) if rows else ""
    2529        after = self.sql(expression, "after")
    2530        after = self.seg(after) if after else ""
    2531        pattern = self.sql(expression, "pattern")
    2532        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    2533        definition_sqls = [
    2534            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    2535            for definition in expression.args.get("define", [])
    2536        ]
    2537        definitions = self.expressions(sqls=definition_sqls)
    2538        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    2539        body = "".join(
    2540            (
    2541                partition,
    2542                order,
    2543                measures,
    2544                rows,
    2545                after,
    2546                pattern,
    2547                define,
    2548            )
    2549        )
    2550        alias = self.sql(expression, "alias")
    2551        alias = f" {alias}" if alias else ""
    2552        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"

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

    2554    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    2555        limit = expression.args.get("limit")
    2556
    2557        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    2558            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
    2559        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    2560            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
    2561
    2562        return csv(
    2563            *sqls,
    2564            *[self.sql(join) for join in expression.args.get("joins") or []],
    2565            self.sql(expression, "match"),
    2566            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    2567            self.sql(expression, "prewhere"),
    2568            self.sql(expression, "where"),
    2569            self.sql(expression, "connect"),
    2570            self.sql(expression, "group"),
    2571            self.sql(expression, "having"),
    2572            *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()],
    2573            self.sql(expression, "order"),
    2574            *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit),
    2575            *self.after_limit_modifiers(expression),
    2576            self.options_modifier(expression),
    2577            sep="",
    2578        )

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

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

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

    2584    def queryoption_sql(self, expression: exp.QueryOption) -> str:
    2585        self.unsupported("Unsupported query option.")
    2586        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

    2588    def offset_limit_modifiers(
    2589        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    2590    ) -> t.List[str]:
    2591        return [
    2592            self.sql(expression, "offset") if fetch else self.sql(limit),
    2593            self.sql(limit) if fetch else self.sql(expression, "offset"),
    2594        ]

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

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

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

    2601    def select_sql(self, expression: exp.Select) -> str:
    2602        into = expression.args.get("into")
    2603        if not self.SUPPORTS_SELECT_INTO and into:
    2604            into.pop()
    2605
    2606        hint = self.sql(expression, "hint")
    2607        distinct = self.sql(expression, "distinct")
    2608        distinct = f" {distinct}" if distinct else ""
    2609        kind = self.sql(expression, "kind")
    2610
    2611        limit = expression.args.get("limit")
    2612        if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP:
    2613            top = self.limit_sql(limit, top=True)
    2614            limit.pop()
    2615        else:
    2616            top = ""
    2617
    2618        expressions = self.expressions(expression)
    2619
    2620        if kind:
    2621            if kind in self.SELECT_KINDS:
    2622                kind = f" AS {kind}"
    2623            else:
    2624                if kind == "STRUCT":
    2625                    expressions = self.expressions(
    2626                        sqls=[
    2627                            self.sql(
    2628                                exp.Struct(
    2629                                    expressions=[
    2630                                        exp.PropertyEQ(this=e.args.get("alias"), expression=e.this)
    2631                                        if isinstance(e, exp.Alias)
    2632                                        else e
    2633                                        for e in expression.expressions
    2634                                    ]
    2635                                )
    2636                            )
    2637                        ]
    2638                    )
    2639                kind = ""
    2640
    2641        operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ")
    2642        operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else ""
    2643
    2644        # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata
    2645        # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first.
    2646        top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}"
    2647        expressions = f"{self.sep()}{expressions}" if expressions else expressions
    2648        sql = self.query_modifiers(
    2649            expression,
    2650            f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}",
    2651            self.sql(expression, "into", comment=False),
    2652            self.sql(expression, "from", comment=False),
    2653        )
    2654
    2655        # If both the CTE and SELECT clauses have comments, generate the latter earlier
    2656        if expression.args.get("with"):
    2657            sql = self.maybe_comment(sql, expression)
    2658            expression.pop_comments()
    2659
    2660        sql = self.prepend_ctes(expression, sql)
    2661
    2662        if not self.SUPPORTS_SELECT_INTO and into:
    2663            if into.args.get("temporary"):
    2664                table_kind = " TEMPORARY"
    2665            elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"):
    2666                table_kind = " UNLOGGED"
    2667            else:
    2668                table_kind = ""
    2669            sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}"
    2670
    2671        return sql

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

    2673    def schema_sql(self, expression: exp.Schema) -> str:
    2674        this = self.sql(expression, "this")
    2675        sql = self.schema_columns_sql(expression)
    2676        return f"{this} {sql}" if this and sql else this or sql

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

    2678    def schema_columns_sql(self, expression: exp.Schema) -> str:
    2679        if expression.expressions:
    2680            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
    2681        return ""

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

    2683    def star_sql(self, expression: exp.Star) -> str:
    2684        except_ = self.expressions(expression, key="except", flat=True)
    2685        except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else ""
    2686        replace = self.expressions(expression, key="replace", flat=True)
    2687        replace = f"{self.seg('REPLACE')} ({replace})" if replace else ""
    2688        rename = self.expressions(expression, key="rename", flat=True)
    2689        rename = f"{self.seg('RENAME')} ({rename})" if rename else ""
    2690        return f"*{except_}{replace}{rename}"

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

    2692    def parameter_sql(self, expression: exp.Parameter) -> str:
    2693        this = self.sql(expression, "this")
    2694        return f"{self.PARAMETER_TOKEN}{this}"

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

    2696    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    2697        this = self.sql(expression, "this")
    2698        kind = expression.text("kind")
    2699        if kind:
    2700            kind = f"{kind}."
    2701        return f"@@{kind}{this}"

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

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

    2706    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    2707        alias = self.sql(expression, "alias")
    2708        alias = f"{sep}{alias}" if alias else ""
    2709        sample = self.sql(expression, "sample")
    2710        if self.dialect.ALIAS_POST_TABLESAMPLE and sample:
    2711            alias = f"{sample}{alias}"
    2712
    2713            # Set to None so it's not generated again by self.query_modifiers()
    2714            expression.set("sample", None)
    2715
    2716        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    2717        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    2718        return self.prepend_ctes(expression, sql)

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

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

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

    2724    def unnest_sql(self, expression: exp.Unnest) -> str:
    2725        args = self.expressions(expression, flat=True)
    2726
    2727        alias = expression.args.get("alias")
    2728        offset = expression.args.get("offset")
    2729
    2730        if self.UNNEST_WITH_ORDINALITY:
    2731            if alias and isinstance(offset, exp.Expression):
    2732                alias.append("columns", offset)
    2733
    2734        if alias and self.dialect.UNNEST_COLUMN_ONLY:
    2735            columns = alias.columns
    2736            alias = self.sql(columns[0]) if columns else ""
    2737        else:
    2738            alias = self.sql(alias)
    2739
    2740        alias = f" AS {alias}" if alias else alias
    2741        if self.UNNEST_WITH_ORDINALITY:
    2742            suffix = f" WITH ORDINALITY{alias}" if offset else alias
    2743        else:
    2744            if isinstance(offset, exp.Expression):
    2745                suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}"
    2746            elif offset:
    2747                suffix = f"{alias} WITH OFFSET"
    2748            else:
    2749                suffix = alias
    2750
    2751        return f"UNNEST({args}){suffix}"

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

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

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

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

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

    2760    def window_sql(self, expression: exp.Window) -> str:
    2761        this = self.sql(expression, "this")
    2762        partition = self.partition_by_sql(expression)
    2763        order = expression.args.get("order")
    2764        order = self.order_sql(order, flat=True) if order else ""
    2765        spec = self.sql(expression, "spec")
    2766        alias = self.sql(expression, "alias")
    2767        over = self.sql(expression, "over") or "OVER"
    2768
    2769        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    2770
    2771        first = expression.args.get("first")
    2772        if first is None:
    2773            first = ""
    2774        else:
    2775            first = "FIRST" if first else "LAST"
    2776
    2777        if not partition and not order and not spec and alias:
    2778            return f"{this} {alias}"
    2779
    2780        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
    2781        return f"{this} ({args})"

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

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

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

    2787    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    2788        kind = self.sql(expression, "kind")
    2789        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    2790        end = (
    2791            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    2792            or "CURRENT ROW"
    2793        )
    2794        return f"{kind} BETWEEN {start} AND {end}"

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

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

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

    2801    def between_sql(self, expression: exp.Between) -> str:
    2802        this = self.sql(expression, "this")
    2803        low = self.sql(expression, "low")
    2804        high = self.sql(expression, "high")
    2805        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

    2807    def bracket_offset_expressions(
    2808        self, expression: exp.Bracket, index_offset: t.Optional[int] = None
    2809    ) -> t.List[exp.Expression]:
    2810        return apply_index_offset(
    2811            expression.this,
    2812            expression.expressions,
    2813            (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0),
    2814            dialect=self.dialect,
    2815        )

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

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

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

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

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

    2825    def any_sql(self, expression: exp.Any) -> str:
    2826        this = self.sql(expression, "this")
    2827        if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)):
    2828            if isinstance(expression.this, exp.UNWRAPPED_QUERIES):
    2829                this = self.wrap(this)
    2830            return f"ANY{this}"
    2831        return f"ANY {this}"

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

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

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

    2836    def case_sql(self, expression: exp.Case) -> str:
    2837        this = self.sql(expression, "this")
    2838        statements = [f"CASE {this}" if this else "CASE"]
    2839
    2840        for e in expression.args["ifs"]:
    2841            statements.append(f"WHEN {self.sql(e, 'this')}")
    2842            statements.append(f"THEN {self.sql(e, 'true')}")
    2843
    2844        default = self.sql(expression, "default")
    2845
    2846        if default:
    2847            statements.append(f"ELSE {default}")
    2848
    2849        statements.append("END")
    2850
    2851        if self.pretty and self.too_wide(statements):
    2852            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    2853
    2854        return " ".join(statements)

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

    2856    def constraint_sql(self, expression: exp.Constraint) -> str:
    2857        this = self.sql(expression, "this")
    2858        expressions = self.expressions(expression, flat=True)
    2859        return f"CONSTRAINT {this} {expressions}"

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

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

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

    2866    def extract_sql(self, expression: exp.Extract) -> str:
    2867        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
    2868        expression_sql = self.sql(expression, "expression")
    2869        return f"EXTRACT({this} FROM {expression_sql})"

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

    2871    def trim_sql(self, expression: exp.Trim) -> str:
    2872        trim_type = self.sql(expression, "position")
    2873
    2874        if trim_type == "LEADING":
    2875            func_name = "LTRIM"
    2876        elif trim_type == "TRAILING":
    2877            func_name = "RTRIM"
    2878        else:
    2879            func_name = "TRIM"
    2880
    2881        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

    2883    def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]:
    2884        args = expression.expressions
    2885        if isinstance(expression, exp.ConcatWs):
    2886            args = args[1:]  # Skip the delimiter
    2887
    2888        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    2889            args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args]
    2890
    2891        if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"):
    2892            args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args]
    2893
    2894        return args

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

    2896    def concat_sql(self, expression: exp.Concat) -> str:
    2897        expressions = self.convert_concat_args(expression)
    2898
    2899        # Some dialects don't allow a single-argument CONCAT call
    2900        if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1:
    2901            return self.sql(expressions[0])
    2902
    2903        return self.func("CONCAT", *expressions)

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

    2905    def concatws_sql(self, expression: exp.ConcatWs) -> str:
    2906        return self.func(
    2907            "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression)
    2908        )

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

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

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

    2914    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    2915        expressions = self.expressions(expression, flat=True)
    2916        expressions = f" ({expressions})" if expressions else ""
    2917        reference = self.sql(expression, "reference")
    2918        reference = f" {reference}" if reference else ""
    2919        delete = self.sql(expression, "delete")
    2920        delete = f" ON DELETE {delete}" if delete else ""
    2921        update = self.sql(expression, "update")
    2922        update = f" ON UPDATE {update}" if update else ""
    2923        return f"FOREIGN KEY{expressions}{reference}{delete}{update}"

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

    2925    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    2926        expressions = self.expressions(expression, flat=True)
    2927        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2928        options = f" {options}" if options else ""
    2929        return f"PRIMARY KEY ({expressions}){options}"

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

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

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

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

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

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

    2942    def jsonpath_sql(self, expression: exp.JSONPath) -> str:
    2943        path = self.expressions(expression, sep="", flat=True).lstrip(".")
    2944
    2945        if expression.args.get("escape"):
    2946            path = self.escape_str(path)
    2947
    2948        if self.QUOTE_JSON_PATH:
    2949            path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"
    2950
    2951        return path

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

    2953    def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str:
    2954        if isinstance(expression, exp.JSONPathPart):
    2955            transform = self.TRANSFORMS.get(expression.__class__)
    2956            if not callable(transform):
    2957                self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}")
    2958                return ""
    2959
    2960            return transform(self, expression)
    2961
    2962        if isinstance(expression, int):
    2963            return str(expression)
    2964
    2965        if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE:
    2966            escaped = expression.replace("'", "\\'")
    2967            escaped = f"\\'{expression}\\'"
    2968        else:
    2969            escaped = expression.replace('"', '\\"')
    2970            escaped = f'"{escaped}"'
    2971
    2972        return escaped

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

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

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

    2977    def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str:
    2978        null_handling = expression.args.get("null_handling")
    2979        null_handling = f" {null_handling}" if null_handling else ""
    2980
    2981        unique_keys = expression.args.get("unique_keys")
    2982        if unique_keys is not None:
    2983            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    2984        else:
    2985            unique_keys = ""
    2986
    2987        return_type = self.sql(expression, "return_type")
    2988        return_type = f" RETURNING {return_type}" if return_type else ""
    2989        encoding = self.sql(expression, "encoding")
    2990        encoding = f" ENCODING {encoding}" if encoding else ""
    2991
    2992        return self.func(
    2993            "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG",
    2994            *expression.expressions,
    2995            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
    2996        )

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

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

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

    3001    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
    3002        null_handling = expression.args.get("null_handling")
    3003        null_handling = f" {null_handling}" if null_handling else ""
    3004        return_type = self.sql(expression, "return_type")
    3005        return_type = f" RETURNING {return_type}" if return_type else ""
    3006        strict = " STRICT" if expression.args.get("strict") else ""
    3007        return self.func(
    3008            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
    3009        )

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

    3011    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
    3012        this = self.sql(expression, "this")
    3013        order = self.sql(expression, "order")
    3014        null_handling = expression.args.get("null_handling")
    3015        null_handling = f" {null_handling}" if null_handling else ""
    3016        return_type = self.sql(expression, "return_type")
    3017        return_type = f" RETURNING {return_type}" if return_type else ""
    3018        strict = " STRICT" if expression.args.get("strict") else ""
    3019        return self.func(
    3020            "JSON_ARRAYAGG",
    3021            this,
    3022            suffix=f"{order}{null_handling}{return_type}{strict})",
    3023        )

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

    3025    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
    3026        path = self.sql(expression, "path")
    3027        path = f" PATH {path}" if path else ""
    3028        nested_schema = self.sql(expression, "nested_schema")
    3029
    3030        if nested_schema:
    3031            return f"NESTED{path} {nested_schema}"
    3032
    3033        this = self.sql(expression, "this")
    3034        kind = self.sql(expression, "kind")
    3035        kind = f" {kind}" if kind else ""
    3036        return f"{this}{kind}{path}"

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

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

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

    3041    def jsontable_sql(self, expression: exp.JSONTable) -> str:
    3042        this = self.sql(expression, "this")
    3043        path = self.sql(expression, "path")
    3044        path = f", {path}" if path else ""
    3045        error_handling = expression.args.get("error_handling")
    3046        error_handling = f" {error_handling}" if error_handling else ""
    3047        empty_handling = expression.args.get("empty_handling")
    3048        empty_handling = f" {empty_handling}" if empty_handling else ""
    3049        schema = self.sql(expression, "schema")
    3050        return self.func(
    3051            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
    3052        )

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

    3054    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    3055        this = self.sql(expression, "this")
    3056        kind = self.sql(expression, "kind")
    3057        path = self.sql(expression, "path")
    3058        path = f" {path}" if path else ""
    3059        as_json = " AS JSON" if expression.args.get("as_json") else ""
    3060        return f"{this} {kind}{path}{as_json}"

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

    3062    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    3063        this = self.sql(expression, "this")
    3064        path = self.sql(expression, "path")
    3065        path = f", {path}" if path else ""
    3066        expressions = self.expressions(expression)
    3067        with_ = (
    3068            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    3069            if expressions
    3070            else ""
    3071        )
    3072        return f"OPENJSON({this}{path}){with_}"

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

    3074    def in_sql(self, expression: exp.In) -> str:
    3075        query = expression.args.get("query")
    3076        unnest = expression.args.get("unnest")
    3077        field = expression.args.get("field")
    3078        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    3079
    3080        if query:
    3081            in_sql = self.sql(query)
    3082        elif unnest:
    3083            in_sql = self.in_unnest_op(unnest)
    3084        elif field:
    3085            in_sql = self.sql(field)
    3086        else:
    3087            in_sql = f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})"
    3088
    3089        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"

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

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

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

    3094    def interval_sql(self, expression: exp.Interval) -> str:
    3095        unit = self.sql(expression, "unit")
    3096        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    3097            unit = self.TIME_PART_SINGULARS.get(unit, unit)
    3098        unit = f" {unit}" if unit else ""
    3099
    3100        if self.SINGLE_STRING_INTERVAL:
    3101            this = expression.this.name if expression.this else ""
    3102            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    3103
    3104        this = self.sql(expression, "this")
    3105        if this:
    3106            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    3107            this = f" {this}" if unwrapped else f" ({this})"
    3108
    3109        return f"INTERVAL{this}{unit}"

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

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

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

    3114    def reference_sql(self, expression: exp.Reference) -> str:
    3115        this = self.sql(expression, "this")
    3116        expressions = self.expressions(expression, flat=True)
    3117        expressions = f"({expressions})" if expressions else ""
    3118        options = self.expressions(expression, key="options", flat=True, sep=" ")
    3119        options = f" {options}" if options else ""
    3120        return f"REFERENCES {this}{expressions}{options}"

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

    3122    def anonymous_sql(self, expression: exp.Anonymous) -> str:
    3123        # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive
    3124        parent = expression.parent
    3125        is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression
    3126        return self.func(
    3127            self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified
    3128        )

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

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

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

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

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

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

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

    3143    def alias_sql(self, expression: exp.Alias) -> str:
    3144        alias = self.sql(expression, "alias")
    3145        alias = f" AS {alias}" if alias else ""
    3146        return f"{self.sql(expression, 'this')}{alias}"

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

    3148    def pivotalias_sql(self, expression: exp.PivotAlias) -> str:
    3149        alias = expression.args["alias"]
    3150
    3151        parent = expression.parent
    3152        pivot = parent and parent.parent
    3153
    3154        if isinstance(pivot, exp.Pivot) and pivot.unpivot:
    3155            identifier_alias = isinstance(alias, exp.Identifier)
    3156            literal_alias = isinstance(alias, exp.Literal)
    3157
    3158            if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    3159                alias.replace(exp.Literal.string(alias.output_name))
    3160            elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    3161                alias.replace(exp.to_identifier(alias.output_name))
    3162
    3163        return self.alias_sql(expression)

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

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

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

    3168    def atindex_sql(self, expression: exp.AtTimeZone) -> str:
    3169        this = self.sql(expression, "this")
    3170        index = self.sql(expression, "expression")
    3171        return f"{this} AT {index}"

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

    3173    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    3174        this = self.sql(expression, "this")
    3175        zone = self.sql(expression, "zone")
    3176        return f"{this} AT TIME ZONE {zone}"

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

    3178    def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str:
    3179        this = self.sql(expression, "this")
    3180        zone = self.sql(expression, "zone")
    3181        return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'"

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

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

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

    3186    def and_sql(
    3187        self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None
    3188    ) -> str:
    3189        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

    3191    def or_sql(
    3192        self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None
    3193    ) -> str:
    3194        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

    3196    def xor_sql(
    3197        self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None
    3198    ) -> str:
    3199        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

    3201    def connector_sql(
    3202        self,
    3203        expression: exp.Connector,
    3204        op: str,
    3205        stack: t.Optional[t.List[str | exp.Expression]] = None,
    3206    ) -> str:
    3207        if stack is not None:
    3208            if expression.expressions:
    3209                stack.append(self.expressions(expression, sep=f" {op} "))
    3210            else:
    3211                stack.append(expression.right)
    3212                if expression.comments and self.comments:
    3213                    for comment in expression.comments:
    3214                        if comment:
    3215                            op += f" /*{self.pad_comment(comment)}*/"
    3216                stack.extend((op, expression.left))
    3217            return op
    3218
    3219        stack = [expression]
    3220        sqls: t.List[str] = []
    3221        ops = set()
    3222
    3223        while stack:
    3224            node = stack.pop()
    3225            if isinstance(node, exp.Connector):
    3226                ops.add(getattr(self, f"{node.key}_sql")(node, stack))
    3227            else:
    3228                sql = self.sql(node)
    3229                if sqls and sqls[-1] in ops:
    3230                    sqls[-1] += f" {sql}"
    3231                else:
    3232                    sqls.append(sql)
    3233
    3234        sep = "\n" if self.pretty and self.too_wide(sqls) else " "
    3235        return sep.join(sqls)

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

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

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

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

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

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

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

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

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

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

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

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

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

    3255    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    3256        format_sql = self.sql(expression, "format")
    3257        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    3258        to_sql = self.sql(expression, "to")
    3259        to_sql = f" {to_sql}" if to_sql else ""
    3260        action = self.sql(expression, "action")
    3261        action = f" {action}" if action else ""
    3262        default = self.sql(expression, "default")
    3263        default = f" DEFAULT {default} ON CONVERSION ERROR" if default else ""
    3264        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

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

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

    3270    def collate_sql(self, expression: exp.Collate) -> str:
    3271        if self.COLLATE_IS_FUNC:
    3272            return self.function_fallback_sql(expression)
    3273        return self.binary(expression, "COLLATE")

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

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

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

    3278    def comment_sql(self, expression: exp.Comment) -> str:
    3279        this = self.sql(expression, "this")
    3280        kind = expression.args["kind"]
    3281        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    3282        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    3283        expression_sql = self.sql(expression, "expression")
    3284        return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"

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

    3286    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    3287        this = self.sql(expression, "this")
    3288        delete = " DELETE" if expression.args.get("delete") else ""
    3289        recompress = self.sql(expression, "recompress")
    3290        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    3291        to_disk = self.sql(expression, "to_disk")
    3292        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    3293        to_volume = self.sql(expression, "to_volume")
    3294        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    3295        return f"{this}{delete}{recompress}{to_disk}{to_volume}"

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

    3297    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    3298        where = self.sql(expression, "where")
    3299        group = self.sql(expression, "group")
    3300        aggregates = self.expressions(expression, key="aggregates")
    3301        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    3302
    3303        if not (where or group or aggregates) and len(expression.expressions) == 1:
    3304            return f"TTL {self.expressions(expression, flat=True)}"
    3305
    3306        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"

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

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

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

    3311    def commit_sql(self, expression: exp.Commit) -> str:
    3312        chain = expression.args.get("chain")
    3313        if chain is not None:
    3314            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    3315
    3316        return f"COMMIT{chain or ''}"

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

    3318    def rollback_sql(self, expression: exp.Rollback) -> str:
    3319        savepoint = expression.args.get("savepoint")
    3320        savepoint = f" TO {savepoint}" if savepoint else ""
    3321        return f"ROLLBACK{savepoint}"

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

    3323    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    3324        this = self.sql(expression, "this")
    3325
    3326        dtype = self.sql(expression, "dtype")
    3327        if dtype:
    3328            collate = self.sql(expression, "collate")
    3329            collate = f" COLLATE {collate}" if collate else ""
    3330            using = self.sql(expression, "using")
    3331            using = f" USING {using}" if using else ""
    3332            return f"ALTER COLUMN {this} {self.ALTER_SET_TYPE} {dtype}{collate}{using}"
    3333
    3334        default = self.sql(expression, "default")
    3335        if default:
    3336            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    3337
    3338        comment = self.sql(expression, "comment")
    3339        if comment:
    3340            return f"ALTER COLUMN {this} COMMENT {comment}"
    3341
    3342        visible = expression.args.get("visible")
    3343        if visible:
    3344            return f"ALTER COLUMN {this} SET {visible}"
    3345
    3346        allow_null = expression.args.get("allow_null")
    3347        drop = expression.args.get("drop")
    3348
    3349        if not drop and not allow_null:
    3350            self.unsupported("Unsupported ALTER COLUMN syntax")
    3351
    3352        if allow_null is not None:
    3353            keyword = "DROP" if drop else "SET"
    3354            return f"ALTER COLUMN {this} {keyword} NOT NULL"
    3355
    3356        return f"ALTER COLUMN {this} DROP DEFAULT"

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

    3358    def alterindex_sql(self, expression: exp.AlterIndex) -> str:
    3359        this = self.sql(expression, "this")
    3360
    3361        visible = expression.args.get("visible")
    3362        visible_sql = "VISIBLE" if visible else "INVISIBLE"
    3363
    3364        return f"ALTER INDEX {this} {visible_sql}"

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

    3366    def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str:
    3367        this = self.sql(expression, "this")
    3368        if not isinstance(expression.this, exp.Var):
    3369            this = f"KEY DISTKEY {this}"
    3370        return f"ALTER DISTSTYLE {this}"

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

    3372    def altersortkey_sql(self, expression: exp.AlterSortKey) -> str:
    3373        compound = " COMPOUND" if expression.args.get("compound") else ""
    3374        this = self.sql(expression, "this")
    3375        expressions = self.expressions(expression, flat=True)
    3376        expressions = f"({expressions})" if expressions else ""
    3377        return f"ALTER{compound} SORTKEY {this or expressions}"

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

    3379    def alterrename_sql(self, expression: exp.AlterRename) -> str:
    3380        if not self.RENAME_TABLE_WITH_DB:
    3381            # Remove db from tables
    3382            expression = expression.transform(
    3383                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    3384            ).assert_is(exp.AlterRename)
    3385        this = self.sql(expression, "this")
    3386        return f"RENAME TO {this}"

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

    3388    def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
    3389        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3390        old_column = self.sql(expression, "this")
    3391        new_column = self.sql(expression, "to")
    3392        return f"RENAME COLUMN{exists} {old_column} TO {new_column}"

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

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

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

    3398    def alter_sql(self, expression: exp.Alter) -> str:
    3399        actions = expression.args["actions"]
    3400
    3401        if isinstance(actions[0], exp.ColumnDef):
    3402            actions = self.add_column_sql(expression)
    3403        elif isinstance(actions[0], exp.Schema):
    3404            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    3405        elif isinstance(actions[0], exp.Delete):
    3406            actions = self.expressions(expression, key="actions", flat=True)
    3407        elif isinstance(actions[0], exp.Query):
    3408            actions = "AS " + self.expressions(expression, key="actions")
    3409        else:
    3410            actions = self.expressions(expression, key="actions", flat=True)
    3411
    3412        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3413        on_cluster = self.sql(expression, "cluster")
    3414        on_cluster = f" {on_cluster}" if on_cluster else ""
    3415        only = " ONLY" if expression.args.get("only") else ""
    3416        options = self.expressions(expression, key="options")
    3417        options = f", {options}" if options else ""
    3418        kind = self.sql(expression, "kind")
    3419        not_valid = " NOT VALID" if expression.args.get("not_valid") else ""
    3420
    3421        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

    3423    def add_column_sql(self, expression: exp.Alter) -> str:
    3424        if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD:
    3425            return self.expressions(
    3426                expression,
    3427                key="actions",
    3428                prefix="ADD COLUMN ",
    3429                skip_first=True,
    3430            )
    3431        return f"ADD {self.expressions(expression, key='actions', flat=True)}"

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

    3433    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    3434        expressions = self.expressions(expression)
    3435        exists = " IF EXISTS " if expression.args.get("exists") else " "
    3436        return f"DROP{exists}{expressions}"

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

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

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

    3441    def distinct_sql(self, expression: exp.Distinct) -> str:
    3442        this = self.expressions(expression, flat=True)
    3443
    3444        if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1:
    3445            case = exp.case()
    3446            for arg in expression.expressions:
    3447                case = case.when(arg.is_(exp.null()), exp.null())
    3448            this = self.sql(case.else_(f"({this})"))
    3449
    3450        this = f" {this}" if this else ""
    3451
    3452        on = self.sql(expression, "on")
    3453        on = f" ON {on}" if on else ""
    3454        return f"DISTINCT{this}{on}"

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

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

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

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

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

    3462    def havingmax_sql(self, expression: exp.HavingMax) -> str:
    3463        this_sql = self.sql(expression, "this")
    3464        expression_sql = self.sql(expression, "expression")
    3465        kind = "MAX" if expression.args.get("max") else "MIN"
    3466        return f"{this_sql} HAVING {kind} {expression_sql}"

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

    3468    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    3469        return self.sql(
    3470            exp.Cast(
    3471                this=exp.Div(this=expression.this, expression=expression.expression),
    3472                to=exp.DataType(this=exp.DataType.Type.INT),
    3473            )
    3474        )

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

    3476    def dpipe_sql(self, expression: exp.DPipe) -> str:
    3477        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    3478            return self.func(
    3479                "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten())
    3480            )
    3481        return self.binary(expression, "||")

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

    3483    def div_sql(self, expression: exp.Div) -> str:
    3484        l, r = expression.left, expression.right
    3485
    3486        if not self.dialect.SAFE_DIVISION and expression.args.get("safe"):
    3487            r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0)))
    3488
    3489        if self.dialect.TYPED_DIVISION and not expression.args.get("typed"):
    3490            if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES):
    3491                l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE))
    3492
    3493        elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"):
    3494            if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES):
    3495                return self.sql(
    3496                    exp.cast(
    3497                        l / r,
    3498                        to=exp.DataType.Type.BIGINT,
    3499                    )
    3500                )
    3501
    3502        return self.binary(expression, "/")

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

    3504    def safedivide_sql(self, expression: exp.SafeDivide) -> str:
    3505        n = exp._wrap(expression.this, exp.Binary)
    3506        d = exp._wrap(expression.expression, exp.Binary)
    3507        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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3542    def is_sql(self, expression: exp.Is) -> str:
    3543        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    3544            return self.sql(
    3545                expression.this if expression.expression.this else exp.not_(expression.this)
    3546            )
    3547        return self.binary(expression, "IS")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3591    def try_sql(self, expression: exp.Try) -> str:
    3592        if not self.TRY_SUPPORTED:
    3593            self.unsupported("Unsupported TRY function")
    3594            return self.sql(expression, "this")
    3595
    3596        return self.func("TRY", expression.this)

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

    3598    def log_sql(self, expression: exp.Log) -> str:
    3599        this = expression.this
    3600        expr = expression.expression
    3601
    3602        if self.dialect.LOG_BASE_FIRST is False:
    3603            this, expr = expr, this
    3604        elif self.dialect.LOG_BASE_FIRST is None and expr:
    3605            if this.name in ("2", "10"):
    3606                return self.func(f"LOG{this.name}", expr)
    3607
    3608            self.unsupported(f"Unsupported logarithm with base {self.sql(this)}")
    3609
    3610        return self.func("LOG", this, expr)

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

    3612    def use_sql(self, expression: exp.Use) -> str:
    3613        kind = self.sql(expression, "kind")
    3614        kind = f" {kind}" if kind else ""
    3615        this = self.sql(expression, "this") or self.expressions(expression, flat=True)
    3616        this = f" {this}" if this else ""
    3617        return f"USE{kind}{this}"

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

    3619    def binary(self, expression: exp.Binary, op: str) -> str:
    3620        sqls: t.List[str] = []
    3621        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    3622        binary_type = type(expression)
    3623
    3624        while stack:
    3625            node = stack.pop()
    3626
    3627            if type(node) is binary_type:
    3628                op_func = node.args.get("operator")
    3629                if op_func:
    3630                    op = f"OPERATOR({self.sql(op_func)})"
    3631
    3632                stack.append(node.right)
    3633                stack.append(f" {self.maybe_comment(op, comments=node.comments)} ")
    3634                stack.append(node.left)
    3635            else:
    3636                sqls.append(self.sql(node))
    3637
    3638        return "".join(sqls)

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

    3640    def ceil_floor(self, expression: exp.Ceil | exp.Floor) -> str:
    3641        to_clause = self.sql(expression, "to")
    3642        if to_clause:
    3643            return f"{expression.sql_name()}({self.sql(expression, 'this')} TO {to_clause})"
    3644
    3645        return self.function_fallback_sql(expression)

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

    3647    def function_fallback_sql(self, expression: exp.Func) -> str:
    3648        args = []
    3649
    3650        for key in expression.arg_types:
    3651            arg_value = expression.args.get(key)
    3652
    3653            if isinstance(arg_value, list):
    3654                for value in arg_value:
    3655                    args.append(value)
    3656            elif arg_value is not None:
    3657                args.append(arg_value)
    3658
    3659        if self.dialect.PRESERVE_ORIGINAL_NAMES:
    3660            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
    3661        else:
    3662            name = expression.sql_name()
    3663
    3664        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

    3666    def func(
    3667        self,
    3668        name: str,
    3669        *args: t.Optional[exp.Expression | str],
    3670        prefix: str = "(",
    3671        suffix: str = ")",
    3672        normalize: bool = True,
    3673    ) -> str:
    3674        name = self.normalize_func(name) if normalize else name
    3675        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

    3677    def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str:
    3678        arg_sqls = tuple(
    3679            self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool)
    3680        )
    3681        if self.pretty and self.too_wide(arg_sqls):
    3682            return self.indent(
    3683                "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True
    3684            )
    3685        return sep.join(arg_sqls)

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

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

    3690    def format_time(
    3691        self,
    3692        expression: exp.Expression,
    3693        inverse_time_mapping: t.Optional[t.Dict[str, str]] = None,
    3694        inverse_time_trie: t.Optional[t.Dict] = None,
    3695    ) -> t.Optional[str]:
    3696        return format_time(
    3697            self.sql(expression, "format"),
    3698            inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING,
    3699            inverse_time_trie or self.dialect.INVERSE_TIME_TRIE,
    3700        )

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

    3702    def expressions(
    3703        self,
    3704        expression: t.Optional[exp.Expression] = None,
    3705        key: t.Optional[str] = None,
    3706        sqls: t.Optional[t.Collection[str | exp.Expression]] = None,
    3707        flat: bool = False,
    3708        indent: bool = True,
    3709        skip_first: bool = False,
    3710        skip_last: bool = False,
    3711        sep: str = ", ",
    3712        prefix: str = "",
    3713        dynamic: bool = False,
    3714        new_line: bool = False,
    3715    ) -> str:
    3716        expressions = expression.args.get(key or "expressions") if expression else sqls
    3717
    3718        if not expressions:
    3719            return ""
    3720
    3721        if flat:
    3722            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
    3723
    3724        num_sqls = len(expressions)
    3725        result_sqls = []
    3726
    3727        for i, e in enumerate(expressions):
    3728            sql = self.sql(e, comment=False)
    3729            if not sql:
    3730                continue
    3731
    3732            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    3733
    3734            if self.pretty:
    3735                if self.leading_comma:
    3736                    result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}")
    3737                else:
    3738                    result_sqls.append(
    3739                        f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}"
    3740                    )
    3741            else:
    3742                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    3743
    3744        if self.pretty and (not dynamic or self.too_wide(result_sqls)):
    3745            if new_line:
    3746                result_sqls.insert(0, "")
    3747                result_sqls.append("")
    3748            result_sql = "\n".join(s.rstrip() for s in result_sqls)
    3749        else:
    3750            result_sql = "".join(result_sqls)
    3751
    3752        return (
    3753            self.indent(result_sql, skip_first=skip_first, skip_last=skip_last)
    3754            if indent
    3755            else result_sql
    3756        )

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

    3758    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    3759        flat = flat or isinstance(expression.parent, exp.Properties)
    3760        expressions_sql = self.expressions(expression, flat=flat)
    3761        if flat:
    3762            return f"{op} {expressions_sql}"
    3763        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"

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

    3765    def naked_property(self, expression: exp.Property) -> str:
    3766        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    3767        if not property_name:
    3768            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    3769        return f"{property_name} {self.sql(expression, 'this')}"

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

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

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

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

    3777    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    3778        this = self.sql(expression, "this")
    3779        expressions = self.no_identify(self.expressions, expression)
    3780        expressions = (
    3781            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    3782        )
    3783        return f"{this}{expressions}" if expressions.strip() != "" else this

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

    3785    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    3786        this = self.sql(expression, "this")
    3787        expressions = self.expressions(expression, flat=True)
    3788        return f"{this}({expressions})"

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

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

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

    3793    def when_sql(self, expression: exp.When) -> str:
    3794        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    3795        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    3796        condition = self.sql(expression, "condition")
    3797        condition = f" AND {condition}" if condition else ""
    3798
    3799        then_expression = expression.args.get("then")
    3800        if isinstance(then_expression, exp.Insert):
    3801            this = self.sql(then_expression, "this")
    3802            this = f"INSERT {this}" if this else "INSERT"
    3803            then = self.sql(then_expression, "expression")
    3804            then = f"{this} VALUES {then}" if then else this
    3805        elif isinstance(then_expression, exp.Update):
    3806            if isinstance(then_expression.args.get("expressions"), exp.Star):
    3807                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    3808            else:
    3809                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    3810        else:
    3811            then = self.sql(then_expression)
    3812        return f"WHEN {matched}{source}{condition} THEN {then}"

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

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

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

    3817    def merge_sql(self, expression: exp.Merge) -> str:
    3818        table = expression.this
    3819        table_alias = ""
    3820
    3821        hints = table.args.get("hints")
    3822        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
    3823            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
    3824            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
    3825
    3826        this = self.sql(table)
    3827        using = f"USING {self.sql(expression, 'using')}"
    3828        on = f"ON {self.sql(expression, 'on')}"
    3829        whens = self.sql(expression, "whens")
    3830
    3831        returning = self.sql(expression, "returning")
    3832        if returning:
    3833            whens = f"{whens}{returning}"
    3834
    3835        sep = self.sep()
    3836
    3837        return self.prepend_ctes(
    3838            expression,
    3839            f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}",
    3840        )

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

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

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

    3846    def tonumber_sql(self, expression: exp.ToNumber) -> str:
    3847        if not self.SUPPORTS_TO_NUMBER:
    3848            self.unsupported("Unsupported TO_NUMBER function")
    3849            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3850
    3851        fmt = expression.args.get("format")
    3852        if not fmt:
    3853            self.unsupported("Conversion format is required for TO_NUMBER")
    3854            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3855
    3856        return self.func("TO_NUMBER", expression.this, fmt)

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

    3858    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    3859        this = self.sql(expression, "this")
    3860        kind = self.sql(expression, "kind")
    3861        settings_sql = self.expressions(expression, key="settings", sep=" ")
    3862        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    3863        return f"{this}({kind}{args})"

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

    3865    def dictrange_sql(self, expression: exp.DictRange) -> str:
    3866        this = self.sql(expression, "this")
    3867        max = self.sql(expression, "max")
    3868        min = self.sql(expression, "min")
    3869        return f"{this}(MIN {min} MAX {max})"

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

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

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

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

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

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

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

    3882    def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str:
    3883        expressions = self.expressions(expression, flat=True)
    3884        expressions = f" {self.wrap(expressions)}" if expressions else ""
    3885        buckets = self.sql(expression, "buckets")
    3886        kind = self.sql(expression, "kind")
    3887        buckets = f" BUCKETS {buckets}" if buckets else ""
    3888        order = self.sql(expression, "order")
    3889        return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}"

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

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

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

    3894    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    3895        expressions = self.expressions(expression, key="expressions", flat=True)
    3896        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    3897        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    3898        buckets = self.sql(expression, "buckets")
    3899        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"

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

    3901    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    3902        this = self.sql(expression, "this")
    3903        having = self.sql(expression, "having")
    3904
    3905        if having:
    3906            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    3907
    3908        return self.func("ANY_VALUE", this)

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

    3910    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
    3911        transform = self.func("TRANSFORM", *expression.expressions)
    3912        row_format_before = self.sql(expression, "row_format_before")
    3913        row_format_before = f" {row_format_before}" if row_format_before else ""
    3914        record_writer = self.sql(expression, "record_writer")
    3915        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
    3916        using = f" USING {self.sql(expression, 'command_script')}"
    3917        schema = self.sql(expression, "schema")
    3918        schema = f" AS {schema}" if schema else ""
    3919        row_format_after = self.sql(expression, "row_format_after")
    3920        row_format_after = f" {row_format_after}" if row_format_after else ""
    3921        record_reader = self.sql(expression, "record_reader")
    3922        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
    3923        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

    3925    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
    3926        key_block_size = self.sql(expression, "key_block_size")
    3927        if key_block_size:
    3928            return f"KEY_BLOCK_SIZE = {key_block_size}"
    3929
    3930        using = self.sql(expression, "using")
    3931        if using:
    3932            return f"USING {using}"
    3933
    3934        parser = self.sql(expression, "parser")
    3935        if parser:
    3936            return f"WITH PARSER {parser}"
    3937
    3938        comment = self.sql(expression, "comment")
    3939        if comment:
    3940            return f"COMMENT {comment}"
    3941
    3942        visible = expression.args.get("visible")
    3943        if visible is not None:
    3944            return "VISIBLE" if visible else "INVISIBLE"
    3945
    3946        engine_attr = self.sql(expression, "engine_attr")
    3947        if engine_attr:
    3948            return f"ENGINE_ATTRIBUTE = {engine_attr}"
    3949
    3950        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
    3951        if secondary_engine_attr:
    3952            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
    3953
    3954        self.unsupported("Unsupported index constraint option.")
    3955        return ""

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

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

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

    3961    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
    3962        kind = self.sql(expression, "kind")
    3963        kind = f"{kind} INDEX" if kind else "INDEX"
    3964        this = self.sql(expression, "this")
    3965        this = f" {this}" if this else ""
    3966        index_type = self.sql(expression, "index_type")
    3967        index_type = f" USING {index_type}" if index_type else ""
    3968        expressions = self.expressions(expression, flat=True)
    3969        expressions = f" ({expressions})" if expressions else ""
    3970        options = self.expressions(expression, key="options", sep=" ")
    3971        options = f" {options}" if options else ""
    3972        return f"{kind}{this}{index_type}{expressions}{options}"

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

    3974    def nvl2_sql(self, expression: exp.Nvl2) -> str:
    3975        if self.NVL2_SUPPORTED:
    3976            return self.function_fallback_sql(expression)
    3977
    3978        case = exp.Case().when(
    3979            expression.this.is_(exp.null()).not_(copy=False),
    3980            expression.args["true"],
    3981            copy=False,
    3982        )
    3983        else_cond = expression.args.get("false")
    3984        if else_cond:
    3985            case.else_(else_cond, copy=False)
    3986
    3987        return self.sql(case)

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

    3989    def comprehension_sql(self, expression: exp.Comprehension) -> str:
    3990        this = self.sql(expression, "this")
    3991        expr = self.sql(expression, "expression")
    3992        iterator = self.sql(expression, "iterator")
    3993        condition = self.sql(expression, "condition")
    3994        condition = f" IF {condition}" if condition else ""
    3995        return f"{this} FOR {expr} IN {iterator}{condition}"

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

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

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

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

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

    4003    def predict_sql(self, expression: exp.Predict) -> str:
    4004        model = self.sql(expression, "this")
    4005        model = f"MODEL {model}"
    4006        table = self.sql(expression, "expression")
    4007        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
    4008        parameters = self.sql(expression, "params_struct")
    4009        return self.func("PREDICT", model, table, parameters or None)

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

    4011    def forin_sql(self, expression: exp.ForIn) -> str:
    4012        this = self.sql(expression, "this")
    4013        expression_sql = self.sql(expression, "expression")
    4014        return f"FOR {this} DO {expression_sql}"

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

    4016    def refresh_sql(self, expression: exp.Refresh) -> str:
    4017        this = self.sql(expression, "this")
    4018        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
    4019        return f"REFRESH {table}{this}"

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

    4021    def toarray_sql(self, expression: exp.ToArray) -> str:
    4022        arg = expression.this
    4023        if not arg.type:
    4024            from sqlglot.optimizer.annotate_types import annotate_types
    4025
    4026            arg = annotate_types(arg, dialect=self.dialect)
    4027
    4028        if arg.is_type(exp.DataType.Type.ARRAY):
    4029            return self.sql(arg)
    4030
    4031        cond_for_null = arg.is_(exp.null())
    4032        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

    4034    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
    4035        this = expression.this
    4036        time_format = self.format_time(expression)
    4037
    4038        if time_format:
    4039            return self.sql(
    4040                exp.cast(
    4041                    exp.StrToTime(this=this, format=expression.args["format"]),
    4042                    exp.DataType.Type.TIME,
    4043                )
    4044            )
    4045
    4046        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
    4047            return self.sql(this)
    4048
    4049        return self.sql(exp.cast(this, exp.DataType.Type.TIME))

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

    4051    def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str:
    4052        this = expression.this
    4053        if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP):
    4054            return self.sql(this)
    4055
    4056        return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect))

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

    4058    def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str:
    4059        this = expression.this
    4060        if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME):
    4061            return self.sql(this)
    4062
    4063        return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect))

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

    4065    def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:
    4066        this = expression.this
    4067        time_format = self.format_time(expression)
    4068
    4069        if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT):
    4070            return self.sql(
    4071                exp.cast(
    4072                    exp.StrToTime(this=this, format=expression.args["format"]),
    4073                    exp.DataType.Type.DATE,
    4074                )
    4075            )
    4076
    4077        if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE):
    4078            return self.sql(this)
    4079
    4080        return self.sql(exp.cast(this, exp.DataType.Type.DATE))

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

    4082    def unixdate_sql(self, expression: exp.UnixDate) -> str:
    4083        return self.sql(
    4084            exp.func(
    4085                "DATEDIFF",
    4086                expression.this,
    4087                exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE),
    4088                "day",
    4089            )
    4090        )

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

    4092    def lastday_sql(self, expression: exp.LastDay) -> str:
    4093        if self.LAST_DAY_SUPPORTS_DATE_PART:
    4094            return self.function_fallback_sql(expression)
    4095
    4096        unit = expression.text("unit")
    4097        if unit and unit != "MONTH":
    4098            self.unsupported("Date parts are not supported in LAST_DAY.")
    4099
    4100        return self.func("LAST_DAY", expression.this)

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

    4102    def dateadd_sql(self, expression: exp.DateAdd) -> str:
    4103        from sqlglot.dialects.dialect import unit_to_str
    4104
    4105        return self.func(
    4106            "DATE_ADD", expression.this, expression.expression, unit_to_str(expression)
    4107        )

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

    4109    def arrayany_sql(self, expression: exp.ArrayAny) -> str:
    4110        if self.CAN_IMPLEMENT_ARRAY_ANY:
    4111            filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression)
    4112            filtered_not_empty = exp.ArraySize(this=filtered).neq(0)
    4113            original_is_empty = exp.ArraySize(this=expression.this).eq(0)
    4114            return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty)))
    4115
    4116        from sqlglot.dialects import Dialect
    4117
    4118        # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect
    4119        if self.dialect.__class__ != Dialect:
    4120            self.unsupported("ARRAY_ANY is unsupported")
    4121
    4122        return self.function_fallback_sql(expression)

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

    4124    def struct_sql(self, expression: exp.Struct) -> str:
    4125        expression.set(
    4126            "expressions",
    4127            [
    4128                exp.alias_(e.expression, e.name if e.this.is_string else e.this)
    4129                if isinstance(e, exp.PropertyEQ)
    4130                else e
    4131                for e in expression.expressions
    4132            ],
    4133        )
    4134
    4135        return self.function_fallback_sql(expression)

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

    4137    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
    4138        low = self.sql(expression, "this")
    4139        high = self.sql(expression, "expression")
    4140
    4141        return f"{low} TO {high}"

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

    4143    def truncatetable_sql(self, expression: exp.TruncateTable) -> str:
    4144        target = "DATABASE" if expression.args.get("is_database") else "TABLE"
    4145        tables = f" {self.expressions(expression)}"
    4146
    4147        exists = " IF EXISTS" if expression.args.get("exists") else ""
    4148
    4149        on_cluster = self.sql(expression, "cluster")
    4150        on_cluster = f" {on_cluster}" if on_cluster else ""
    4151
    4152        identity = self.sql(expression, "identity")
    4153        identity = f" {identity} IDENTITY" if identity else ""
    4154
    4155        option = self.sql(expression, "option")
    4156        option = f" {option}" if option else ""
    4157
    4158        partition = self.sql(expression, "partition")
    4159        partition = f" {partition}" if partition else ""
    4160
    4161        return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"

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

    4165    def convert_sql(self, expression: exp.Convert) -> str:
    4166        to = expression.this
    4167        value = expression.expression
    4168        style = expression.args.get("style")
    4169        safe = expression.args.get("safe")
    4170        strict = expression.args.get("strict")
    4171
    4172        if not to or not value:
    4173            return ""
    4174
    4175        # Retrieve length of datatype and override to default if not specified
    4176        if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    4177            to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
    4178
    4179        transformed: t.Optional[exp.Expression] = None
    4180        cast = exp.Cast if strict else exp.TryCast
    4181
    4182        # Check whether a conversion with format (T-SQL calls this 'style') is applicable
    4183        if isinstance(style, exp.Literal) and style.is_int:
    4184            from sqlglot.dialects.tsql import TSQL
    4185
    4186            style_value = style.name
    4187            converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value)
    4188            if not converted_style:
    4189                self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}")
    4190
    4191            fmt = exp.Literal.string(converted_style)
    4192
    4193            if to.this == exp.DataType.Type.DATE:
    4194                transformed = exp.StrToDate(this=value, format=fmt)
    4195            elif to.this in (exp.DataType.Type.DATETIME, exp.DataType.Type.DATETIME2):
    4196                transformed = exp.StrToTime(this=value, format=fmt)
    4197            elif to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    4198                transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe)
    4199            elif to.this == exp.DataType.Type.TEXT:
    4200                transformed = exp.TimeToStr(this=value, format=fmt)
    4201
    4202        if not transformed:
    4203            transformed = cast(this=value, to=to, safe=safe)
    4204
    4205        return self.sql(transformed)

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

    4265    def copyparameter_sql(self, expression: exp.CopyParameter) -> str:
    4266        option = self.sql(expression, "this")
    4267
    4268        if expression.expressions:
    4269            upper = option.upper()
    4270
    4271            # Snowflake FILE_FORMAT options are separated by whitespace
    4272            sep = " " if upper == "FILE_FORMAT" else ", "
    4273
    4274            # Databricks copy/format options do not set their list of values with EQ
    4275            op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = "
    4276            values = self.expressions(expression, flat=True, sep=sep)
    4277            return f"{option}{op}({values})"
    4278
    4279        value = self.sql(expression, "expression")
    4280
    4281        if not value:
    4282            return option
    4283
    4284        op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " "
    4285
    4286        return f"{option}{op}{value}"

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

    4288    def credentials_sql(self, expression: exp.Credentials) -> str:
    4289        cred_expr = expression.args.get("credentials")
    4290        if isinstance(cred_expr, exp.Literal):
    4291            # Redshift case: CREDENTIALS <string>
    4292            credentials = self.sql(expression, "credentials")
    4293            credentials = f"CREDENTIALS {credentials}" if credentials else ""
    4294        else:
    4295            # Snowflake case: CREDENTIALS = (...)
    4296            credentials = self.expressions(expression, key="credentials", flat=True, sep=" ")
    4297            credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else ""
    4298
    4299        storage = self.sql(expression, "storage")
    4300        storage = f"STORAGE_INTEGRATION = {storage}" if storage else ""
    4301
    4302        encryption = self.expressions(expression, key="encryption", flat=True, sep=" ")
    4303        encryption = f" ENCRYPTION = ({encryption})" if encryption else ""
    4304
    4305        iam_role = self.sql(expression, "iam_role")
    4306        iam_role = f"IAM_ROLE {iam_role}" if iam_role else ""
    4307
    4308        region = self.sql(expression, "region")
    4309        region = f" REGION {region}" if region else ""
    4310
    4311        return f"{credentials}{storage}{encryption}{iam_role}{region}"

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

    4313    def copy_sql(self, expression: exp.Copy) -> str:
    4314        this = self.sql(expression, "this")
    4315        this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}"
    4316
    4317        credentials = self.sql(expression, "credentials")
    4318        credentials = self.seg(credentials) if credentials else ""
    4319        kind = self.seg("FROM" if expression.args.get("kind") else "TO")
    4320        files = self.expressions(expression, key="files", flat=True)
    4321
    4322        sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " "
    4323        params = self.expressions(
    4324            expression,
    4325            key="params",
    4326            sep=sep,
    4327            new_line=True,
    4328            skip_last=True,
    4329            skip_first=True,
    4330            indent=self.COPY_PARAMS_ARE_WRAPPED,
    4331        )
    4332
    4333        if params:
    4334            if self.COPY_PARAMS_ARE_WRAPPED:
    4335                params = f" WITH ({params})"
    4336            elif not self.pretty:
    4337                params = f" {params}"
    4338
    4339        return f"COPY{this}{kind} {files}{credentials}{params}"

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

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

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

    4344    def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str:
    4345        on_sql = "ON" if expression.args.get("on") else "OFF"
    4346        filter_col: t.Optional[str] = self.sql(expression, "filter_column")
    4347        filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None
    4348        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    4349        retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None
    4350
    4351        if filter_col or retention_period:
    4352            on_sql = self.func("ON", filter_col, retention_period)
    4353
    4354        return f"DATA_DELETION={on_sql}"

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

    4356    def maskingpolicycolumnconstraint_sql(
    4357        self, expression: exp.MaskingPolicyColumnConstraint
    4358    ) -> str:
    4359        this = self.sql(expression, "this")
    4360        expressions = self.expressions(expression, flat=True)
    4361        expressions = f" USING ({expressions})" if expressions else ""
    4362        return f"MASKING POLICY {this}{expressions}"

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

    4364    def gapfill_sql(self, expression: exp.GapFill) -> str:
    4365        this = self.sql(expression, "this")
    4366        this = f"TABLE {this}"
    4367        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

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

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

    4372    def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str:
    4373        this = self.sql(expression, "this")
    4374        expr = expression.expression
    4375
    4376        if isinstance(expr, exp.Func):
    4377            # T-SQL's CLR functions are case sensitive
    4378            expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})"
    4379        else:
    4380            expr = self.sql(expression, "expression")
    4381
    4382        return self.scope_resolution(expr, this)

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

    4384    def parsejson_sql(self, expression: exp.ParseJSON) -> str:
    4385        if self.PARSE_JSON_NAME is None:
    4386            return self.sql(expression.this)
    4387
    4388        return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression)

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

    4390    def rand_sql(self, expression: exp.Rand) -> str:
    4391        lower = self.sql(expression, "lower")
    4392        upper = self.sql(expression, "upper")
    4393
    4394        if lower and upper:
    4395            return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}"
    4396        return self.func("RAND", expression.this)

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

    4398    def changes_sql(self, expression: exp.Changes) -> str:
    4399        information = self.sql(expression, "information")
    4400        information = f"INFORMATION => {information}"
    4401        at_before = self.sql(expression, "at_before")
    4402        at_before = f"{self.seg('')}{at_before}" if at_before else ""
    4403        end = self.sql(expression, "end")
    4404        end = f"{self.seg('')}{end}" if end else ""
    4405
    4406        return f"CHANGES ({information}){at_before}{end}"

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

    4408    def pad_sql(self, expression: exp.Pad) -> str:
    4409        prefix = "L" if expression.args.get("is_left") else "R"
    4410
    4411        fill_pattern = self.sql(expression, "fill_pattern") or None
    4412        if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED:
    4413            fill_pattern = "' '"
    4414
    4415        return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)

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

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

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

    4421    def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str:
    4422        generate_series = exp.GenerateSeries(**expression.args)
    4423
    4424        parent = expression.parent
    4425        if isinstance(parent, (exp.Alias, exp.TableAlias)):
    4426            parent = parent.parent
    4427
    4428        if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)):
    4429            return self.sql(exp.Unnest(expressions=[generate_series]))
    4430
    4431        if isinstance(parent, exp.Select):
    4432            self.unsupported("GenerateSeries projection unnesting is not supported.")
    4433
    4434        return self.sql(generate_series)

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

    4436    def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str:
    4437        exprs = expression.expressions
    4438        if not self.ARRAY_CONCAT_IS_VAR_LEN:
    4439            rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs)
    4440        else:
    4441            rhs = self.expressions(expression)
    4442
    4443        return self.func(name, expression.this, rhs or None)

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

    4445    def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str:
    4446        if self.SUPPORTS_CONVERT_TIMEZONE:
    4447            return self.function_fallback_sql(expression)
    4448
    4449        source_tz = expression.args.get("source_tz")
    4450        target_tz = expression.args.get("target_tz")
    4451        timestamp = expression.args.get("timestamp")
    4452
    4453        if source_tz and timestamp:
    4454            timestamp = exp.AtTimeZone(
    4455                this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz
    4456            )
    4457
    4458        expr = exp.AtTimeZone(this=timestamp, zone=target_tz)
    4459
    4460        return self.sql(expr)

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

    4462    def json_sql(self, expression: exp.JSON) -> str:
    4463        this = self.sql(expression, "this")
    4464        this = f" {this}" if this else ""
    4465
    4466        _with = expression.args.get("with")
    4467
    4468        if _with is None:
    4469            with_sql = ""
    4470        elif not _with:
    4471            with_sql = " WITHOUT"
    4472        else:
    4473            with_sql = " WITH"
    4474
    4475        unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else ""
    4476
    4477        return f"JSON{this}{with_sql}{unique_sql}"

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

    4479    def jsonvalue_sql(self, expression: exp.JSONValue) -> str:
    4480        def _generate_on_options(arg: t.Any) -> str:
    4481            return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}"
    4482
    4483        path = self.sql(expression, "path")
    4484        returning = self.sql(expression, "returning")
    4485        returning = f" RETURNING {returning}" if returning else ""
    4486
    4487        on_condition = self.sql(expression, "on_condition")
    4488        on_condition = f" {on_condition}" if on_condition else ""
    4489
    4490        return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}")

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

    4492    def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str:
    4493        else_ = "ELSE " if expression.args.get("else_") else ""
    4494        condition = self.sql(expression, "expression")
    4495        condition = f"WHEN {condition} THEN " if condition else else_
    4496        insert = self.sql(expression, "this")[len("INSERT") :].strip()
    4497        return f"{condition}{insert}"

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

    4499    def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str:
    4500        kind = self.sql(expression, "kind")
    4501        expressions = self.seg(self.expressions(expression, sep=" "))
    4502        res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}"
    4503        return res

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

    4505    def oncondition_sql(self, expression: exp.OnCondition) -> str:
    4506        # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR"
    4507        empty = expression.args.get("empty")
    4508        empty = (
    4509            f"DEFAULT {empty} ON EMPTY"
    4510            if isinstance(empty, exp.Expression)
    4511            else self.sql(expression, "empty")
    4512        )
    4513
    4514        error = expression.args.get("error")
    4515        error = (
    4516            f"DEFAULT {error} ON ERROR"
    4517            if isinstance(error, exp.Expression)
    4518            else self.sql(expression, "error")
    4519        )
    4520
    4521        if error and empty:
    4522            error = (
    4523                f"{empty} {error}"
    4524                if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR
    4525                else f"{error} {empty}"
    4526            )
    4527            empty = ""
    4528
    4529        null = self.sql(expression, "null")
    4530
    4531        return f"{empty}{error}{null}"

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

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

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

    4537    def jsonexists_sql(self, expression: exp.JSONExists) -> str:
    4538        this = self.sql(expression, "this")
    4539        path = self.sql(expression, "path")
    4540
    4541        passing = self.expressions(expression, "passing")
    4542        passing = f" PASSING {passing}" if passing else ""
    4543
    4544        on_condition = self.sql(expression, "on_condition")
    4545        on_condition = f" {on_condition}" if on_condition else ""
    4546
    4547        path = f"{path}{passing}{on_condition}"
    4548
    4549        return self.func("JSON_EXISTS", this, path)

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

    4551    def arrayagg_sql(self, expression: exp.ArrayAgg) -> str:
    4552        array_agg = self.function_fallback_sql(expression)
    4553
    4554        # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls
    4555        # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB)
    4556        if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"):
    4557            parent = expression.parent
    4558            if isinstance(parent, exp.Filter):
    4559                parent_cond = parent.expression.this
    4560                parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_()))
    4561            else:
    4562                this = expression.this
    4563                # Do not add the filter if the input is not a column (e.g. literal, struct etc)
    4564                if this.find(exp.Column):
    4565                    # DISTINCT is already present in the agg function, do not propagate it to FILTER as well
    4566                    this_sql = (
    4567                        self.expressions(this)
    4568                        if isinstance(this, exp.Distinct)
    4569                        else self.sql(expression, "this")
    4570                    )
    4571
    4572                    array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)"
    4573
    4574        return array_agg

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

    4576    def apply_sql(self, expression: exp.Apply) -> str:
    4577        this = self.sql(expression, "this")
    4578        expr = self.sql(expression, "expression")
    4579
    4580        return f"{this} APPLY({expr})"

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

    4582    def grant_sql(self, expression: exp.Grant) -> str:
    4583        privileges_sql = self.expressions(expression, key="privileges", flat=True)
    4584
    4585        kind = self.sql(expression, "kind")
    4586        kind = f" {kind}" if kind else ""
    4587
    4588        securable = self.sql(expression, "securable")
    4589        securable = f" {securable}" if securable else ""
    4590
    4591        principals = self.expressions(expression, key="principals", flat=True)
    4592
    4593        grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else ""
    4594
    4595        return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}"

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

    4597    def grantprivilege_sql(self, expression: exp.GrantPrivilege):
    4598        this = self.sql(expression, "this")
    4599        columns = self.expressions(expression, flat=True)
    4600        columns = f"({columns})" if columns else ""
    4601
    4602        return f"{this}{columns}"

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

    4604    def grantprincipal_sql(self, expression: exp.GrantPrincipal):
    4605        this = self.sql(expression, "this")
    4606
    4607        kind = self.sql(expression, "kind")
    4608        kind = f"{kind} " if kind else ""
    4609
    4610        return f"{kind}{this}"

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

    4612    def columns_sql(self, expression: exp.Columns):
    4613        func = self.function_fallback_sql(expression)
    4614        if expression.args.get("unpack"):
    4615            func = f"*{func}"
    4616
    4617        return func

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

    4619    def overlay_sql(self, expression: exp.Overlay):
    4620        this = self.sql(expression, "this")
    4621        expr = self.sql(expression, "expression")
    4622        from_sql = self.sql(expression, "from")
    4623        for_sql = self.sql(expression, "for")
    4624        for_sql = f" FOR {for_sql}" if for_sql else ""
    4625
    4626        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

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

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

    4632    def string_sql(self, expression: exp.String) -> str:
    4633        this = expression.this
    4634        zone = expression.args.get("zone")
    4635
    4636        if zone:
    4637            # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>)
    4638            # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC
    4639            # set for source_tz to transpile the time conversion before the STRING cast
    4640            this = exp.ConvertTimezone(
    4641                source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this
    4642            )
    4643
    4644        return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR))

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

    4646    def median_sql(self, expression: exp.Median):
    4647        if not self.SUPPORTS_MEDIAN:
    4648            return self.sql(
    4649                exp.PercentileCont(this=expression.this, expression=exp.Literal.number(0.5))
    4650            )
    4651
    4652        return self.function_fallback_sql(expression)

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

    4654    def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str:
    4655        filler = self.sql(expression, "this")
    4656        filler = f" {filler}" if filler else ""
    4657        with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT"
    4658        return f"TRUNCATE{filler} {with_count}"

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

    4660    def unixseconds_sql(self, expression: exp.UnixSeconds) -> str:
    4661        if self.SUPPORTS_UNIX_SECONDS:
    4662            return self.function_fallback_sql(expression)
    4663
    4664        start_ts = exp.cast(
    4665            exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ
    4666        )
    4667
    4668        return self.sql(
    4669            exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS"))
    4670        )

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

    4672    def arraysize_sql(self, expression: exp.ArraySize) -> str:
    4673        dim = expression.expression
    4674
    4675        # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension)
    4676        if dim and self.ARRAY_SIZE_DIM_REQUIRED is None:
    4677            if not (dim.is_int and dim.name == "1"):
    4678                self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH")
    4679            dim = None
    4680
    4681        # If dimension is required but not specified, default initialize it
    4682        if self.ARRAY_SIZE_DIM_REQUIRED and not dim:
    4683            dim = exp.Literal.number(1)
    4684
    4685        return self.func(self.ARRAY_SIZE_NAME, expression.this, dim)

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

    4687    def attach_sql(self, expression: exp.Attach) -> str:
    4688        this = self.sql(expression, "this")
    4689        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
    4690        expressions = self.expressions(expression)
    4691        expressions = f" ({expressions})" if expressions else ""
    4692
    4693        return f"ATTACH{exists_sql} {this}{expressions}"

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

    4695    def detach_sql(self, expression: exp.Detach) -> str:
    4696        this = self.sql(expression, "this")
    4697        exists_sql = " IF EXISTS" if expression.args.get("exists") else ""
    4698
    4699        return f"DETACH{exists_sql} {this}"

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

    4701    def attachoption_sql(self, expression: exp.AttachOption) -> str:
    4702        this = self.sql(expression, "this")
    4703        value = self.sql(expression, "expression")
    4704        value = f" {value}" if value else ""
    4705        return f"{this}{value}"

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

    4707    def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str:
    4708        this_sql = self.sql(expression, "this")
    4709        if isinstance(expression.this, exp.Table):
    4710            this_sql = f"TABLE {this_sql}"
    4711
    4712        return self.func(
    4713            "FEATURES_AT_TIME",
    4714            this_sql,
    4715            expression.args.get("time"),
    4716            expression.args.get("num_rows"),
    4717            expression.args.get("ignore_feature_nulls"),
    4718        )

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

    4720    def watermarkcolumnconstraint_sql(self, expression: exp.WatermarkColumnConstraint) -> str:
    4721        return (
    4722            f"WATERMARK FOR {self.sql(expression, 'this')} AS {self.sql(expression, 'expression')}"
    4723        )

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

    4725    def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str:
    4726        encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE"
    4727        encode = f"{encode} {self.sql(expression, 'this')}"
    4728
    4729        properties = expression.args.get("properties")
    4730        if properties:
    4731            encode = f"{encode} {self.properties(properties)}"
    4732
    4733        return encode

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

    4735    def includeproperty_sql(self, expression: exp.IncludeProperty) -> str:
    4736        this = self.sql(expression, "this")
    4737        include = f"INCLUDE {this}"
    4738
    4739        column_def = self.sql(expression, "column_def")
    4740        if column_def:
    4741            include = f"{include} {column_def}"
    4742
    4743        alias = self.sql(expression, "alias")
    4744        if alias:
    4745            include = f"{include} AS {alias}"
    4746
    4747        return include

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

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

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

    4753    def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str:
    4754        partitions = self.expressions(expression, "partition_expressions")
    4755        create = self.expressions(expression, "create_expressions")
    4756        return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}"

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

    4758    def partitionbyrangepropertydynamic_sql(
    4759        self, expression: exp.PartitionByRangePropertyDynamic
    4760    ) -> str:
    4761        start = self.sql(expression, "start")
    4762        end = self.sql(expression, "end")
    4763
    4764        every = expression.args["every"]
    4765        if isinstance(every, exp.Interval) and every.this.is_string:
    4766            every.this.replace(exp.Literal.number(every.name))
    4767
    4768        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

    4770    def unpivotcolumns_sql(self, expression: exp.UnpivotColumns) -> str:
    4771        name = self.sql(expression, "this")
    4772        values = self.expressions(expression, flat=True)
    4773
    4774        return f"NAME {name} VALUE {values}"

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

    4776    def analyzesample_sql(self, expression: exp.AnalyzeSample) -> str:
    4777        kind = self.sql(expression, "kind")
    4778        sample = self.sql(expression, "sample")
    4779        return f"SAMPLE {sample} {kind}"

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

    4781    def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str:
    4782        kind = self.sql(expression, "kind")
    4783        option = self.sql(expression, "option")
    4784        option = f" {option}" if option else ""
    4785        this = self.sql(expression, "this")
    4786        this = f" {this}" if this else ""
    4787        columns = self.expressions(expression)
    4788        columns = f" {columns}" if columns else ""
    4789        return f"{kind}{option} STATISTICS{this}{columns}"

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

    4791    def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str:
    4792        this = self.sql(expression, "this")
    4793        columns = self.expressions(expression)
    4794        inner_expression = self.sql(expression, "expression")
    4795        inner_expression = f" {inner_expression}" if inner_expression else ""
    4796        update_options = self.sql(expression, "update_options")
    4797        update_options = f" {update_options} UPDATE" if update_options else ""
    4798        return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}"

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

    4800    def analyzedelete_sql(self, expression: exp.AnalyzeDelete) -> str:
    4801        kind = self.sql(expression, "kind")
    4802        kind = f" {kind}" if kind else ""
    4803        return f"DELETE{kind} STATISTICS"

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

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

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

    4809    def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str:
    4810        kind = self.sql(expression, "kind")
    4811        this = self.sql(expression, "this")
    4812        this = f" {this}" if this else ""
    4813        inner_expression = self.sql(expression, "expression")
    4814        return f"VALIDATE {kind}{this}{inner_expression}"

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

    4816    def analyze_sql(self, expression: exp.Analyze) -> str:
    4817        options = self.expressions(expression, key="options", sep=" ")
    4818        options = f" {options}" if options else ""
    4819        kind = self.sql(expression, "kind")
    4820        kind = f" {kind}" if kind else ""
    4821        this = self.sql(expression, "this")
    4822        this = f" {this}" if this else ""
    4823        mode = self.sql(expression, "mode")
    4824        mode = f" {mode}" if mode else ""
    4825        properties = self.sql(expression, "properties")
    4826        properties = f" {properties}" if properties else ""
    4827        partition = self.sql(expression, "partition")
    4828        partition = f" {partition}" if partition else ""
    4829        inner_expression = self.sql(expression, "expression")
    4830        inner_expression = f" {inner_expression}" if inner_expression else ""
    4831        return f"ANALYZE{options}{kind}{this}{partition}{mode}{inner_expression}{properties}"

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

    4833    def xmltable_sql(self, expression: exp.XMLTable) -> str:
    4834        this = self.sql(expression, "this")
    4835        namespaces = self.expressions(expression, key="namespaces")
    4836        namespaces = f"XMLNAMESPACES({namespaces}), " if namespaces else ""
    4837        passing = self.expressions(expression, key="passing")
    4838        passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else ""
    4839        columns = self.expressions(expression, key="columns")
    4840        columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else ""
    4841        by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else ""
    4842        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

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

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

    4848    def export_sql(self, expression: exp.Export) -> str:
    4849        this = self.sql(expression, "this")
    4850        connection = self.sql(expression, "connection")
    4851        connection = f"WITH CONNECTION {connection} " if connection else ""
    4852        options = self.sql(expression, "options")
    4853        return f"EXPORT DATA {connection}{options} AS {this}"

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

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

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

    4858    def declareitem_sql(self, expression: exp.DeclareItem) -> str:
    4859        variable = self.sql(expression, "this")
    4860        default = self.sql(expression, "default")
    4861        default = f" = {default}" if default else ""
    4862
    4863        kind = self.sql(expression, "kind")
    4864        if isinstance(expression.args.get("kind"), exp.Schema):
    4865            kind = f"TABLE {kind}"
    4866
    4867        return f"{variable} AS {kind}{default}"

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

    4869    def recursivewithsearch_sql(self, expression: exp.RecursiveWithSearch) -> str:
    4870        kind = self.sql(expression, "kind")
    4871        this = self.sql(expression, "this")
    4872        set = self.sql(expression, "expression")
    4873        using = self.sql(expression, "using")
    4874        using = f" USING {using}" if using else ""
    4875
    4876        kind_sql = kind if kind == "CYCLE" else f"SEARCH {kind} FIRST BY"
    4877
    4878        return f"{kind_sql} {this} SET {set}{using}"

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

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

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

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

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

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

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

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

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

    4893    def show_sql(self, expression: exp.Show) -> str:
    4894        self.unsupported("Unsupported SHOW statement")
    4895        return ""

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

    4897    def put_sql(self, expression: exp.Put) -> str:
    4898        props = expression.args.get("properties")
    4899        props_sql = self.properties(props, prefix=" ", sep=" ", wrapped=False) if props else ""
    4900        this = self.sql(expression, "this")
    4901        target = self.sql(expression, "target")
    4902        return f"PUT {this} {target}{props_sql}"