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

    685    def __init__(
    686        self,
    687        pretty: t.Optional[bool] = None,
    688        identify: str | bool = False,
    689        normalize: bool = False,
    690        pad: int = 2,
    691        indent: int = 2,
    692        normalize_functions: t.Optional[str | bool] = None,
    693        unsupported_level: ErrorLevel = ErrorLevel.WARN,
    694        max_unsupported: int = 3,
    695        leading_comma: bool = False,
    696        max_text_width: int = 80,
    697        comments: bool = True,
    698        dialect: DialectType = None,
    699    ):
    700        import sqlglot
    701        from sqlglot.dialects import Dialect
    702
    703        self.pretty = pretty if pretty is not None else sqlglot.pretty
    704        self.identify = identify
    705        self.normalize = normalize
    706        self.pad = pad
    707        self._indent = indent
    708        self.unsupported_level = unsupported_level
    709        self.max_unsupported = max_unsupported
    710        self.leading_comma = leading_comma
    711        self.max_text_width = max_text_width
    712        self.comments = comments
    713        self.dialect = Dialect.get_or_raise(dialect)
    714
    715        # This is both a Dialect property and a Generator argument, so we prioritize the latter
    716        self.normalize_functions = (
    717            self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions
    718        )
    719
    720        self.unsupported_messages: t.List[str] = []
    721        self._escaped_quote_end: str = (
    722            self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END
    723        )
    724        self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2
    725
    726        self._next_name = name_sequence("_t")
    727
    728        self._identifier_start = self.dialect.IDENTIFIER_START
    729        self._identifier_end = self.dialect.IDENTIFIER_END
    730
    731        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.PartitionedByBucket'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PartitionByTruncate'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PivotAny'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ProjectionPolicyColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ReturnsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SampleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SecureProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetConfigProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SharingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlReadWriteProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StabilityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Stream'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StreamingTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StrictProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SwapTable'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Tags'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TemporaryProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Union'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UnloggedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UsingTemplateProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UsingData'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Uuid'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VarMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ViewAttributeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithProcedureOptions'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithSchemaBindingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithOperator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ForceProperty'>: <function Generator.<lambda>>}
NULL_ORDERING_SUPPORTED: Optional[bool] = True
IGNORE_NULLS_IN_FUNC = False
LOCKING_READS_SUPPORTED = False
EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = True
WRAP_DERIVED_VALUES = True
CREATE_FUNCTION_RETURN_AS = True
MATCHED_BY_SOURCE = True
SINGLE_STRING_INTERVAL = False
INTERVAL_ALLOWS_PLURAL_FORM = True
LIMIT_FETCH = 'ALL'
LIMIT_ONLY_LITERALS = False
RENAME_TABLE_WITH_DB = True
GROUPINGS_SEP = ','
INDEX_ON = 'ON'
JOIN_HINTS = True
TABLE_HINTS = True
QUERY_HINTS = True
QUERY_HINT_SEP = ', '
IS_BOOL_ALLOWED = True
DUPLICATE_KEY_UPDATE_WITH_SET = True
LIMIT_IS_TOP = False
RETURNING_END = True
EXTRACT_ALLOWS_QUOTES = True
TZ_TO_WITH_TIME_ZONE = False
NVL2_SUPPORTED = True
SELECT_KINDS: Tuple[str, ...] = ('STRUCT', 'VALUE')
VALUES_AS_TABLE = True
ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = True
UNNEST_WITH_ORDINALITY = True
AGGREGATE_FILTER_SUPPORTED = True
SEMI_ANTI_JOIN_WITH_SIDE = True
COMPUTED_COLUMN_WITH_TYPE = True
SUPPORTS_TABLE_COPY = True
TABLESAMPLE_REQUIRES_PARENS = True
TABLESAMPLE_SIZE_IS_ROWS = True
TABLESAMPLE_KEYWORDS = 'TABLESAMPLE'
TABLESAMPLE_WITH_METHOD = True
TABLESAMPLE_SEED_KEYWORD = 'SEED'
COLLATE_IS_FUNC = False
DATA_TYPE_SPECIFIERS_ALLOWED = False
ENSURE_BOOLS = False
CTE_RECURSIVE_KEYWORD_REQUIRED = True
SUPPORTS_SINGLE_ARG_CONCAT = True
LAST_DAY_SUPPORTS_DATE_PART = True
SUPPORTS_TABLE_ALIAS_COLUMNS = True
UNPIVOT_ALIASES_ARE_IDENTIFIERS = True
JSON_KEY_VALUE_PAIR_SEP = ':'
INSERT_OVERWRITE = ' OVERWRITE TABLE'
SUPPORTS_SELECT_INTO = False
SUPPORTS_UNLOGGED_TABLES = False
SUPPORTS_CREATE_TABLE_LIKE = True
LIKE_PROPERTY_INSIDE_SCHEMA = False
MULTI_ARG_DISTINCT = True
JSON_TYPE_REQUIRED_FOR_EXTRACTION = False
JSON_PATH_BRACKETED_KEY_SUPPORTED = True
JSON_PATH_SINGLE_QUOTE_ESCAPE = False
SUPPORTED_JSON_PATH_PARTS = {<class 'sqlglot.expressions.JSONPathFilter'>, <class 'sqlglot.expressions.JSONPathUnion'>, <class 'sqlglot.expressions.JSONPathSubscript'>, <class 'sqlglot.expressions.JSONPathSelector'>, <class 'sqlglot.expressions.JSONPathSlice'>, <class 'sqlglot.expressions.JSONPathScript'>, <class 'sqlglot.expressions.JSONPathRoot'>, <class 'sqlglot.expressions.JSONPathWildcard'>, <class 'sqlglot.expressions.JSONPathRecursive'>, <class 'sqlglot.expressions.JSONPathKey'>}
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.NCHAR: 'NCHAR'>, <Type.NVARCHAR: 'NVARCHAR'>, <Type.CHAR: 'CHAR'>, <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

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

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

Apply generic preprocessing transformations to a given expression.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    1066    def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str:
    1067        desc = expression.args.get("desc")
    1068        if desc is not None:
    1069            return f"PRIMARY KEY{' DESC' if desc else ' ASC'}"
    1070        options = self.expressions(expression, key="options", flat=True, sep=" ")
    1071        options = f" {options}" if options else ""
    1072        return f"PRIMARY KEY{options}"

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

    1074    def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str:
    1075        this = self.sql(expression, "this")
    1076        this = f" {this}" if this else ""
    1077        index_type = expression.args.get("index_type")
    1078        index_type = f" USING {index_type}" if index_type else ""
    1079        on_conflict = self.sql(expression, "on_conflict")
    1080        on_conflict = f" {on_conflict}" if on_conflict else ""
    1081        nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else ""
    1082        options = self.expressions(expression, key="options", flat=True, sep=" ")
    1083        options = f" {options}" if options else ""
    1084        return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}{options}"

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

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

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

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

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

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

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

    1223    def clone_sql(self, expression: exp.Clone) -> str:
    1224        this = self.sql(expression, "this")
    1225        shallow = "SHALLOW " if expression.args.get("shallow") else ""
    1226        keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE"
    1227        return f"{shallow}{keyword} {this}"

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

    1229    def describe_sql(self, expression: exp.Describe) -> str:
    1230        style = expression.args.get("style")
    1231        style = f" {style}" if style else ""
    1232        partition = self.sql(expression, "partition")
    1233        partition = f" {partition}" if partition else ""
    1234        format = self.sql(expression, "format")
    1235        format = f" {format}" if format else ""
    1236
    1237        return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}"

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

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

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

    1243    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
    1244        with_ = self.sql(expression, "with")
    1245        if with_:
    1246            sql = f"{with_}{self.sep()}{sql}"
    1247        return sql

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

    1249    def with_sql(self, expression: exp.With) -> str:
    1250        sql = self.expressions(expression, flat=True)
    1251        recursive = (
    1252            "RECURSIVE "
    1253            if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive")
    1254            else ""
    1255        )
    1256        search = self.sql(expression, "search")
    1257        search = f" {search}" if search else ""
    1258
    1259        return f"WITH {recursive}{sql}{search}"

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

    1261    def cte_sql(self, expression: exp.CTE) -> str:
    1262        alias = expression.args.get("alias")
    1263        if alias:
    1264            alias.add_comments(expression.pop_comments())
    1265
    1266        alias_sql = self.sql(expression, "alias")
    1267
    1268        materialized = expression.args.get("materialized")
    1269        if materialized is False:
    1270            materialized = "NOT MATERIALIZED "
    1271        elif materialized:
    1272            materialized = "MATERIALIZED "
    1273
    1274        return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}"

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

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

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

    1290    def bitstring_sql(self, expression: exp.BitString) -> str:
    1291        this = self.sql(expression, "this")
    1292        if self.dialect.BIT_START:
    1293            return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}"
    1294        return f"{int(this, 2)}"

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

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

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

    1321    def bytestring_sql(self, expression: exp.ByteString) -> str:
    1322        this = self.sql(expression, "this")
    1323        if self.dialect.BYTE_START:
    1324            return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}"
    1325        return this

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

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

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

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

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

    1354    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
    1355        this = self.sql(expression, "this")
    1356        specifier = self.sql(expression, "expression")
    1357        specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else ""
    1358        return f"{this}{specifier}"

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

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

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

    1396    def directory_sql(self, expression: exp.Directory) -> str:
    1397        local = "LOCAL " if expression.args.get("local") else ""
    1398        row_format = self.sql(expression, "row_format")
    1399        row_format = f" {row_format}" if row_format else ""
    1400        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"

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

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

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

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

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

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

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

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

    1507    def fetch_sql(self, expression: exp.Fetch) -> str:
    1508        direction = expression.args.get("direction")
    1509        direction = f" {direction}" if direction else ""
    1510        count = self.sql(expression, "count")
    1511        count = f" {count}" if count else ""
    1512        limit_options = self.sql(expression, "limit_options")
    1513        limit_options = f"{limit_options}" if limit_options else " ROWS ONLY"
    1514        return f"{self.seg('FETCH')}{direction}{count}{limit_options}"

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

    1516    def limitoptions_sql(self, expression: exp.LimitOptions) -> str:
    1517        percent = " PERCENT" if expression.args.get("percent") else ""
    1518        rows = " ROWS" if expression.args.get("rows") else ""
    1519        with_ties = " WITH TIES" if expression.args.get("with_ties") else ""
    1520        if not with_ties and rows:
    1521            with_ties = " ONLY"
    1522        return f"{percent}{rows}{with_ties}"

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

    1524    def filter_sql(self, expression: exp.Filter) -> str:
    1525        if self.AGGREGATE_FILTER_SUPPORTED:
    1526            this = self.sql(expression, "this")
    1527            where = self.sql(expression, "expression").strip()
    1528            return f"{this} FILTER({where})"
    1529
    1530        agg = expression.this
    1531        agg_arg = agg.this
    1532        cond = expression.expression.this
    1533        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
    1534        return self.sql(agg)

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

    1536    def hint_sql(self, expression: exp.Hint) -> str:
    1537        if not self.QUERY_HINTS:
    1538            self.unsupported("Hints are not supported")
    1539            return ""
    1540
    1541        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"

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

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

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

    1563    def index_sql(self, expression: exp.Index) -> str:
    1564        unique = "UNIQUE " if expression.args.get("unique") else ""
    1565        primary = "PRIMARY " if expression.args.get("primary") else ""
    1566        amp = "AMP " if expression.args.get("amp") else ""
    1567        name = self.sql(expression, "this")
    1568        name = f"{name} " if name else ""
    1569        table = self.sql(expression, "table")
    1570        table = f"{self.INDEX_ON} {table}" if table else ""
    1571
    1572        index = "INDEX " if not table else ""
    1573
    1574        params = self.sql(expression, "params")
    1575        return f"{unique}{primary}{amp}{index}{name}{table}{params}"

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

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

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

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

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

    1598    def lowerhex_sql(self, expression: exp.LowerHex) -> str:
    1599        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1600        if not self.dialect.HEX_LOWERCASE:
    1601            text = self.func("LOWER", text)
    1602        return text

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

    1604    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    1605        input_format = self.sql(expression, "input_format")
    1606        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    1607        output_format = self.sql(expression, "output_format")
    1608        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    1609        return self.sep().join((input_format, output_format))

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

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

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

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

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

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

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

    1638    def root_properties(self, properties: exp.Properties) -> str:
    1639        if properties.expressions:
    1640            return self.expressions(properties, indent=False, sep=" ")
    1641        return ""

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

    1643    def properties(
    1644        self,
    1645        properties: exp.Properties,
    1646        prefix: str = "",
    1647        sep: str = ", ",
    1648        suffix: str = "",
    1649        wrapped: bool = True,
    1650    ) -> str:
    1651        if properties.expressions:
    1652            expressions = self.expressions(properties, sep=sep, indent=False)
    1653            if expressions:
    1654                expressions = self.wrap(expressions) if wrapped else expressions
    1655                return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}"
    1656        return ""

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

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

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

    1661    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
    1662        properties_locs = defaultdict(list)
    1663        for p in properties.expressions:
    1664            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1665            if p_loc != exp.Properties.Location.UNSUPPORTED:
    1666                properties_locs[p_loc].append(p)
    1667            else:
    1668                self.unsupported(f"Unsupported property {p.key}")
    1669
    1670        return properties_locs

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

    1672    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
    1673        if isinstance(expression.this, exp.Dot):
    1674            return self.sql(expression, "this")
    1675        return f"'{expression.name}'" if string_key else expression.name

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

    1677    def property_sql(self, expression: exp.Property) -> str:
    1678        property_cls = expression.__class__
    1679        if property_cls == exp.Property:
    1680            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
    1681
    1682        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    1683        if not property_name:
    1684            self.unsupported(f"Unsupported property {expression.key}")
    1685
    1686        return f"{property_name}={self.sql(expression, 'this')}"

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

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

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

    1705    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1706        no = "NO " if expression.args.get("no") else ""
    1707        protection = " PROTECTION" if expression.args.get("protection") else ""
    1708        return f"{no}FALLBACK{protection}"

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

    1710    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1711        no = "NO " if expression.args.get("no") else ""
    1712        local = expression.args.get("local")
    1713        local = f"{local} " if local else ""
    1714        dual = "DUAL " if expression.args.get("dual") else ""
    1715        before = "BEFORE " if expression.args.get("before") else ""
    1716        after = "AFTER " if expression.args.get("after") else ""
    1717        return f"{no}{local}{dual}{before}{after}JOURNAL"

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

    1719    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1720        freespace = self.sql(expression, "this")
    1721        percent = " PERCENT" if expression.args.get("percent") else ""
    1722        return f"FREESPACE={freespace}{percent}"

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

    1724    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1725        if expression.args.get("default"):
    1726            property = "DEFAULT"
    1727        elif expression.args.get("on"):
    1728            property = "ON"
    1729        else:
    1730            property = "OFF"
    1731        return f"CHECKSUM={property}"

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

    1733    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1734        if expression.args.get("no"):
    1735            return "NO MERGEBLOCKRATIO"
    1736        if expression.args.get("default"):
    1737            return "DEFAULT MERGEBLOCKRATIO"
    1738
    1739        percent = " PERCENT" if expression.args.get("percent") else ""
    1740        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"

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

    1742    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1743        default = expression.args.get("default")
    1744        minimum = expression.args.get("minimum")
    1745        maximum = expression.args.get("maximum")
    1746        if default or minimum or maximum:
    1747            if default:
    1748                prop = "DEFAULT"
    1749            elif minimum:
    1750                prop = "MINIMUM"
    1751            else:
    1752                prop = "MAXIMUM"
    1753            return f"{prop} DATABLOCKSIZE"
    1754        units = expression.args.get("units")
    1755        units = f" {units}" if units else ""
    1756        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"

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

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

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

    1777    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1778        no = expression.args.get("no")
    1779        no = " NO" if no else ""
    1780        concurrent = expression.args.get("concurrent")
    1781        concurrent = " CONCURRENT" if concurrent else ""
    1782        target = self.sql(expression, "target")
    1783        target = f" {target}" if target else ""
    1784        return f"WITH{no}{concurrent} ISOLATED LOADING{target}"

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

    1786    def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str:
    1787        if isinstance(expression.this, list):
    1788            return f"IN ({self.expressions(expression, key='this', flat=True)})"
    1789        if expression.this:
    1790            modulus = self.sql(expression, "this")
    1791            remainder = self.sql(expression, "expression")
    1792            return f"WITH (MODULUS {modulus}, REMAINDER {remainder})"
    1793
    1794        from_expressions = self.expressions(expression, key="from_expressions", flat=True)
    1795        to_expressions = self.expressions(expression, key="to_expressions", flat=True)
    1796        return f"FROM ({from_expressions}) TO ({to_expressions})"

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

    1798    def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str:
    1799        this = self.sql(expression, "this")
    1800
    1801        for_values_or_default = expression.expression
    1802        if isinstance(for_values_or_default, exp.PartitionBoundSpec):
    1803            for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}"
    1804        else:
    1805            for_values_or_default = " DEFAULT"
    1806
    1807        return f"PARTITION OF {this}{for_values_or_default}"

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

    1809    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1810        kind = expression.args.get("kind")
    1811        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1812        for_or_in = expression.args.get("for_or_in")
    1813        for_or_in = f" {for_or_in}" if for_or_in else ""
    1814        lock_type = expression.args.get("lock_type")
    1815        override = " OVERRIDE" if expression.args.get("override") else ""
    1816        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"

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

    1818    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1819        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1820        statistics = expression.args.get("statistics")
    1821        statistics_sql = ""
    1822        if statistics is not None:
    1823            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1824        return f"{data_sql}{statistics_sql}"

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

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

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

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

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

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

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

    1894    def kill_sql(self, expression: exp.Kill) -> str:
    1895        kind = self.sql(expression, "kind")
    1896        kind = f" {kind}" if kind else ""
    1897        this = self.sql(expression, "this")
    1898        this = f" {this}" if this else ""
    1899        return f"KILL{kind}{this}"

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

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

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

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

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

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

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

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

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

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

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

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

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

    1946    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1947        this = f"{self.sql(expression, 'this')} INDEX"
    1948        target = self.sql(expression, "target")
    1949        target = f" FOR {target}" if target else ""
    1950        return f"{this}{target} ({self.expressions(expression, flat=True)})"

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

    1952    def historicaldata_sql(self, expression: exp.HistoricalData) -> str:
    1953        this = self.sql(expression, "this")
    1954        kind = self.sql(expression, "kind")
    1955        expr = self.sql(expression, "expression")
    1956        return f"{this} ({kind} => {expr})"

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

    1958    def table_parts(self, expression: exp.Table) -> str:
    1959        return ".".join(
    1960            self.sql(part)
    1961            for part in (
    1962                expression.args.get("catalog"),
    1963                expression.args.get("db"),
    1964                expression.args.get("this"),
    1965            )
    1966            if part is not None
    1967        )

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

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

    2019    def tablefromrows_sql(self, expression: exp.TableFromRows) -> str:
    2020        table = self.func("TABLE", expression.this)
    2021        alias = self.sql(expression, "alias")
    2022        alias = f" AS {alias}" if alias else ""
    2023        sample = self.sql(expression, "sample")
    2024        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    2025        joins = self.indent(
    2026            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
    2027        )
    2028        return f"{table}{alias}{pivots}{sample}{joins}"

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

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

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

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

    2100    def version_sql(self, expression: exp.Version) -> str:
    2101        this = f"FOR {expression.name}"
    2102        kind = expression.text("kind")
    2103        expr = self.sql(expression, "expression")
    2104        return f"{this} {kind} {expr}"

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

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

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

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

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

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

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

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

    2170    @unsupported_args("expressions")
    2171    def into_sql(self, expression: exp.Into) -> str:
    2172        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    2173        unlogged = " UNLOGGED" if expression.args.get("unlogged") else ""
    2174        return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"

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

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

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

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

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

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

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

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

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

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

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

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

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

    2227    def connect_sql(self, expression: exp.Connect) -> str:
    2228        start = self.sql(expression, "start")
    2229        start = self.seg(f"START WITH {start}") if start else ""
    2230        nocycle = " NOCYCLE" if expression.args.get("nocycle") else ""
    2231        connect = self.sql(expression, "connect")
    2232        connect = self.seg(f"CONNECT BY{nocycle} {connect}")
    2233        return start + connect

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

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

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

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

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

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

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

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

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

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

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

    2344    def offset_sql(self, expression: exp.Offset) -> str:
    2345        this = self.sql(expression, "this")
    2346        value = expression.expression
    2347        value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value
    2348        expressions = self.expressions(expression, flat=True)
    2349        expressions = f" BY {expressions}" if expressions else ""
    2350        return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"

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

    2352    def setitem_sql(self, expression: exp.SetItem) -> str:
    2353        kind = self.sql(expression, "kind")
    2354        kind = f"{kind} " if kind else ""
    2355        this = self.sql(expression, "this")
    2356        expressions = self.expressions(expression)
    2357        collate = self.sql(expression, "collate")
    2358        collate = f" COLLATE {collate}" if collate else ""
    2359        global_ = "GLOBAL " if expression.args.get("global") else ""
    2360        return f"{global_}{kind}{this}{expressions}{collate}"

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

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

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

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

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

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

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

    2388    def literal_sql(self, expression: exp.Literal) -> str:
    2389        text = expression.this or ""
    2390        if expression.is_string:
    2391            text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}"
    2392        return text

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

    2394    def escape_str(self, text: str, escape_backslash: bool = True) -> str:
    2395        if self.dialect.ESCAPED_SEQUENCES:
    2396            to_escaped = self.dialect.ESCAPED_SEQUENCES
    2397            text = "".join(
    2398                to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text
    2399            )
    2400
    2401        return self._replace_line_breaks(text).replace(
    2402            self.dialect.QUOTE_END, self._escaped_quote_end
    2403        )

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

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

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

    2418    def null_sql(self, *_) -> str:
    2419        return "NULL"

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

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

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

    2424    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    2425        this = self.sql(expression, "this")
    2426        this = f"{this} " if this else this
    2427        siblings = "SIBLINGS " if expression.args.get("siblings") else ""
    2428        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

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

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

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

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

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

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

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

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

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

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

    2520    def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str:
    2521        window_frame = self.sql(expression, "window_frame")
    2522        window_frame = f"{window_frame} " if window_frame else ""
    2523
    2524        this = self.sql(expression, "this")
    2525
    2526        return f"{window_frame}{this}"

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

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

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

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

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

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

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

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

    2594    def offset_limit_modifiers(
    2595        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    2596    ) -> t.List[str]:
    2597        return [
    2598            self.sql(expression, "offset") if fetch else self.sql(limit),
    2599            self.sql(limit) if fetch else self.sql(expression, "offset"),
    2600        ]

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

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

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

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

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

    2679    def schema_sql(self, expression: exp.Schema) -> str:
    2680        this = self.sql(expression, "this")
    2681        sql = self.schema_columns_sql(expression)
    2682        return f"{this} {sql}" if this and sql else this or sql

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

    2684    def schema_columns_sql(self, expression: exp.Schema) -> str:
    2685        if expression.expressions:
    2686            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
    2687        return ""

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

    2689    def star_sql(self, expression: exp.Star) -> str:
    2690        except_ = self.expressions(expression, key="except", flat=True)
    2691        except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else ""
    2692        replace = self.expressions(expression, key="replace", flat=True)
    2693        replace = f"{self.seg('REPLACE')} ({replace})" if replace else ""
    2694        rename = self.expressions(expression, key="rename", flat=True)
    2695        rename = f"{self.seg('RENAME')} ({rename})" if rename else ""
    2696        return f"*{except_}{replace}{rename}"

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

    2698    def parameter_sql(self, expression: exp.Parameter) -> str:
    2699        this = self.sql(expression, "this")
    2700        return f"{self.PARAMETER_TOKEN}{this}"

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

    2702    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    2703        this = self.sql(expression, "this")
    2704        kind = expression.text("kind")
    2705        if kind:
    2706            kind = f"{kind}."
    2707        return f"@@{kind}{this}"

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

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

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

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

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

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

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

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

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

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

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

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

    2766    def window_sql(self, expression: exp.Window) -> str:
    2767        this = self.sql(expression, "this")
    2768        partition = self.partition_by_sql(expression)
    2769        order = expression.args.get("order")
    2770        order = self.order_sql(order, flat=True) if order else ""
    2771        spec = self.sql(expression, "spec")
    2772        alias = self.sql(expression, "alias")
    2773        over = self.sql(expression, "over") or "OVER"
    2774
    2775        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    2776
    2777        first = expression.args.get("first")
    2778        if first is None:
    2779            first = ""
    2780        else:
    2781            first = "FIRST" if first else "LAST"
    2782
    2783        if not partition and not order and not spec and alias:
    2784            return f"{this} {alias}"
    2785
    2786        args = self.format_args(
    2787            *[arg for arg in (alias, first, partition, order, spec) if arg], sep=" "
    2788        )
    2789        return f"{this} ({args})"

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

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

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

    2795    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    2796        kind = self.sql(expression, "kind")
    2797        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    2798        end = (
    2799            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    2800            or "CURRENT ROW"
    2801        )
    2802        return f"{kind} BETWEEN {start} AND {end}"

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

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

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

    2809    def between_sql(self, expression: exp.Between) -> str:
    2810        this = self.sql(expression, "this")
    2811        low = self.sql(expression, "low")
    2812        high = self.sql(expression, "high")
    2813        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

    2815    def bracket_offset_expressions(
    2816        self, expression: exp.Bracket, index_offset: t.Optional[int] = None
    2817    ) -> t.List[exp.Expression]:
    2818        return apply_index_offset(
    2819            expression.this,
    2820            expression.expressions,
    2821            (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0),
    2822            dialect=self.dialect,
    2823        )

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

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

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

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

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

    2833    def any_sql(self, expression: exp.Any) -> str:
    2834        this = self.sql(expression, "this")
    2835        if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)):
    2836            if isinstance(expression.this, exp.UNWRAPPED_QUERIES):
    2837                this = self.wrap(this)
    2838            return f"ANY{this}"
    2839        return f"ANY {this}"

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

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

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

    2844    def case_sql(self, expression: exp.Case) -> str:
    2845        this = self.sql(expression, "this")
    2846        statements = [f"CASE {this}" if this else "CASE"]
    2847
    2848        for e in expression.args["ifs"]:
    2849            statements.append(f"WHEN {self.sql(e, 'this')}")
    2850            statements.append(f"THEN {self.sql(e, 'true')}")
    2851
    2852        default = self.sql(expression, "default")
    2853
    2854        if default:
    2855            statements.append(f"ELSE {default}")
    2856
    2857        statements.append("END")
    2858
    2859        if self.pretty and self.too_wide(statements):
    2860            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    2861
    2862        return " ".join(statements)

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

    2864    def constraint_sql(self, expression: exp.Constraint) -> str:
    2865        this = self.sql(expression, "this")
    2866        expressions = self.expressions(expression, flat=True)
    2867        return f"CONSTRAINT {this} {expressions}"

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

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

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

    2874    def extract_sql(self, expression: exp.Extract) -> str:
    2875        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
    2876        expression_sql = self.sql(expression, "expression")
    2877        return f"EXTRACT({this} FROM {expression_sql})"

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

    2879    def trim_sql(self, expression: exp.Trim) -> str:
    2880        trim_type = self.sql(expression, "position")
    2881
    2882        if trim_type == "LEADING":
    2883            func_name = "LTRIM"
    2884        elif trim_type == "TRAILING":
    2885            func_name = "RTRIM"
    2886        else:
    2887            func_name = "TRIM"
    2888
    2889        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

    2891    def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]:
    2892        args = expression.expressions
    2893        if isinstance(expression, exp.ConcatWs):
    2894            args = args[1:]  # Skip the delimiter
    2895
    2896        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    2897            args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args]
    2898
    2899        if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"):
    2900            args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args]
    2901
    2902        return args

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

    2904    def concat_sql(self, expression: exp.Concat) -> str:
    2905        expressions = self.convert_concat_args(expression)
    2906
    2907        # Some dialects don't allow a single-argument CONCAT call
    2908        if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1:
    2909            return self.sql(expressions[0])
    2910
    2911        return self.func("CONCAT", *expressions)

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

    2913    def concatws_sql(self, expression: exp.ConcatWs) -> str:
    2914        return self.func(
    2915            "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression)
    2916        )

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

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

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

    2922    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    2923        expressions = self.expressions(expression, flat=True)
    2924        expressions = f" ({expressions})" if expressions else ""
    2925        reference = self.sql(expression, "reference")
    2926        reference = f" {reference}" if reference else ""
    2927        delete = self.sql(expression, "delete")
    2928        delete = f" ON DELETE {delete}" if delete else ""
    2929        update = self.sql(expression, "update")
    2930        update = f" ON UPDATE {update}" if update else ""
    2931        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2932        options = f" {options}" if options else ""
    2933        return f"FOREIGN KEY{expressions}{reference}{delete}{update}{options}"

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

    2935    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    2936        expressions = self.expressions(expression, flat=True)
    2937        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2938        options = f" {options}" if options else ""
    2939        return f"PRIMARY KEY ({expressions}){options}"

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

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

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

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

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

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

    2952    def jsonpath_sql(self, expression: exp.JSONPath) -> str:
    2953        path = self.expressions(expression, sep="", flat=True).lstrip(".")
    2954
    2955        if expression.args.get("escape"):
    2956            path = self.escape_str(path)
    2957
    2958        if self.QUOTE_JSON_PATH:
    2959            path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"
    2960
    2961        return path

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

    2963    def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str:
    2964        if isinstance(expression, exp.JSONPathPart):
    2965            transform = self.TRANSFORMS.get(expression.__class__)
    2966            if not callable(transform):
    2967                self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}")
    2968                return ""
    2969
    2970            return transform(self, expression)
    2971
    2972        if isinstance(expression, int):
    2973            return str(expression)
    2974
    2975        if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE:
    2976            escaped = expression.replace("'", "\\'")
    2977            escaped = f"\\'{expression}\\'"
    2978        else:
    2979            escaped = expression.replace('"', '\\"')
    2980            escaped = f'"{escaped}"'
    2981
    2982        return escaped

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

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

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

    2987    def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str:
    2988        null_handling = expression.args.get("null_handling")
    2989        null_handling = f" {null_handling}" if null_handling else ""
    2990
    2991        unique_keys = expression.args.get("unique_keys")
    2992        if unique_keys is not None:
    2993            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    2994        else:
    2995            unique_keys = ""
    2996
    2997        return_type = self.sql(expression, "return_type")
    2998        return_type = f" RETURNING {return_type}" if return_type else ""
    2999        encoding = self.sql(expression, "encoding")
    3000        encoding = f" ENCODING {encoding}" if encoding else ""
    3001
    3002        return self.func(
    3003            "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG",
    3004            *expression.expressions,
    3005            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
    3006        )

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

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

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

    3011    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
    3012        null_handling = expression.args.get("null_handling")
    3013        null_handling = f" {null_handling}" if null_handling else ""
    3014        return_type = self.sql(expression, "return_type")
    3015        return_type = f" RETURNING {return_type}" if return_type else ""
    3016        strict = " STRICT" if expression.args.get("strict") else ""
    3017        return self.func(
    3018            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
    3019        )

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

    3021    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
    3022        this = self.sql(expression, "this")
    3023        order = self.sql(expression, "order")
    3024        null_handling = expression.args.get("null_handling")
    3025        null_handling = f" {null_handling}" if null_handling else ""
    3026        return_type = self.sql(expression, "return_type")
    3027        return_type = f" RETURNING {return_type}" if return_type else ""
    3028        strict = " STRICT" if expression.args.get("strict") else ""
    3029        return self.func(
    3030            "JSON_ARRAYAGG",
    3031            this,
    3032            suffix=f"{order}{null_handling}{return_type}{strict})",
    3033        )

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

    3035    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
    3036        path = self.sql(expression, "path")
    3037        path = f" PATH {path}" if path else ""
    3038        nested_schema = self.sql(expression, "nested_schema")
    3039
    3040        if nested_schema:
    3041            return f"NESTED{path} {nested_schema}"
    3042
    3043        this = self.sql(expression, "this")
    3044        kind = self.sql(expression, "kind")
    3045        kind = f" {kind}" if kind else ""
    3046        return f"{this}{kind}{path}"

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

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

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

    3051    def jsontable_sql(self, expression: exp.JSONTable) -> str:
    3052        this = self.sql(expression, "this")
    3053        path = self.sql(expression, "path")
    3054        path = f", {path}" if path else ""
    3055        error_handling = expression.args.get("error_handling")
    3056        error_handling = f" {error_handling}" if error_handling else ""
    3057        empty_handling = expression.args.get("empty_handling")
    3058        empty_handling = f" {empty_handling}" if empty_handling else ""
    3059        schema = self.sql(expression, "schema")
    3060        return self.func(
    3061            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
    3062        )

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

    3064    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    3065        this = self.sql(expression, "this")
    3066        kind = self.sql(expression, "kind")
    3067        path = self.sql(expression, "path")
    3068        path = f" {path}" if path else ""
    3069        as_json = " AS JSON" if expression.args.get("as_json") else ""
    3070        return f"{this} {kind}{path}{as_json}"

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

    3072    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    3073        this = self.sql(expression, "this")
    3074        path = self.sql(expression, "path")
    3075        path = f", {path}" if path else ""
    3076        expressions = self.expressions(expression)
    3077        with_ = (
    3078            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    3079            if expressions
    3080            else ""
    3081        )
    3082        return f"OPENJSON({this}{path}){with_}"

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

    3084    def in_sql(self, expression: exp.In) -> str:
    3085        query = expression.args.get("query")
    3086        unnest = expression.args.get("unnest")
    3087        field = expression.args.get("field")
    3088        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    3089
    3090        if query:
    3091            in_sql = self.sql(query)
    3092        elif unnest:
    3093            in_sql = self.in_unnest_op(unnest)
    3094        elif field:
    3095            in_sql = self.sql(field)
    3096        else:
    3097            in_sql = f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})"
    3098
    3099        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"

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

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

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

    3104    def interval_sql(self, expression: exp.Interval) -> str:
    3105        unit = self.sql(expression, "unit")
    3106        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    3107            unit = self.TIME_PART_SINGULARS.get(unit, unit)
    3108        unit = f" {unit}" if unit else ""
    3109
    3110        if self.SINGLE_STRING_INTERVAL:
    3111            this = expression.this.name if expression.this else ""
    3112            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    3113
    3114        this = self.sql(expression, "this")
    3115        if this:
    3116            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    3117            this = f" {this}" if unwrapped else f" ({this})"
    3118
    3119        return f"INTERVAL{this}{unit}"

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

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

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

    3124    def reference_sql(self, expression: exp.Reference) -> str:
    3125        this = self.sql(expression, "this")
    3126        expressions = self.expressions(expression, flat=True)
    3127        expressions = f"({expressions})" if expressions else ""
    3128        options = self.expressions(expression, key="options", flat=True, sep=" ")
    3129        options = f" {options}" if options else ""
    3130        return f"REFERENCES {this}{expressions}{options}"

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

    3132    def anonymous_sql(self, expression: exp.Anonymous) -> str:
    3133        # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive
    3134        parent = expression.parent
    3135        is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression
    3136        return self.func(
    3137            self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified
    3138        )

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

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

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

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

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

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

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

    3153    def alias_sql(self, expression: exp.Alias) -> str:
    3154        alias = self.sql(expression, "alias")
    3155        alias = f" AS {alias}" if alias else ""
    3156        return f"{self.sql(expression, 'this')}{alias}"

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

    3158    def pivotalias_sql(self, expression: exp.PivotAlias) -> str:
    3159        alias = expression.args["alias"]
    3160
    3161        parent = expression.parent
    3162        pivot = parent and parent.parent
    3163
    3164        if isinstance(pivot, exp.Pivot) and pivot.unpivot:
    3165            identifier_alias = isinstance(alias, exp.Identifier)
    3166            literal_alias = isinstance(alias, exp.Literal)
    3167
    3168            if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    3169                alias.replace(exp.Literal.string(alias.output_name))
    3170            elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    3171                alias.replace(exp.to_identifier(alias.output_name))
    3172
    3173        return self.alias_sql(expression)

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

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

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

    3178    def atindex_sql(self, expression: exp.AtTimeZone) -> str:
    3179        this = self.sql(expression, "this")
    3180        index = self.sql(expression, "expression")
    3181        return f"{this} AT {index}"

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

    3183    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    3184        this = self.sql(expression, "this")
    3185        zone = self.sql(expression, "zone")
    3186        return f"{this} AT TIME ZONE {zone}"

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

    3188    def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str:
    3189        this = self.sql(expression, "this")
    3190        zone = self.sql(expression, "zone")
    3191        return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'"

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

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

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

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

    3201    def or_sql(
    3202        self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None
    3203    ) -> str:
    3204        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

    3206    def xor_sql(
    3207        self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None
    3208    ) -> str:
    3209        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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3265    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    3266        format_sql = self.sql(expression, "format")
    3267        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    3268        to_sql = self.sql(expression, "to")
    3269        to_sql = f" {to_sql}" if to_sql else ""
    3270        action = self.sql(expression, "action")
    3271        action = f" {action}" if action else ""
    3272        default = self.sql(expression, "default")
    3273        default = f" DEFAULT {default} ON CONVERSION ERROR" if default else ""
    3274        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

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

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

    3280    def collate_sql(self, expression: exp.Collate) -> str:
    3281        if self.COLLATE_IS_FUNC:
    3282            return self.function_fallback_sql(expression)
    3283        return self.binary(expression, "COLLATE")

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

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

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

    3288    def comment_sql(self, expression: exp.Comment) -> str:
    3289        this = self.sql(expression, "this")
    3290        kind = expression.args["kind"]
    3291        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    3292        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    3293        expression_sql = self.sql(expression, "expression")
    3294        return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"

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

    3296    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    3297        this = self.sql(expression, "this")
    3298        delete = " DELETE" if expression.args.get("delete") else ""
    3299        recompress = self.sql(expression, "recompress")
    3300        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    3301        to_disk = self.sql(expression, "to_disk")
    3302        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    3303        to_volume = self.sql(expression, "to_volume")
    3304        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    3305        return f"{this}{delete}{recompress}{to_disk}{to_volume}"

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

    3307    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    3308        where = self.sql(expression, "where")
    3309        group = self.sql(expression, "group")
    3310        aggregates = self.expressions(expression, key="aggregates")
    3311        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    3312
    3313        if not (where or group or aggregates) and len(expression.expressions) == 1:
    3314            return f"TTL {self.expressions(expression, flat=True)}"
    3315
    3316        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"

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

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

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

    3321    def commit_sql(self, expression: exp.Commit) -> str:
    3322        chain = expression.args.get("chain")
    3323        if chain is not None:
    3324            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    3325
    3326        return f"COMMIT{chain or ''}"

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

    3328    def rollback_sql(self, expression: exp.Rollback) -> str:
    3329        savepoint = expression.args.get("savepoint")
    3330        savepoint = f" TO {savepoint}" if savepoint else ""
    3331        return f"ROLLBACK{savepoint}"

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

    3333    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    3334        this = self.sql(expression, "this")
    3335
    3336        dtype = self.sql(expression, "dtype")
    3337        if dtype:
    3338            collate = self.sql(expression, "collate")
    3339            collate = f" COLLATE {collate}" if collate else ""
    3340            using = self.sql(expression, "using")
    3341            using = f" USING {using}" if using else ""
    3342            return f"ALTER COLUMN {this} {self.ALTER_SET_TYPE} {dtype}{collate}{using}"
    3343
    3344        default = self.sql(expression, "default")
    3345        if default:
    3346            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    3347
    3348        comment = self.sql(expression, "comment")
    3349        if comment:
    3350            return f"ALTER COLUMN {this} COMMENT {comment}"
    3351
    3352        visible = expression.args.get("visible")
    3353        if visible:
    3354            return f"ALTER COLUMN {this} SET {visible}"
    3355
    3356        allow_null = expression.args.get("allow_null")
    3357        drop = expression.args.get("drop")
    3358
    3359        if not drop and not allow_null:
    3360            self.unsupported("Unsupported ALTER COLUMN syntax")
    3361
    3362        if allow_null is not None:
    3363            keyword = "DROP" if drop else "SET"
    3364            return f"ALTER COLUMN {this} {keyword} NOT NULL"
    3365
    3366        return f"ALTER COLUMN {this} DROP DEFAULT"

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

    3368    def alterindex_sql(self, expression: exp.AlterIndex) -> str:
    3369        this = self.sql(expression, "this")
    3370
    3371        visible = expression.args.get("visible")
    3372        visible_sql = "VISIBLE" if visible else "INVISIBLE"
    3373
    3374        return f"ALTER INDEX {this} {visible_sql}"

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

    3376    def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str:
    3377        this = self.sql(expression, "this")
    3378        if not isinstance(expression.this, exp.Var):
    3379            this = f"KEY DISTKEY {this}"
    3380        return f"ALTER DISTSTYLE {this}"

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

    3382    def altersortkey_sql(self, expression: exp.AlterSortKey) -> str:
    3383        compound = " COMPOUND" if expression.args.get("compound") else ""
    3384        this = self.sql(expression, "this")
    3385        expressions = self.expressions(expression, flat=True)
    3386        expressions = f"({expressions})" if expressions else ""
    3387        return f"ALTER{compound} SORTKEY {this or expressions}"

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

    3389    def alterrename_sql(self, expression: exp.AlterRename) -> str:
    3390        if not self.RENAME_TABLE_WITH_DB:
    3391            # Remove db from tables
    3392            expression = expression.transform(
    3393                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    3394            ).assert_is(exp.AlterRename)
    3395        this = self.sql(expression, "this")
    3396        return f"RENAME TO {this}"

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

    3398    def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
    3399        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3400        old_column = self.sql(expression, "this")
    3401        new_column = self.sql(expression, "to")
    3402        return f"RENAME COLUMN{exists} {old_column} TO {new_column}"

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

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

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

    3408    def alter_sql(self, expression: exp.Alter) -> str:
    3409        actions = expression.args["actions"]
    3410
    3411        if isinstance(actions[0], exp.ColumnDef):
    3412            actions = self.add_column_sql(expression)
    3413        elif isinstance(actions[0], exp.Schema):
    3414            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    3415        elif isinstance(actions[0], exp.Delete):
    3416            actions = self.expressions(expression, key="actions", flat=True)
    3417        elif isinstance(actions[0], exp.Query):
    3418            actions = "AS " + self.expressions(expression, key="actions")
    3419        else:
    3420            actions = self.expressions(expression, key="actions", flat=True)
    3421
    3422        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3423        on_cluster = self.sql(expression, "cluster")
    3424        on_cluster = f" {on_cluster}" if on_cluster else ""
    3425        only = " ONLY" if expression.args.get("only") else ""
    3426        options = self.expressions(expression, key="options")
    3427        options = f", {options}" if options else ""
    3428        kind = self.sql(expression, "kind")
    3429        not_valid = " NOT VALID" if expression.args.get("not_valid") else ""
    3430
    3431        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

    3433    def add_column_sql(self, expression: exp.Alter) -> str:
    3434        if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD:
    3435            return self.expressions(
    3436                expression,
    3437                key="actions",
    3438                prefix="ADD COLUMN ",
    3439                skip_first=True,
    3440            )
    3441        return f"ADD {self.expressions(expression, key='actions', flat=True)}"

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

    3443    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    3444        expressions = self.expressions(expression)
    3445        exists = " IF EXISTS " if expression.args.get("exists") else " "
    3446        return f"DROP{exists}{expressions}"

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

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

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

    3451    def distinct_sql(self, expression: exp.Distinct) -> str:
    3452        this = self.expressions(expression, flat=True)
    3453
    3454        if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1:
    3455            case = exp.case()
    3456            for arg in expression.expressions:
    3457                case = case.when(arg.is_(exp.null()), exp.null())
    3458            this = self.sql(case.else_(f"({this})"))
    3459
    3460        this = f" {this}" if this else ""
    3461
    3462        on = self.sql(expression, "on")
    3463        on = f" ON {on}" if on else ""
    3464        return f"DISTINCT{this}{on}"

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

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

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

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

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

    3472    def havingmax_sql(self, expression: exp.HavingMax) -> str:
    3473        this_sql = self.sql(expression, "this")
    3474        expression_sql = self.sql(expression, "expression")
    3475        kind = "MAX" if expression.args.get("max") else "MIN"
    3476        return f"{this_sql} HAVING {kind} {expression_sql}"

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

    3478    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    3479        return self.sql(
    3480            exp.Cast(
    3481                this=exp.Div(this=expression.this, expression=expression.expression),
    3482                to=exp.DataType(this=exp.DataType.Type.INT),
    3483            )
    3484        )

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

    3486    def dpipe_sql(self, expression: exp.DPipe) -> str:
    3487        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    3488            return self.func(
    3489                "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten())
    3490            )
    3491        return self.binary(expression, "||")

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

    3493    def div_sql(self, expression: exp.Div) -> str:
    3494        l, r = expression.left, expression.right
    3495
    3496        if not self.dialect.SAFE_DIVISION and expression.args.get("safe"):
    3497            r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0)))
    3498
    3499        if self.dialect.TYPED_DIVISION and not expression.args.get("typed"):
    3500            if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES):
    3501                l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE))
    3502
    3503        elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"):
    3504            if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES):
    3505                return self.sql(
    3506                    exp.cast(
    3507                        l / r,
    3508                        to=exp.DataType.Type.BIGINT,
    3509                    )
    3510                )
    3511
    3512        return self.binary(expression, "/")

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

    3514    def safedivide_sql(self, expression: exp.SafeDivide) -> str:
    3515        n = exp._wrap(expression.this, exp.Binary)
    3516        d = exp._wrap(expression.expression, exp.Binary)
    3517        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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3552    def is_sql(self, expression: exp.Is) -> str:
    3553        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    3554            return self.sql(
    3555                expression.this if expression.expression.this else exp.not_(expression.this)
    3556            )
    3557        return self.binary(expression, "IS")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3601    def try_sql(self, expression: exp.Try) -> str:
    3602        if not self.TRY_SUPPORTED:
    3603            self.unsupported("Unsupported TRY function")
    3604            return self.sql(expression, "this")
    3605
    3606        return self.func("TRY", expression.this)

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

    3608    def log_sql(self, expression: exp.Log) -> str:
    3609        this = expression.this
    3610        expr = expression.expression
    3611
    3612        if self.dialect.LOG_BASE_FIRST is False:
    3613            this, expr = expr, this
    3614        elif self.dialect.LOG_BASE_FIRST is None and expr:
    3615            if this.name in ("2", "10"):
    3616                return self.func(f"LOG{this.name}", expr)
    3617
    3618            self.unsupported(f"Unsupported logarithm with base {self.sql(this)}")
    3619
    3620        return self.func("LOG", this, expr)

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

    3622    def use_sql(self, expression: exp.Use) -> str:
    3623        kind = self.sql(expression, "kind")
    3624        kind = f" {kind}" if kind else ""
    3625        this = self.sql(expression, "this") or self.expressions(expression, flat=True)
    3626        this = f" {this}" if this else ""
    3627        return f"USE{kind}{this}"

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

    3629    def binary(self, expression: exp.Binary, op: str) -> str:
    3630        sqls: t.List[str] = []
    3631        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    3632        binary_type = type(expression)
    3633
    3634        while stack:
    3635            node = stack.pop()
    3636
    3637            if type(node) is binary_type:
    3638                op_func = node.args.get("operator")
    3639                if op_func:
    3640                    op = f"OPERATOR({self.sql(op_func)})"
    3641
    3642                stack.append(node.right)
    3643                stack.append(f" {self.maybe_comment(op, comments=node.comments)} ")
    3644                stack.append(node.left)
    3645            else:
    3646                sqls.append(self.sql(node))
    3647
    3648        return "".join(sqls)

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

    3650    def ceil_floor(self, expression: exp.Ceil | exp.Floor) -> str:
    3651        to_clause = self.sql(expression, "to")
    3652        if to_clause:
    3653            return f"{expression.sql_name()}({self.sql(expression, 'this')} TO {to_clause})"
    3654
    3655        return self.function_fallback_sql(expression)

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

    3657    def function_fallback_sql(self, expression: exp.Func) -> str:
    3658        args = []
    3659
    3660        for key in expression.arg_types:
    3661            arg_value = expression.args.get(key)
    3662
    3663            if isinstance(arg_value, list):
    3664                for value in arg_value:
    3665                    args.append(value)
    3666            elif arg_value is not None:
    3667                args.append(arg_value)
    3668
    3669        if self.dialect.PRESERVE_ORIGINAL_NAMES:
    3670            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
    3671        else:
    3672            name = expression.sql_name()
    3673
    3674        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

    3676    def func(
    3677        self,
    3678        name: str,
    3679        *args: t.Optional[exp.Expression | str],
    3680        prefix: str = "(",
    3681        suffix: str = ")",
    3682        normalize: bool = True,
    3683    ) -> str:
    3684        name = self.normalize_func(name) if normalize else name
    3685        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

    3687    def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str:
    3688        arg_sqls = tuple(
    3689            self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool)
    3690        )
    3691        if self.pretty and self.too_wide(arg_sqls):
    3692            return self.indent(
    3693                "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True
    3694            )
    3695        return sep.join(arg_sqls)

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

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

    3700    def format_time(
    3701        self,
    3702        expression: exp.Expression,
    3703        inverse_time_mapping: t.Optional[t.Dict[str, str]] = None,
    3704        inverse_time_trie: t.Optional[t.Dict] = None,
    3705    ) -> t.Optional[str]:
    3706        return format_time(
    3707            self.sql(expression, "format"),
    3708            inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING,
    3709            inverse_time_trie or self.dialect.INVERSE_TIME_TRIE,
    3710        )

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

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

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

    3768    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    3769        flat = flat or isinstance(expression.parent, exp.Properties)
    3770        expressions_sql = self.expressions(expression, flat=flat)
    3771        if flat:
    3772            return f"{op} {expressions_sql}"
    3773        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"

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

    3775    def naked_property(self, expression: exp.Property) -> str:
    3776        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    3777        if not property_name:
    3778            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    3779        return f"{property_name} {self.sql(expression, 'this')}"

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

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

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

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

    3787    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    3788        this = self.sql(expression, "this")
    3789        expressions = self.no_identify(self.expressions, expression)
    3790        expressions = (
    3791            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    3792        )
    3793        return f"{this}{expressions}" if expressions.strip() != "" else this

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

    3795    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    3796        this = self.sql(expression, "this")
    3797        expressions = self.expressions(expression, flat=True)
    3798        return f"{this}({expressions})"

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

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

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

    3803    def when_sql(self, expression: exp.When) -> str:
    3804        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    3805        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    3806        condition = self.sql(expression, "condition")
    3807        condition = f" AND {condition}" if condition else ""
    3808
    3809        then_expression = expression.args.get("then")
    3810        if isinstance(then_expression, exp.Insert):
    3811            this = self.sql(then_expression, "this")
    3812            this = f"INSERT {this}" if this else "INSERT"
    3813            then = self.sql(then_expression, "expression")
    3814            then = f"{this} VALUES {then}" if then else this
    3815        elif isinstance(then_expression, exp.Update):
    3816            if isinstance(then_expression.args.get("expressions"), exp.Star):
    3817                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    3818            else:
    3819                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    3820        else:
    3821            then = self.sql(then_expression)
    3822        return f"WHEN {matched}{source}{condition} THEN {then}"

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

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

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

    3827    def merge_sql(self, expression: exp.Merge) -> str:
    3828        table = expression.this
    3829        table_alias = ""
    3830
    3831        hints = table.args.get("hints")
    3832        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
    3833            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
    3834            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
    3835
    3836        this = self.sql(table)
    3837        using = f"USING {self.sql(expression, 'using')}"
    3838        on = f"ON {self.sql(expression, 'on')}"
    3839        whens = self.sql(expression, "whens")
    3840
    3841        returning = self.sql(expression, "returning")
    3842        if returning:
    3843            whens = f"{whens}{returning}"
    3844
    3845        sep = self.sep()
    3846
    3847        return self.prepend_ctes(
    3848            expression,
    3849            f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}",
    3850        )

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

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

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

    3856    def tonumber_sql(self, expression: exp.ToNumber) -> str:
    3857        if not self.SUPPORTS_TO_NUMBER:
    3858            self.unsupported("Unsupported TO_NUMBER function")
    3859            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3860
    3861        fmt = expression.args.get("format")
    3862        if not fmt:
    3863            self.unsupported("Conversion format is required for TO_NUMBER")
    3864            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3865
    3866        return self.func("TO_NUMBER", expression.this, fmt)

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

    3868    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    3869        this = self.sql(expression, "this")
    3870        kind = self.sql(expression, "kind")
    3871        settings_sql = self.expressions(expression, key="settings", sep=" ")
    3872        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    3873        return f"{this}({kind}{args})"

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

    3875    def dictrange_sql(self, expression: exp.DictRange) -> str:
    3876        this = self.sql(expression, "this")
    3877        max = self.sql(expression, "max")
    3878        min = self.sql(expression, "min")
    3879        return f"{this}(MIN {min} MAX {max})"

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

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

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

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

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

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

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

    3892    def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str:
    3893        expressions = self.expressions(expression, flat=True)
    3894        expressions = f" {self.wrap(expressions)}" if expressions else ""
    3895        buckets = self.sql(expression, "buckets")
    3896        kind = self.sql(expression, "kind")
    3897        buckets = f" BUCKETS {buckets}" if buckets else ""
    3898        order = self.sql(expression, "order")
    3899        return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}"

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

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

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

    3904    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    3905        expressions = self.expressions(expression, key="expressions", flat=True)
    3906        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    3907        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    3908        buckets = self.sql(expression, "buckets")
    3909        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"

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

    3911    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    3912        this = self.sql(expression, "this")
    3913        having = self.sql(expression, "having")
    3914
    3915        if having:
    3916            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    3917
    3918        return self.func("ANY_VALUE", this)

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

    3920    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
    3921        transform = self.func("TRANSFORM", *expression.expressions)
    3922        row_format_before = self.sql(expression, "row_format_before")
    3923        row_format_before = f" {row_format_before}" if row_format_before else ""
    3924        record_writer = self.sql(expression, "record_writer")
    3925        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
    3926        using = f" USING {self.sql(expression, 'command_script')}"
    3927        schema = self.sql(expression, "schema")
    3928        schema = f" AS {schema}" if schema else ""
    3929        row_format_after = self.sql(expression, "row_format_after")
    3930        row_format_after = f" {row_format_after}" if row_format_after else ""
    3931        record_reader = self.sql(expression, "record_reader")
    3932        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
    3933        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

    3935    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
    3936        key_block_size = self.sql(expression, "key_block_size")
    3937        if key_block_size:
    3938            return f"KEY_BLOCK_SIZE = {key_block_size}"
    3939
    3940        using = self.sql(expression, "using")
    3941        if using:
    3942            return f"USING {using}"
    3943
    3944        parser = self.sql(expression, "parser")
    3945        if parser:
    3946            return f"WITH PARSER {parser}"
    3947
    3948        comment = self.sql(expression, "comment")
    3949        if comment:
    3950            return f"COMMENT {comment}"
    3951
    3952        visible = expression.args.get("visible")
    3953        if visible is not None:
    3954            return "VISIBLE" if visible else "INVISIBLE"
    3955
    3956        engine_attr = self.sql(expression, "engine_attr")
    3957        if engine_attr:
    3958            return f"ENGINE_ATTRIBUTE = {engine_attr}"
    3959
    3960        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
    3961        if secondary_engine_attr:
    3962            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
    3963
    3964        self.unsupported("Unsupported index constraint option.")
    3965        return ""

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

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

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

    3971    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
    3972        kind = self.sql(expression, "kind")
    3973        kind = f"{kind} INDEX" if kind else "INDEX"
    3974        this = self.sql(expression, "this")
    3975        this = f" {this}" if this else ""
    3976        index_type = self.sql(expression, "index_type")
    3977        index_type = f" USING {index_type}" if index_type else ""
    3978        expressions = self.expressions(expression, flat=True)
    3979        expressions = f" ({expressions})" if expressions else ""
    3980        options = self.expressions(expression, key="options", sep=" ")
    3981        options = f" {options}" if options else ""
    3982        return f"{kind}{this}{index_type}{expressions}{options}"

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

    3984    def nvl2_sql(self, expression: exp.Nvl2) -> str:
    3985        if self.NVL2_SUPPORTED:
    3986            return self.function_fallback_sql(expression)
    3987
    3988        case = exp.Case().when(
    3989            expression.this.is_(exp.null()).not_(copy=False),
    3990            expression.args["true"],
    3991            copy=False,
    3992        )
    3993        else_cond = expression.args.get("false")
    3994        if else_cond:
    3995            case.else_(else_cond, copy=False)
    3996
    3997        return self.sql(case)

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

    3999    def comprehension_sql(self, expression: exp.Comprehension) -> str:
    4000        this = self.sql(expression, "this")
    4001        expr = self.sql(expression, "expression")
    4002        iterator = self.sql(expression, "iterator")
    4003        condition = self.sql(expression, "condition")
    4004        condition = f" IF {condition}" if condition else ""
    4005        return f"{this} FOR {expr} IN {iterator}{condition}"

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

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

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

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

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

    4013    def predict_sql(self, expression: exp.Predict) -> str:
    4014        model = self.sql(expression, "this")
    4015        model = f"MODEL {model}"
    4016        table = self.sql(expression, "expression")
    4017        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
    4018        parameters = self.sql(expression, "params_struct")
    4019        return self.func("PREDICT", model, table, parameters or None)

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

    4021    def forin_sql(self, expression: exp.ForIn) -> str:
    4022        this = self.sql(expression, "this")
    4023        expression_sql = self.sql(expression, "expression")
    4024        return f"FOR {this} DO {expression_sql}"

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

    4026    def refresh_sql(self, expression: exp.Refresh) -> str:
    4027        this = self.sql(expression, "this")
    4028        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
    4029        return f"REFRESH {table}{this}"

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

    4031    def toarray_sql(self, expression: exp.ToArray) -> str:
    4032        arg = expression.this
    4033        if not arg.type:
    4034            from sqlglot.optimizer.annotate_types import annotate_types
    4035
    4036            arg = annotate_types(arg, dialect=self.dialect)
    4037
    4038        if arg.is_type(exp.DataType.Type.ARRAY):
    4039            return self.sql(arg)
    4040
    4041        cond_for_null = arg.is_(exp.null())
    4042        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

    4044    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
    4045        this = expression.this
    4046        time_format = self.format_time(expression)
    4047
    4048        if time_format:
    4049            return self.sql(
    4050                exp.cast(
    4051                    exp.StrToTime(this=this, format=expression.args["format"]),
    4052                    exp.DataType.Type.TIME,
    4053                )
    4054            )
    4055
    4056        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
    4057            return self.sql(this)
    4058
    4059        return self.sql(exp.cast(this, exp.DataType.Type.TIME))

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

    4061    def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str:
    4062        this = expression.this
    4063        if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP):
    4064            return self.sql(this)
    4065
    4066        return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect))

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

    4068    def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str:
    4069        this = expression.this
    4070        if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME):
    4071            return self.sql(this)
    4072
    4073        return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect))

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

    4075    def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:
    4076        this = expression.this
    4077        time_format = self.format_time(expression)
    4078
    4079        if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT):
    4080            return self.sql(
    4081                exp.cast(
    4082                    exp.StrToTime(this=this, format=expression.args["format"]),
    4083                    exp.DataType.Type.DATE,
    4084                )
    4085            )
    4086
    4087        if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE):
    4088            return self.sql(this)
    4089
    4090        return self.sql(exp.cast(this, exp.DataType.Type.DATE))

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

    4092    def unixdate_sql(self, expression: exp.UnixDate) -> str:
    4093        return self.sql(
    4094            exp.func(
    4095                "DATEDIFF",
    4096                expression.this,
    4097                exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE),
    4098                "day",
    4099            )
    4100        )

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

    4102    def lastday_sql(self, expression: exp.LastDay) -> str:
    4103        if self.LAST_DAY_SUPPORTS_DATE_PART:
    4104            return self.function_fallback_sql(expression)
    4105
    4106        unit = expression.text("unit")
    4107        if unit and unit != "MONTH":
    4108            self.unsupported("Date parts are not supported in LAST_DAY.")
    4109
    4110        return self.func("LAST_DAY", expression.this)

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

    4112    def dateadd_sql(self, expression: exp.DateAdd) -> str:
    4113        from sqlglot.dialects.dialect import unit_to_str
    4114
    4115        return self.func(
    4116            "DATE_ADD", expression.this, expression.expression, unit_to_str(expression)
    4117        )

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

    4119    def arrayany_sql(self, expression: exp.ArrayAny) -> str:
    4120        if self.CAN_IMPLEMENT_ARRAY_ANY:
    4121            filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression)
    4122            filtered_not_empty = exp.ArraySize(this=filtered).neq(0)
    4123            original_is_empty = exp.ArraySize(this=expression.this).eq(0)
    4124            return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty)))
    4125
    4126        from sqlglot.dialects import Dialect
    4127
    4128        # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect
    4129        if self.dialect.__class__ != Dialect:
    4130            self.unsupported("ARRAY_ANY is unsupported")
    4131
    4132        return self.function_fallback_sql(expression)

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

    4134    def struct_sql(self, expression: exp.Struct) -> str:
    4135        expression.set(
    4136            "expressions",
    4137            [
    4138                exp.alias_(e.expression, e.name if e.this.is_string else e.this)
    4139                if isinstance(e, exp.PropertyEQ)
    4140                else e
    4141                for e in expression.expressions
    4142            ],
    4143        )
    4144
    4145        return self.function_fallback_sql(expression)

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

    4147    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
    4148        low = self.sql(expression, "this")
    4149        high = self.sql(expression, "expression")
    4150
    4151        return f"{low} TO {high}"

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

    4153    def truncatetable_sql(self, expression: exp.TruncateTable) -> str:
    4154        target = "DATABASE" if expression.args.get("is_database") else "TABLE"
    4155        tables = f" {self.expressions(expression)}"
    4156
    4157        exists = " IF EXISTS" if expression.args.get("exists") else ""
    4158
    4159        on_cluster = self.sql(expression, "cluster")
    4160        on_cluster = f" {on_cluster}" if on_cluster else ""
    4161
    4162        identity = self.sql(expression, "identity")
    4163        identity = f" {identity} IDENTITY" if identity else ""
    4164
    4165        option = self.sql(expression, "option")
    4166        option = f" {option}" if option else ""
    4167
    4168        partition = self.sql(expression, "partition")
    4169        partition = f" {partition}" if partition else ""
    4170
    4171        return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"

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

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

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

    4275    def copyparameter_sql(self, expression: exp.CopyParameter) -> str:
    4276        option = self.sql(expression, "this")
    4277
    4278        if expression.expressions:
    4279            upper = option.upper()
    4280
    4281            # Snowflake FILE_FORMAT options are separated by whitespace
    4282            sep = " " if upper == "FILE_FORMAT" else ", "
    4283
    4284            # Databricks copy/format options do not set their list of values with EQ
    4285            op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = "
    4286            values = self.expressions(expression, flat=True, sep=sep)
    4287            return f"{option}{op}({values})"
    4288
    4289        value = self.sql(expression, "expression")
    4290
    4291        if not value:
    4292            return option
    4293
    4294        op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " "
    4295
    4296        return f"{option}{op}{value}"

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

    4298    def credentials_sql(self, expression: exp.Credentials) -> str:
    4299        cred_expr = expression.args.get("credentials")
    4300        if isinstance(cred_expr, exp.Literal):
    4301            # Redshift case: CREDENTIALS <string>
    4302            credentials = self.sql(expression, "credentials")
    4303            credentials = f"CREDENTIALS {credentials}" if credentials else ""
    4304        else:
    4305            # Snowflake case: CREDENTIALS = (...)
    4306            credentials = self.expressions(expression, key="credentials", flat=True, sep=" ")
    4307            credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else ""
    4308
    4309        storage = self.sql(expression, "storage")
    4310        storage = f"STORAGE_INTEGRATION = {storage}" if storage else ""
    4311
    4312        encryption = self.expressions(expression, key="encryption", flat=True, sep=" ")
    4313        encryption = f" ENCRYPTION = ({encryption})" if encryption else ""
    4314
    4315        iam_role = self.sql(expression, "iam_role")
    4316        iam_role = f"IAM_ROLE {iam_role}" if iam_role else ""
    4317
    4318        region = self.sql(expression, "region")
    4319        region = f" REGION {region}" if region else ""
    4320
    4321        return f"{credentials}{storage}{encryption}{iam_role}{region}"

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

    4323    def copy_sql(self, expression: exp.Copy) -> str:
    4324        this = self.sql(expression, "this")
    4325        this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}"
    4326
    4327        credentials = self.sql(expression, "credentials")
    4328        credentials = self.seg(credentials) if credentials else ""
    4329        kind = self.seg("FROM" if expression.args.get("kind") else "TO")
    4330        files = self.expressions(expression, key="files", flat=True)
    4331
    4332        sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " "
    4333        params = self.expressions(
    4334            expression,
    4335            key="params",
    4336            sep=sep,
    4337            new_line=True,
    4338            skip_last=True,
    4339            skip_first=True,
    4340            indent=self.COPY_PARAMS_ARE_WRAPPED,
    4341        )
    4342
    4343        if params:
    4344            if self.COPY_PARAMS_ARE_WRAPPED:
    4345                params = f" WITH ({params})"
    4346            elif not self.pretty:
    4347                params = f" {params}"
    4348
    4349        return f"COPY{this}{kind} {files}{credentials}{params}"

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

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

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

    4354    def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str:
    4355        on_sql = "ON" if expression.args.get("on") else "OFF"
    4356        filter_col: t.Optional[str] = self.sql(expression, "filter_column")
    4357        filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None
    4358        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    4359        retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None
    4360
    4361        if filter_col or retention_period:
    4362            on_sql = self.func("ON", filter_col, retention_period)
    4363
    4364        return f"DATA_DELETION={on_sql}"

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

    4366    def maskingpolicycolumnconstraint_sql(
    4367        self, expression: exp.MaskingPolicyColumnConstraint
    4368    ) -> str:
    4369        this = self.sql(expression, "this")
    4370        expressions = self.expressions(expression, flat=True)
    4371        expressions = f" USING ({expressions})" if expressions else ""
    4372        return f"MASKING POLICY {this}{expressions}"

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

    4374    def gapfill_sql(self, expression: exp.GapFill) -> str:
    4375        this = self.sql(expression, "this")
    4376        this = f"TABLE {this}"
    4377        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

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

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

    4382    def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str:
    4383        this = self.sql(expression, "this")
    4384        expr = expression.expression
    4385
    4386        if isinstance(expr, exp.Func):
    4387            # T-SQL's CLR functions are case sensitive
    4388            expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})"
    4389        else:
    4390            expr = self.sql(expression, "expression")
    4391
    4392        return self.scope_resolution(expr, this)

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

    4394    def parsejson_sql(self, expression: exp.ParseJSON) -> str:
    4395        if self.PARSE_JSON_NAME is None:
    4396            return self.sql(expression.this)
    4397
    4398        return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression)

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

    4400    def rand_sql(self, expression: exp.Rand) -> str:
    4401        lower = self.sql(expression, "lower")
    4402        upper = self.sql(expression, "upper")
    4403
    4404        if lower and upper:
    4405            return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}"
    4406        return self.func("RAND", expression.this)

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

    4408    def changes_sql(self, expression: exp.Changes) -> str:
    4409        information = self.sql(expression, "information")
    4410        information = f"INFORMATION => {information}"
    4411        at_before = self.sql(expression, "at_before")
    4412        at_before = f"{self.seg('')}{at_before}" if at_before else ""
    4413        end = self.sql(expression, "end")
    4414        end = f"{self.seg('')}{end}" if end else ""
    4415
    4416        return f"CHANGES ({information}){at_before}{end}"

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

    4418    def pad_sql(self, expression: exp.Pad) -> str:
    4419        prefix = "L" if expression.args.get("is_left") else "R"
    4420
    4421        fill_pattern = self.sql(expression, "fill_pattern") or None
    4422        if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED:
    4423            fill_pattern = "' '"
    4424
    4425        return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)

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

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

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

    4431    def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str:
    4432        generate_series = exp.GenerateSeries(**expression.args)
    4433
    4434        parent = expression.parent
    4435        if isinstance(parent, (exp.Alias, exp.TableAlias)):
    4436            parent = parent.parent
    4437
    4438        if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)):
    4439            return self.sql(exp.Unnest(expressions=[generate_series]))
    4440
    4441        if isinstance(parent, exp.Select):
    4442            self.unsupported("GenerateSeries projection unnesting is not supported.")
    4443
    4444        return self.sql(generate_series)

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

    4446    def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str:
    4447        exprs = expression.expressions
    4448        if not self.ARRAY_CONCAT_IS_VAR_LEN:
    4449            rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs)
    4450        else:
    4451            rhs = self.expressions(expression)
    4452
    4453        return self.func(name, expression.this, rhs or None)

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

    4455    def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str:
    4456        if self.SUPPORTS_CONVERT_TIMEZONE:
    4457            return self.function_fallback_sql(expression)
    4458
    4459        source_tz = expression.args.get("source_tz")
    4460        target_tz = expression.args.get("target_tz")
    4461        timestamp = expression.args.get("timestamp")
    4462
    4463        if source_tz and timestamp:
    4464            timestamp = exp.AtTimeZone(
    4465                this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz
    4466            )
    4467
    4468        expr = exp.AtTimeZone(this=timestamp, zone=target_tz)
    4469
    4470        return self.sql(expr)

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

    4472    def json_sql(self, expression: exp.JSON) -> str:
    4473        this = self.sql(expression, "this")
    4474        this = f" {this}" if this else ""
    4475
    4476        _with = expression.args.get("with")
    4477
    4478        if _with is None:
    4479            with_sql = ""
    4480        elif not _with:
    4481            with_sql = " WITHOUT"
    4482        else:
    4483            with_sql = " WITH"
    4484
    4485        unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else ""
    4486
    4487        return f"JSON{this}{with_sql}{unique_sql}"

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

    4489    def jsonvalue_sql(self, expression: exp.JSONValue) -> str:
    4490        def _generate_on_options(arg: t.Any) -> str:
    4491            return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}"
    4492
    4493        path = self.sql(expression, "path")
    4494        returning = self.sql(expression, "returning")
    4495        returning = f" RETURNING {returning}" if returning else ""
    4496
    4497        on_condition = self.sql(expression, "on_condition")
    4498        on_condition = f" {on_condition}" if on_condition else ""
    4499
    4500        return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}")

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

    4502    def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str:
    4503        else_ = "ELSE " if expression.args.get("else_") else ""
    4504        condition = self.sql(expression, "expression")
    4505        condition = f"WHEN {condition} THEN " if condition else else_
    4506        insert = self.sql(expression, "this")[len("INSERT") :].strip()
    4507        return f"{condition}{insert}"

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

    4509    def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str:
    4510        kind = self.sql(expression, "kind")
    4511        expressions = self.seg(self.expressions(expression, sep=" "))
    4512        res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}"
    4513        return res

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

    4515    def oncondition_sql(self, expression: exp.OnCondition) -> str:
    4516        # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR"
    4517        empty = expression.args.get("empty")
    4518        empty = (
    4519            f"DEFAULT {empty} ON EMPTY"
    4520            if isinstance(empty, exp.Expression)
    4521            else self.sql(expression, "empty")
    4522        )
    4523
    4524        error = expression.args.get("error")
    4525        error = (
    4526            f"DEFAULT {error} ON ERROR"
    4527            if isinstance(error, exp.Expression)
    4528            else self.sql(expression, "error")
    4529        )
    4530
    4531        if error and empty:
    4532            error = (
    4533                f"{empty} {error}"
    4534                if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR
    4535                else f"{error} {empty}"
    4536            )
    4537            empty = ""
    4538
    4539        null = self.sql(expression, "null")
    4540
    4541        return f"{empty}{error}{null}"

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

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

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

    4547    def jsonexists_sql(self, expression: exp.JSONExists) -> str:
    4548        this = self.sql(expression, "this")
    4549        path = self.sql(expression, "path")
    4550
    4551        passing = self.expressions(expression, "passing")
    4552        passing = f" PASSING {passing}" if passing else ""
    4553
    4554        on_condition = self.sql(expression, "on_condition")
    4555        on_condition = f" {on_condition}" if on_condition else ""
    4556
    4557        path = f"{path}{passing}{on_condition}"
    4558
    4559        return self.func("JSON_EXISTS", this, path)

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

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

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

    4586    def apply_sql(self, expression: exp.Apply) -> str:
    4587        this = self.sql(expression, "this")
    4588        expr = self.sql(expression, "expression")
    4589
    4590        return f"{this} APPLY({expr})"

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

    4592    def grant_sql(self, expression: exp.Grant) -> str:
    4593        privileges_sql = self.expressions(expression, key="privileges", flat=True)
    4594
    4595        kind = self.sql(expression, "kind")
    4596        kind = f" {kind}" if kind else ""
    4597
    4598        securable = self.sql(expression, "securable")
    4599        securable = f" {securable}" if securable else ""
    4600
    4601        principals = self.expressions(expression, key="principals", flat=True)
    4602
    4603        grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else ""
    4604
    4605        return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}"

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

    4607    def grantprivilege_sql(self, expression: exp.GrantPrivilege):
    4608        this = self.sql(expression, "this")
    4609        columns = self.expressions(expression, flat=True)
    4610        columns = f"({columns})" if columns else ""
    4611
    4612        return f"{this}{columns}"

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

    4614    def grantprincipal_sql(self, expression: exp.GrantPrincipal):
    4615        this = self.sql(expression, "this")
    4616
    4617        kind = self.sql(expression, "kind")
    4618        kind = f"{kind} " if kind else ""
    4619
    4620        return f"{kind}{this}"

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

    4622    def columns_sql(self, expression: exp.Columns):
    4623        func = self.function_fallback_sql(expression)
    4624        if expression.args.get("unpack"):
    4625            func = f"*{func}"
    4626
    4627        return func

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

    4629    def overlay_sql(self, expression: exp.Overlay):
    4630        this = self.sql(expression, "this")
    4631        expr = self.sql(expression, "expression")
    4632        from_sql = self.sql(expression, "from")
    4633        for_sql = self.sql(expression, "for")
    4634        for_sql = f" FOR {for_sql}" if for_sql else ""
    4635
    4636        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

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

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

    4642    def string_sql(self, expression: exp.String) -> str:
    4643        this = expression.this
    4644        zone = expression.args.get("zone")
    4645
    4646        if zone:
    4647            # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>)
    4648            # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC
    4649            # set for source_tz to transpile the time conversion before the STRING cast
    4650            this = exp.ConvertTimezone(
    4651                source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this
    4652            )
    4653
    4654        return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR))

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

    4656    def median_sql(self, expression: exp.Median):
    4657        if not self.SUPPORTS_MEDIAN:
    4658            return self.sql(
    4659                exp.PercentileCont(this=expression.this, expression=exp.Literal.number(0.5))
    4660            )
    4661
    4662        return self.function_fallback_sql(expression)

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

    4664    def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str:
    4665        filler = self.sql(expression, "this")
    4666        filler = f" {filler}" if filler else ""
    4667        with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT"
    4668        return f"TRUNCATE{filler} {with_count}"

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

    4670    def unixseconds_sql(self, expression: exp.UnixSeconds) -> str:
    4671        if self.SUPPORTS_UNIX_SECONDS:
    4672            return self.function_fallback_sql(expression)
    4673
    4674        start_ts = exp.cast(
    4675            exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ
    4676        )
    4677
    4678        return self.sql(
    4679            exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS"))
    4680        )

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

    4682    def arraysize_sql(self, expression: exp.ArraySize) -> str:
    4683        dim = expression.expression
    4684
    4685        # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension)
    4686        if dim and self.ARRAY_SIZE_DIM_REQUIRED is None:
    4687            if not (dim.is_int and dim.name == "1"):
    4688                self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH")
    4689            dim = None
    4690
    4691        # If dimension is required but not specified, default initialize it
    4692        if self.ARRAY_SIZE_DIM_REQUIRED and not dim:
    4693            dim = exp.Literal.number(1)
    4694
    4695        return self.func(self.ARRAY_SIZE_NAME, expression.this, dim)

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

    4697    def attach_sql(self, expression: exp.Attach) -> str:
    4698        this = self.sql(expression, "this")
    4699        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
    4700        expressions = self.expressions(expression)
    4701        expressions = f" ({expressions})" if expressions else ""
    4702
    4703        return f"ATTACH{exists_sql} {this}{expressions}"

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

    4705    def detach_sql(self, expression: exp.Detach) -> str:
    4706        this = self.sql(expression, "this")
    4707        exists_sql = " IF EXISTS" if expression.args.get("exists") else ""
    4708
    4709        return f"DETACH{exists_sql} {this}"

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

    4711    def attachoption_sql(self, expression: exp.AttachOption) -> str:
    4712        this = self.sql(expression, "this")
    4713        value = self.sql(expression, "expression")
    4714        value = f" {value}" if value else ""
    4715        return f"{this}{value}"

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

    4717    def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str:
    4718        this_sql = self.sql(expression, "this")
    4719        if isinstance(expression.this, exp.Table):
    4720            this_sql = f"TABLE {this_sql}"
    4721
    4722        return self.func(
    4723            "FEATURES_AT_TIME",
    4724            this_sql,
    4725            expression.args.get("time"),
    4726            expression.args.get("num_rows"),
    4727            expression.args.get("ignore_feature_nulls"),
    4728        )

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

    4730    def watermarkcolumnconstraint_sql(self, expression: exp.WatermarkColumnConstraint) -> str:
    4731        return (
    4732            f"WATERMARK FOR {self.sql(expression, 'this')} AS {self.sql(expression, 'expression')}"
    4733        )

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

    4735    def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str:
    4736        encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE"
    4737        encode = f"{encode} {self.sql(expression, 'this')}"
    4738
    4739        properties = expression.args.get("properties")
    4740        if properties:
    4741            encode = f"{encode} {self.properties(properties)}"
    4742
    4743        return encode

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

    4745    def includeproperty_sql(self, expression: exp.IncludeProperty) -> str:
    4746        this = self.sql(expression, "this")
    4747        include = f"INCLUDE {this}"
    4748
    4749        column_def = self.sql(expression, "column_def")
    4750        if column_def:
    4751            include = f"{include} {column_def}"
    4752
    4753        alias = self.sql(expression, "alias")
    4754        if alias:
    4755            include = f"{include} AS {alias}"
    4756
    4757        return include

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

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

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

    4763    def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str:
    4764        partitions = self.expressions(expression, "partition_expressions")
    4765        create = self.expressions(expression, "create_expressions")
    4766        return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}"

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

    4768    def partitionbyrangepropertydynamic_sql(
    4769        self, expression: exp.PartitionByRangePropertyDynamic
    4770    ) -> str:
    4771        start = self.sql(expression, "start")
    4772        end = self.sql(expression, "end")
    4773
    4774        every = expression.args["every"]
    4775        if isinstance(every, exp.Interval) and every.this.is_string:
    4776            every.this.replace(exp.Literal.number(every.name))
    4777
    4778        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

    4780    def unpivotcolumns_sql(self, expression: exp.UnpivotColumns) -> str:
    4781        name = self.sql(expression, "this")
    4782        values = self.expressions(expression, flat=True)
    4783
    4784        return f"NAME {name} VALUE {values}"

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

    4786    def analyzesample_sql(self, expression: exp.AnalyzeSample) -> str:
    4787        kind = self.sql(expression, "kind")
    4788        sample = self.sql(expression, "sample")
    4789        return f"SAMPLE {sample} {kind}"

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

    4791    def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str:
    4792        kind = self.sql(expression, "kind")
    4793        option = self.sql(expression, "option")
    4794        option = f" {option}" if option else ""
    4795        this = self.sql(expression, "this")
    4796        this = f" {this}" if this else ""
    4797        columns = self.expressions(expression)
    4798        columns = f" {columns}" if columns else ""
    4799        return f"{kind}{option} STATISTICS{this}{columns}"

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

    4801    def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str:
    4802        this = self.sql(expression, "this")
    4803        columns = self.expressions(expression)
    4804        inner_expression = self.sql(expression, "expression")
    4805        inner_expression = f" {inner_expression}" if inner_expression else ""
    4806        update_options = self.sql(expression, "update_options")
    4807        update_options = f" {update_options} UPDATE" if update_options else ""
    4808        return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}"

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

    4810    def analyzedelete_sql(self, expression: exp.AnalyzeDelete) -> str:
    4811        kind = self.sql(expression, "kind")
    4812        kind = f" {kind}" if kind else ""
    4813        return f"DELETE{kind} STATISTICS"

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

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

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

    4819    def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str:
    4820        kind = self.sql(expression, "kind")
    4821        this = self.sql(expression, "this")
    4822        this = f" {this}" if this else ""
    4823        inner_expression = self.sql(expression, "expression")
    4824        return f"VALIDATE {kind}{this}{inner_expression}"

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

    4826    def analyze_sql(self, expression: exp.Analyze) -> str:
    4827        options = self.expressions(expression, key="options", sep=" ")
    4828        options = f" {options}" if options else ""
    4829        kind = self.sql(expression, "kind")
    4830        kind = f" {kind}" if kind else ""
    4831        this = self.sql(expression, "this")
    4832        this = f" {this}" if this else ""
    4833        mode = self.sql(expression, "mode")
    4834        mode = f" {mode}" if mode else ""
    4835        properties = self.sql(expression, "properties")
    4836        properties = f" {properties}" if properties else ""
    4837        partition = self.sql(expression, "partition")
    4838        partition = f" {partition}" if partition else ""
    4839        inner_expression = self.sql(expression, "expression")
    4840        inner_expression = f" {inner_expression}" if inner_expression else ""
    4841        return f"ANALYZE{options}{kind}{this}{partition}{mode}{inner_expression}{properties}"

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

    4843    def xmltable_sql(self, expression: exp.XMLTable) -> str:
    4844        this = self.sql(expression, "this")
    4845        namespaces = self.expressions(expression, key="namespaces")
    4846        namespaces = f"XMLNAMESPACES({namespaces}), " if namespaces else ""
    4847        passing = self.expressions(expression, key="passing")
    4848        passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else ""
    4849        columns = self.expressions(expression, key="columns")
    4850        columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else ""
    4851        by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else ""
    4852        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

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

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

    4858    def export_sql(self, expression: exp.Export) -> str:
    4859        this = self.sql(expression, "this")
    4860        connection = self.sql(expression, "connection")
    4861        connection = f"WITH CONNECTION {connection} " if connection else ""
    4862        options = self.sql(expression, "options")
    4863        return f"EXPORT DATA {connection}{options} AS {this}"

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

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

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

    4868    def declareitem_sql(self, expression: exp.DeclareItem) -> str:
    4869        variable = self.sql(expression, "this")
    4870        default = self.sql(expression, "default")
    4871        default = f" = {default}" if default else ""
    4872
    4873        kind = self.sql(expression, "kind")
    4874        if isinstance(expression.args.get("kind"), exp.Schema):
    4875            kind = f"TABLE {kind}"
    4876
    4877        return f"{variable} AS {kind}{default}"

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

    4879    def recursivewithsearch_sql(self, expression: exp.RecursiveWithSearch) -> str:
    4880        kind = self.sql(expression, "kind")
    4881        this = self.sql(expression, "this")
    4882        set = self.sql(expression, "expression")
    4883        using = self.sql(expression, "using")
    4884        using = f" USING {using}" if using else ""
    4885
    4886        kind_sql = kind if kind == "CYCLE" else f"SEARCH {kind} FIRST BY"
    4887
    4888        return f"{kind_sql} {this} SET {set}{using}"

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

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

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

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

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

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

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

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

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

    4903    def show_sql(self, expression: exp.Show) -> str:
    4904        self.unsupported("Unsupported SHOW statement")
    4905        return ""

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

    4907    def put_sql(self, expression: exp.Put) -> str:
    4908        props = expression.args.get("properties")
    4909        props_sql = self.properties(props, prefix=" ", sep=" ", wrapped=False) if props else ""
    4910        this = self.sql(expression, "this")
    4911        target = self.sql(expression, "target")
    4912        return f"PUT {this} {target}{props_sql}"