sqlglot.generator API documentation

Edit on GitHub

# sqlglot.generator

View Source

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

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

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

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

class Generator: View Source

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

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

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

TRANSFORMS: Dict[Type[sqlglot.expressions.Expression], Callable[..., str]] = {<class 'sqlglot.expressions.JSONPathFilter'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathKey'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathRecursive'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathRoot'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathScript'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSelector'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSlice'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSubscript'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathUnion'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathWildcard'>: <function <lambda>>, <class 'sqlglot.expressions.AllowedValuesProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AnalyzeColumns'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AnalyzeWith'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ArrayContainsAll'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ArrayOverlaps'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AutoRefreshProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.BackupProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CaseSpecificColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Ceil'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CommentColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ConnectByRoot'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DateFormatColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DefaultColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DynamicProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EmptyProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EncodeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EphemeralColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExcludeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Except'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExternalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Floor'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.GlobalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.HeapProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.IcebergProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InheritsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InlineLengthColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Intersect'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.IntervalSpan'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Int64'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LanguageProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LocationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.MaterializedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NonClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NotForReplicationColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnCommitProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnUpdateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Operator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OutputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PivotAny'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ProjectionPolicyColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ReturnsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SampleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SecureProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetConfigProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SharingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlReadWriteProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StabilityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Stream'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StreamingTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StrictProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SwapTable'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TemporaryProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Tags'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Union'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UnloggedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.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>>}
NULL_ORDERING_SUPPORTED: Optional[bool] = True
IGNORE_NULLS_IN_FUNC = False
LOCKING_READS_SUPPORTED = False
EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = True
WRAP_DERIVED_VALUES = True
CREATE_FUNCTION_RETURN_AS = True
MATCHED_BY_SOURCE = True
SINGLE_STRING_INTERVAL = False
INTERVAL_ALLOWS_PLURAL_FORM = True
LIMIT_FETCH = 'ALL'
LIMIT_ONLY_LITERALS = False
RENAME_TABLE_WITH_DB = True
GROUPINGS_SEP = ','
INDEX_ON = 'ON'
JOIN_HINTS = True
TABLE_HINTS = True
QUERY_HINTS = True
QUERY_HINT_SEP = ', '
IS_BOOL_ALLOWED = True
DUPLICATE_KEY_UPDATE_WITH_SET = True
LIMIT_IS_TOP = False
RETURNING_END = True
EXTRACT_ALLOWS_QUOTES = True
TZ_TO_WITH_TIME_ZONE = False
NVL2_SUPPORTED = True
SELECT_KINDS: Tuple[str, ...] = ('STRUCT', 'VALUE')
VALUES_AS_TABLE = True
ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = True
UNNEST_WITH_ORDINALITY = True
AGGREGATE_FILTER_SUPPORTED = True
SEMI_ANTI_JOIN_WITH_SIDE = True
COMPUTED_COLUMN_WITH_TYPE = True
SUPPORTS_TABLE_COPY = True
TABLESAMPLE_REQUIRES_PARENS = True
TABLESAMPLE_SIZE_IS_ROWS = True
TABLESAMPLE_KEYWORDS = 'TABLESAMPLE'
TABLESAMPLE_WITH_METHOD = True
TABLESAMPLE_SEED_KEYWORD = 'SEED'
COLLATE_IS_FUNC = False
DATA_TYPE_SPECIFIERS_ALLOWED = False
ENSURE_BOOLS = False
CTE_RECURSIVE_KEYWORD_REQUIRED = True
SUPPORTS_SINGLE_ARG_CONCAT = True
LAST_DAY_SUPPORTS_DATE_PART = True
SUPPORTS_TABLE_ALIAS_COLUMNS = True
UNPIVOT_ALIASES_ARE_IDENTIFIERS = True
JSON_KEY_VALUE_PAIR_SEP = ':'
INSERT_OVERWRITE = ' OVERWRITE TABLE'
SUPPORTS_SELECT_INTO = False
SUPPORTS_UNLOGGED_TABLES = False
SUPPORTS_CREATE_TABLE_LIKE = True
LIKE_PROPERTY_INSIDE_SCHEMA = False
MULTI_ARG_DISTINCT = True
JSON_TYPE_REQUIRED_FOR_EXTRACTION = False
JSON_PATH_BRACKETED_KEY_SUPPORTED = True
JSON_PATH_SINGLE_QUOTE_ESCAPE = False
SUPPORTED_JSON_PATH_PARTS = {<class 'sqlglot.expressions.JSONPathKey'>, <class 'sqlglot.expressions.JSONPathWildcard'>, <class 'sqlglot.expressions.JSONPathFilter'>, <class 'sqlglot.expressions.JSONPathUnion'>, <class 'sqlglot.expressions.JSONPathSubscript'>, <class 'sqlglot.expressions.JSONPathSelector'>, <class 'sqlglot.expressions.JSONPathSlice'>, <class 'sqlglot.expressions.JSONPathScript'>, <class 'sqlglot.expressions.JSONPathRoot'>, <class 'sqlglot.expressions.JSONPathRecursive'>}
CAN_IMPLEMENT_ARRAY_ANY = False
SUPPORTS_TO_NUMBER = True
SET_OP_MODIFIERS = True
COPY_PARAMS_ARE_WRAPPED = True
COPY_PARAMS_EQ_REQUIRED = False
COPY_HAS_INTO_KEYWORD = True
TRY_SUPPORTED = True
SUPPORTS_UESCAPE = True
STAR_EXCEPT = 'EXCEPT'
HEX_FUNC = 'HEX'
WITH_PROPERTIES_PREFIX = 'WITH'
QUOTE_JSON_PATH = True
PAD_FILL_PATTERN_IS_REQUIRED = False
SUPPORTS_EXPLODING_PROJECTIONS = True
ARRAY_CONCAT_IS_VAR_LEN = True
SUPPORTS_CONVERT_TIMEZONE = False
SUPPORTS_MEDIAN = True
SUPPORTS_UNIX_SECONDS = False
PARSE_JSON_NAME: Optional[str] = 'PARSE_JSON'
ARRAY_SIZE_NAME: str = 'ARRAY_LENGTH'
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.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.StreamingTableProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StrictProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Tags'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.TemporaryProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.ToTableProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TransientProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.TransformModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.MergeTreeTTL'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.UnloggedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.ViewAttributeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.VolatileProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.WithDataProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.WithProcedureOptions'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.WithSchemaBindingProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.WithSystemVersioningProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>}
RESERVED_KEYWORDS: Set[str] = set()
WITH_SEPARATED_COMMENTS: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Command'>, <class 'sqlglot.expressions.Create'>, <class 'sqlglot.expressions.Describe'>, <class 'sqlglot.expressions.Delete'>, <class 'sqlglot.expressions.Drop'>, <class 'sqlglot.expressions.From'>, <class 'sqlglot.expressions.Insert'>, <class 'sqlglot.expressions.Join'>, <class 'sqlglot.expressions.MultitableInserts'>, <class 'sqlglot.expressions.Select'>, <class 'sqlglot.expressions.SetOperation'>, <class 'sqlglot.expressions.Update'>, <class 'sqlglot.expressions.Where'>, <class 'sqlglot.expressions.With'>)
EXCLUDE_COMMENTS: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Binary'>, <class 'sqlglot.expressions.SetOperation'>)
UNWRAPPED_INTERVAL_VALUES: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Column'>, <class 'sqlglot.expressions.Literal'>, <class 'sqlglot.expressions.Neg'>, <class 'sqlglot.expressions.Paren'>)
PARAMETERIZABLE_TEXT_TYPES = {<Type.CHAR: 'CHAR'>, <Type.NVARCHAR: 'NVARCHAR'>, <Type.VARCHAR: 'VARCHAR'>, <Type.NCHAR: 'NCHAR'>}
EXPRESSIONS_WITHOUT_NESTED_CTES: Set[Type[sqlglot.expressions.Expression]] = set()
SENTINEL_LINE_BREAK = '__SQLGLOT__LB__'
pretty
identify
normalize
pad
unsupported_level
max_unsupported
leading_comma
max_text_width
comments
dialect
normalize_functions
unsupported_messages: List[str]
def generate( self, expression: sqlglot.expressions.Expression, copy: bool = True) -> str: View Source

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

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

Apply generic preprocessing transformations to a given expression.

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

    779    def unsupported(self, message: str) -> None:
    780        if self.unsupported_level == ErrorLevel.IMMEDIATE:
    781            raise UnsupportedError(message)
    782        self.unsupported_messages.append(message)

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

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

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

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

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

    790    def pad_comment(self, comment: str) -> str:
    791        comment = " " + comment if comment[0].strip() else comment
    792        comment = comment + " " if comment[-1].strip() else comment
    793        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

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

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

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

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

    841    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
    842        original = self.identify
    843        self.identify = False
    844        result = func(*args, **kwargs)
    845        self.identify = original
    846        return result

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

    848    def normalize_func(self, name: str) -> str:
    849        if self.normalize_functions == "upper" or self.normalize_functions is True:
    850            return name.upper()
    851        if self.normalize_functions == "lower":
    852            return name.lower()
    853        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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    958    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
    959        this = self.sql(expression, "this")
    960        this = f" {this}" if this else ""
    961        position = self.sql(expression, "position")
    962        return f"{position}{this}"

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

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

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

    979    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
    980        this = self.sql(expression, "this")
    981        kind_sql = self.sql(expression, "kind").strip()
    982        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql

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

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

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

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

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

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

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

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

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

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

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

    1045    def periodforsystemtimeconstraint_sql(
    1046        self, expression: exp.PeriodForSystemTimeConstraint
    1047    ) -> str:
    1048        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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    1229    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
    1230        with_ = self.sql(expression, "with")
    1231        if with_:
    1232            sql = f"{with_}{self.sep()}{sql}"
    1233        return sql

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

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

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

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

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

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

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

    1276    def bitstring_sql(self, expression: exp.BitString) -> str:
    1277        this = self.sql(expression, "this")
    1278        if self.dialect.BIT_START:
    1279            return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}"
    1280        return f"{int(this, 2)}"

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

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

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

    1307    def bytestring_sql(self, expression: exp.ByteString) -> str:
    1308        this = self.sql(expression, "this")
    1309        if self.dialect.BYTE_START:
    1310            return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}"
    1311        return this

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

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

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

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

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

    1340    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
    1341        this = self.sql(expression, "this")
    1342        specifier = self.sql(expression, "expression")
    1343        specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else ""
    1344        return f"{this}{specifier}"

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    1571    def hex_sql(self, expression: exp.Hex) -> str:
    1572        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1573        if self.dialect.HEX_LOWERCASE:
    1574            text = self.func("LOWER", text)
    1575
    1576        return text

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

    1578    def lowerhex_sql(self, expression: exp.LowerHex) -> str:
    1579        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1580        if not self.dialect.HEX_LOWERCASE:
    1581            text = self.func("LOWER", text)
    1582        return text

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

    1584    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    1585        input_format = self.sql(expression, "input_format")
    1586        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    1587        output_format = self.sql(expression, "output_format")
    1588        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    1589        return self.sep().join((input_format, output_format))

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

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

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

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

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

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

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

    1618    def root_properties(self, properties: exp.Properties) -> str:
    1619        if properties.expressions:
    1620            return self.expressions(properties, indent=False, sep=" ")
    1621        return ""

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

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

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

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

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

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

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

    1652    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
    1653        if isinstance(expression.this, exp.Dot):
    1654            return self.sql(expression, "this")
    1655        return f"'{expression.name}'" if string_key else expression.name

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

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

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

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

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

    1685    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1686        no = "NO " if expression.args.get("no") else ""
    1687        protection = " PROTECTION" if expression.args.get("protection") else ""
    1688        return f"{no}FALLBACK{protection}"

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

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

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

    1699    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1700        freespace = self.sql(expression, "this")
    1701        percent = " PERCENT" if expression.args.get("percent") else ""
    1702        return f"FREESPACE={freespace}{percent}"

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    1874    def kill_sql(self, expression: exp.Kill) -> str:
    1875        kind = self.sql(expression, "kind")
    1876        kind = f" {kind}" if kind else ""
    1877        this = self.sql(expression, "this")
    1878        this = f" {this}" if this else ""
    1879        return f"KILL{kind}{this}"

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    1932    def historicaldata_sql(self, expression: exp.HistoricalData) -> str:
    1933        this = self.sql(expression, "this")
    1934        kind = self.sql(expression, "kind")
    1935        expr = self.sql(expression, "expression")
    1936        return f"{this} ({kind} => {expr})"

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

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

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

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

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

    1999    def tablesample_sql(
    2000        self,
    2001        expression: exp.TableSample,
    2002        tablesample_keyword: t.Optional[str] = None,
    2003    ) -> str:
    2004        method = self.sql(expression, "method")
    2005        method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    2006        numerator = self.sql(expression, "bucket_numerator")
    2007        denominator = self.sql(expression, "bucket_denominator")
    2008        field = self.sql(expression, "bucket_field")
    2009        field = f" ON {field}" if field else ""
    2010        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    2011        seed = self.sql(expression, "seed")
    2012        seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else ""
    2013
    2014        size = self.sql(expression, "size")
    2015        if size and self.TABLESAMPLE_SIZE_IS_ROWS:
    2016            size = f"{size} ROWS"
    2017
    2018        percent = self.sql(expression, "percent")
    2019        if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT:
    2020            percent = f"{percent} PERCENT"
    2021
    2022        expr = f"{bucket}{percent}{size}"
    2023        if self.TABLESAMPLE_REQUIRES_PARENS:
    2024            expr = f"({expr})"
    2025
    2026        return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}"

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

    2028    def pivot_sql(self, expression: exp.Pivot) -> str:
    2029        expressions = self.expressions(expression, flat=True)
    2030        direction = "UNPIVOT" if expression.unpivot else "PIVOT"
    2031
    2032        if expression.this:
    2033            this = self.sql(expression, "this")
    2034            if not expressions:
    2035                return f"UNPIVOT {this}"
    2036
    2037            on = f"{self.seg('ON')} {expressions}"
    2038            into = self.sql(expression, "into")
    2039            into = f"{self.seg('INTO')} {into}" if into else ""
    2040            using = self.expressions(expression, key="using", flat=True)
    2041            using = f"{self.seg('USING')} {using}" if using else ""
    2042            group = self.sql(expression, "group")
    2043            return f"{direction} {this}{on}{into}{using}{group}"
    2044
    2045        alias = self.sql(expression, "alias")
    2046        alias = f" AS {alias}" if alias else ""
    2047
    2048        field = self.sql(expression, "field")
    2049
    2050        include_nulls = expression.args.get("include_nulls")
    2051        if include_nulls is not None:
    2052            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
    2053        else:
    2054            nulls = ""
    2055
    2056        default_on_null = self.sql(expression, "default_on_null")
    2057        default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else ""
    2058        return f"{self.seg(direction)}{nulls}({expressions} FOR {field}{default_on_null}){alias}"

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

    2060    def version_sql(self, expression: exp.Version) -> str:
    2061        this = f"FOR {expression.name}"
    2062        kind = expression.text("kind")
    2063        expr = self.sql(expression, "expression")
    2064        return f"{this} {kind} {expr}"

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

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

    2069    def update_sql(self, expression: exp.Update) -> str:
    2070        this = self.sql(expression, "this")
    2071        set_sql = self.expressions(expression, flat=True)
    2072        from_sql = self.sql(expression, "from")
    2073        where_sql = self.sql(expression, "where")
    2074        returning = self.sql(expression, "returning")
    2075        order = self.sql(expression, "order")
    2076        limit = self.sql(expression, "limit")
    2077        if self.RETURNING_END:
    2078            expression_sql = f"{from_sql}{where_sql}{returning}"
    2079        else:
    2080            expression_sql = f"{returning}{from_sql}{where_sql}"
    2081        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
    2082        return self.prepend_ctes(expression, sql)

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

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

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

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

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

    2130    @unsupported_args("expressions")
    2131    def into_sql(self, expression: exp.Into) -> str:
    2132        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    2133        unlogged = " UNLOGGED" if expression.args.get("unlogged") else ""
    2134        return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"

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

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

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

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

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

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

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

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

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

    2151    def group_sql(self, expression: exp.Group) -> str:
    2152        group_by_all = expression.args.get("all")
    2153        if group_by_all is True:
    2154            modifier = " ALL"
    2155        elif group_by_all is False:
    2156            modifier = " DISTINCT"
    2157        else:
    2158            modifier = ""
    2159
    2160        group_by = self.op_expressions(f"GROUP BY{modifier}", expression)
    2161
    2162        grouping_sets = self.expressions(expression, key="grouping_sets")
    2163        cube = self.expressions(expression, key="cube")
    2164        rollup = self.expressions(expression, key="rollup")
    2165
    2166        groupings = csv(
    2167            self.seg(grouping_sets) if grouping_sets else "",
    2168            self.seg(cube) if cube else "",
    2169            self.seg(rollup) if rollup else "",
    2170            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    2171            sep=self.GROUPINGS_SEP,
    2172        )
    2173
    2174        if (
    2175            expression.expressions
    2176            and groupings
    2177            and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP")
    2178        ):
    2179            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    2180
    2181        return f"{group_by}{groupings}"

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

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

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

    2187    def connect_sql(self, expression: exp.Connect) -> str:
    2188        start = self.sql(expression, "start")
    2189        start = self.seg(f"START WITH {start}") if start else ""
    2190        nocycle = " NOCYCLE" if expression.args.get("nocycle") else ""
    2191        connect = self.sql(expression, "connect")
    2192        connect = self.seg(f"CONNECT BY{nocycle} {connect}")
    2193        return start + connect

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

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

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

    2198    def join_sql(self, expression: exp.Join) -> str:
    2199        if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"):
    2200            side = None
    2201        else:
    2202            side = expression.side
    2203
    2204        op_sql = " ".join(
    2205            op
    2206            for op in (
    2207                expression.method,
    2208                "GLOBAL" if expression.args.get("global") else None,
    2209                side,
    2210                expression.kind,
    2211                expression.hint if self.JOIN_HINTS else None,
    2212            )
    2213            if op
    2214        )
    2215        match_cond = self.sql(expression, "match_condition")
    2216        match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else ""
    2217        on_sql = self.sql(expression, "on")
    2218        using = expression.args.get("using")
    2219
    2220        if not on_sql and using:
    2221            on_sql = csv(*(self.sql(column) for column in using))
    2222
    2223        this = expression.this
    2224        this_sql = self.sql(this)
    2225
    2226        exprs = self.expressions(expression)
    2227        if exprs:
    2228            this_sql = f"{this_sql},{self.seg(exprs)}"
    2229
    2230        if on_sql:
    2231            on_sql = self.indent(on_sql, skip_first=True)
    2232            space = self.seg(" " * self.pad) if self.pretty else " "
    2233            if using:
    2234                on_sql = f"{space}USING ({on_sql})"
    2235            else:
    2236                on_sql = f"{space}ON {on_sql}"
    2237        elif not op_sql:
    2238            if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None:
    2239                return f" {this_sql}"
    2240
    2241            return f", {this_sql}"
    2242
    2243        if op_sql != "STRAIGHT_JOIN":
    2244            op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    2245
    2246        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

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

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

    2253    def lateral_op(self, expression: exp.Lateral) -> str:
    2254        cross_apply = expression.args.get("cross_apply")
    2255
    2256        # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/
    2257        if cross_apply is True:
    2258            op = "INNER JOIN "
    2259        elif cross_apply is False:
    2260            op = "LEFT JOIN "
    2261        else:
    2262            op = ""
    2263
    2264        return f"{op}LATERAL"

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

    2266    def lateral_sql(self, expression: exp.Lateral) -> str:
    2267        this = self.sql(expression, "this")
    2268
    2269        if expression.args.get("view"):
    2270            alias = expression.args["alias"]
    2271            columns = self.expressions(alias, key="columns", flat=True)
    2272            table = f" {alias.name}" if alias.name else ""
    2273            columns = f" AS {columns}" if columns else ""
    2274            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    2275            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    2276
    2277        alias = self.sql(expression, "alias")
    2278        alias = f" AS {alias}" if alias else ""
    2279        return f"{self.lateral_op(expression)} {this}{alias}"

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

    2281    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    2282        this = self.sql(expression, "this")
    2283
    2284        args = [
    2285            self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e
    2286            for e in (expression.args.get(k) for k in ("offset", "expression"))
    2287            if e
    2288        ]
    2289
    2290        args_sql = ", ".join(self.sql(e) for e in args)
    2291        args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql
    2292        expressions = self.expressions(expression, flat=True)
    2293        limit_options = self.sql(expression, "limit_options")
    2294        expressions = f" BY {expressions}" if expressions else ""
    2295
    2296        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

    2298    def offset_sql(self, expression: exp.Offset) -> str:
    2299        this = self.sql(expression, "this")
    2300        value = expression.expression
    2301        value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value
    2302        expressions = self.expressions(expression, flat=True)
    2303        expressions = f" BY {expressions}" if expressions else ""
    2304        return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"

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

    2306    def setitem_sql(self, expression: exp.SetItem) -> str:
    2307        kind = self.sql(expression, "kind")
    2308        kind = f"{kind} " if kind else ""
    2309        this = self.sql(expression, "this")
    2310        expressions = self.expressions(expression)
    2311        collate = self.sql(expression, "collate")
    2312        collate = f" COLLATE {collate}" if collate else ""
    2313        global_ = "GLOBAL " if expression.args.get("global") else ""
    2314        return f"{global_}{kind}{this}{expressions}{collate}"

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

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

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

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

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

    2324    def lock_sql(self, expression: exp.Lock) -> str:
    2325        if not self.LOCKING_READS_SUPPORTED:
    2326            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    2327            return ""
    2328
    2329        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    2330        expressions = self.expressions(expression, flat=True)
    2331        expressions = f" OF {expressions}" if expressions else ""
    2332        wait = expression.args.get("wait")
    2333
    2334        if wait is not None:
    2335            if isinstance(wait, exp.Literal):
    2336                wait = f" WAIT {self.sql(wait)}"
    2337            else:
    2338                wait = " NOWAIT" if wait else " SKIP LOCKED"
    2339
    2340        return f"{lock_type}{expressions}{wait or ''}"

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

    2342    def literal_sql(self, expression: exp.Literal) -> str:
    2343        text = expression.this or ""
    2344        if expression.is_string:
    2345            text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}"
    2346        return text

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

    2348    def escape_str(self, text: str, escape_backslash: bool = True) -> str:
    2349        if self.dialect.ESCAPED_SEQUENCES:
    2350            to_escaped = self.dialect.ESCAPED_SEQUENCES
    2351            text = "".join(
    2352                to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text
    2353            )
    2354
    2355        return self._replace_line_breaks(text).replace(
    2356            self.dialect.QUOTE_END, self._escaped_quote_end
    2357        )

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

    2359    def loaddata_sql(self, expression: exp.LoadData) -> str:
    2360        local = " LOCAL" if expression.args.get("local") else ""
    2361        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    2362        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    2363        this = f" INTO TABLE {self.sql(expression, 'this')}"
    2364        partition = self.sql(expression, "partition")
    2365        partition = f" {partition}" if partition else ""
    2366        input_format = self.sql(expression, "input_format")
    2367        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    2368        serde = self.sql(expression, "serde")
    2369        serde = f" SERDE {serde}" if serde else ""
    2370        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"

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

    2372    def null_sql(self, *_) -> str:
    2373        return "NULL"

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

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

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

    2378    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    2379        this = self.sql(expression, "this")
    2380        this = f"{this} " if this else this
    2381        siblings = "SIBLINGS " if expression.args.get("siblings") else ""
    2382        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

    2384    def withfill_sql(self, expression: exp.WithFill) -> str:
    2385        from_sql = self.sql(expression, "from")
    2386        from_sql = f" FROM {from_sql}" if from_sql else ""
    2387        to_sql = self.sql(expression, "to")
    2388        to_sql = f" TO {to_sql}" if to_sql else ""
    2389        step_sql = self.sql(expression, "step")
    2390        step_sql = f" STEP {step_sql}" if step_sql else ""
    2391        interpolated_values = [
    2392            f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}"
    2393            if isinstance(e, exp.Alias)
    2394            else self.sql(e, "this")
    2395            for e in expression.args.get("interpolate") or []
    2396        ]
    2397        interpolate = (
    2398            f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else ""
    2399        )
    2400        return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}"

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

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

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

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

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

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

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

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

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

    2474    def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str:
    2475        window_frame = self.sql(expression, "window_frame")
    2476        window_frame = f"{window_frame} " if window_frame else ""
    2477
    2478        this = self.sql(expression, "this")
    2479
    2480        return f"{window_frame}{this}"

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

    2482    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    2483        partition = self.partition_by_sql(expression)
    2484        order = self.sql(expression, "order")
    2485        measures = self.expressions(expression, key="measures")
    2486        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    2487        rows = self.sql(expression, "rows")
    2488        rows = self.seg(rows) if rows else ""
    2489        after = self.sql(expression, "after")
    2490        after = self.seg(after) if after else ""
    2491        pattern = self.sql(expression, "pattern")
    2492        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    2493        definition_sqls = [
    2494            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    2495            for definition in expression.args.get("define", [])
    2496        ]
    2497        definitions = self.expressions(sqls=definition_sqls)
    2498        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    2499        body = "".join(
    2500            (
    2501                partition,
    2502                order,
    2503                measures,
    2504                rows,
    2505                after,
    2506                pattern,
    2507                define,
    2508            )
    2509        )
    2510        alias = self.sql(expression, "alias")
    2511        alias = f" {alias}" if alias else ""
    2512        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"

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

    2514    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    2515        limit = expression.args.get("limit")
    2516
    2517        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    2518            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
    2519        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    2520            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
    2521
    2522        return csv(
    2523            *sqls,
    2524            *[self.sql(join) for join in expression.args.get("joins") or []],
    2525            self.sql(expression, "match"),
    2526            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    2527            self.sql(expression, "prewhere"),
    2528            self.sql(expression, "where"),
    2529            self.sql(expression, "connect"),
    2530            self.sql(expression, "group"),
    2531            self.sql(expression, "having"),
    2532            *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()],
    2533            self.sql(expression, "order"),
    2534            *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit),
    2535            *self.after_limit_modifiers(expression),
    2536            self.options_modifier(expression),
    2537            sep="",
    2538        )

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

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

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

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

    2547    def offset_limit_modifiers(
    2548        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    2549    ) -> t.List[str]:
    2550        return [
    2551            self.sql(expression, "offset") if fetch else self.sql(limit),
    2552            self.sql(limit) if fetch else self.sql(expression, "offset"),
    2553        ]

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

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

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

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

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

    2632    def schema_sql(self, expression: exp.Schema) -> str:
    2633        this = self.sql(expression, "this")
    2634        sql = self.schema_columns_sql(expression)
    2635        return f"{this} {sql}" if this and sql else this or sql

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

    2637    def schema_columns_sql(self, expression: exp.Schema) -> str:
    2638        if expression.expressions:
    2639            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
    2640        return ""

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

    2642    def star_sql(self, expression: exp.Star) -> str:
    2643        except_ = self.expressions(expression, key="except", flat=True)
    2644        except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else ""
    2645        replace = self.expressions(expression, key="replace", flat=True)
    2646        replace = f"{self.seg('REPLACE')} ({replace})" if replace else ""
    2647        rename = self.expressions(expression, key="rename", flat=True)
    2648        rename = f"{self.seg('RENAME')} ({rename})" if rename else ""
    2649        return f"*{except_}{replace}{rename}"

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

    2651    def parameter_sql(self, expression: exp.Parameter) -> str:
    2652        this = self.sql(expression, "this")
    2653        return f"{self.PARAMETER_TOKEN}{this}"

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

    2655    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    2656        this = self.sql(expression, "this")
    2657        kind = expression.text("kind")
    2658        if kind:
    2659            kind = f"{kind}."
    2660        return f"@@{kind}{this}"

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

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

    2665    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    2666        alias = self.sql(expression, "alias")
    2667        alias = f"{sep}{alias}" if alias else ""
    2668        sample = self.sql(expression, "sample")
    2669        if self.dialect.ALIAS_POST_TABLESAMPLE and sample:
    2670            alias = f"{sample}{alias}"
    2671
    2672            # Set to None so it's not generated again by self.query_modifiers()
    2673            expression.set("sample", None)
    2674
    2675        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    2676        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    2677        return self.prepend_ctes(expression, sql)

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

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

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

    2683    def unnest_sql(self, expression: exp.Unnest) -> str:
    2684        args = self.expressions(expression, flat=True)
    2685
    2686        alias = expression.args.get("alias")
    2687        offset = expression.args.get("offset")
    2688
    2689        if self.UNNEST_WITH_ORDINALITY:
    2690            if alias and isinstance(offset, exp.Expression):
    2691                alias.append("columns", offset)
    2692
    2693        if alias and self.dialect.UNNEST_COLUMN_ONLY:
    2694            columns = alias.columns
    2695            alias = self.sql(columns[0]) if columns else ""
    2696        else:
    2697            alias = self.sql(alias)
    2698
    2699        alias = f" AS {alias}" if alias else alias
    2700        if self.UNNEST_WITH_ORDINALITY:
    2701            suffix = f" WITH ORDINALITY{alias}" if offset else alias
    2702        else:
    2703            if isinstance(offset, exp.Expression):
    2704                suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}"
    2705            elif offset:
    2706                suffix = f"{alias} WITH OFFSET"
    2707            else:
    2708                suffix = alias
    2709
    2710        return f"UNNEST({args}){suffix}"

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

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

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

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

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

    2719    def window_sql(self, expression: exp.Window) -> str:
    2720        this = self.sql(expression, "this")
    2721        partition = self.partition_by_sql(expression)
    2722        order = expression.args.get("order")
    2723        order = self.order_sql(order, flat=True) if order else ""
    2724        spec = self.sql(expression, "spec")
    2725        alias = self.sql(expression, "alias")
    2726        over = self.sql(expression, "over") or "OVER"
    2727
    2728        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    2729
    2730        first = expression.args.get("first")
    2731        if first is None:
    2732            first = ""
    2733        else:
    2734            first = "FIRST" if first else "LAST"
    2735
    2736        if not partition and not order and not spec and alias:
    2737            return f"{this} {alias}"
    2738
    2739        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
    2740        return f"{this} ({args})"

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

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

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

    2746    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    2747        kind = self.sql(expression, "kind")
    2748        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    2749        end = (
    2750            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    2751            or "CURRENT ROW"
    2752        )
    2753        return f"{kind} BETWEEN {start} AND {end}"

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

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

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

    2760    def between_sql(self, expression: exp.Between) -> str:
    2761        this = self.sql(expression, "this")
    2762        low = self.sql(expression, "low")
    2763        high = self.sql(expression, "high")
    2764        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

    2766    def bracket_offset_expressions(
    2767        self, expression: exp.Bracket, index_offset: t.Optional[int] = None
    2768    ) -> t.List[exp.Expression]:
    2769        return apply_index_offset(
    2770            expression.this,
    2771            expression.expressions,
    2772            (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0),
    2773        )

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

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

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

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

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

    2783    def any_sql(self, expression: exp.Any) -> str:
    2784        this = self.sql(expression, "this")
    2785        if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)):
    2786            if isinstance(expression.this, exp.UNWRAPPED_QUERIES):
    2787                this = self.wrap(this)
    2788            return f"ANY{this}"
    2789        return f"ANY {this}"

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

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

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

    2794    def case_sql(self, expression: exp.Case) -> str:
    2795        this = self.sql(expression, "this")
    2796        statements = [f"CASE {this}" if this else "CASE"]
    2797
    2798        for e in expression.args["ifs"]:
    2799            statements.append(f"WHEN {self.sql(e, 'this')}")
    2800            statements.append(f"THEN {self.sql(e, 'true')}")
    2801
    2802        default = self.sql(expression, "default")
    2803
    2804        if default:
    2805            statements.append(f"ELSE {default}")
    2806
    2807        statements.append("END")
    2808
    2809        if self.pretty and self.too_wide(statements):
    2810            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    2811
    2812        return " ".join(statements)

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

    2814    def constraint_sql(self, expression: exp.Constraint) -> str:
    2815        this = self.sql(expression, "this")
    2816        expressions = self.expressions(expression, flat=True)
    2817        return f"CONSTRAINT {this} {expressions}"

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

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

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

    2824    def extract_sql(self, expression: exp.Extract) -> str:
    2825        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
    2826        expression_sql = self.sql(expression, "expression")
    2827        return f"EXTRACT({this} FROM {expression_sql})"

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

    2829    def trim_sql(self, expression: exp.Trim) -> str:
    2830        trim_type = self.sql(expression, "position")
    2831
    2832        if trim_type == "LEADING":
    2833            func_name = "LTRIM"
    2834        elif trim_type == "TRAILING":
    2835            func_name = "RTRIM"
    2836        else:
    2837            func_name = "TRIM"
    2838
    2839        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

    2841    def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]:
    2842        args = expression.expressions
    2843        if isinstance(expression, exp.ConcatWs):
    2844            args = args[1:]  # Skip the delimiter
    2845
    2846        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    2847            args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args]
    2848
    2849        if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"):
    2850            args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args]
    2851
    2852        return args

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

    2854    def concat_sql(self, expression: exp.Concat) -> str:
    2855        expressions = self.convert_concat_args(expression)
    2856
    2857        # Some dialects don't allow a single-argument CONCAT call
    2858        if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1:
    2859            return self.sql(expressions[0])
    2860
    2861        return self.func("CONCAT", *expressions)

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

    2863    def concatws_sql(self, expression: exp.ConcatWs) -> str:
    2864        return self.func(
    2865            "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression)
    2866        )

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

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

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

    2872    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    2873        expressions = self.expressions(expression, flat=True)
    2874        expressions = f" ({expressions})" if expressions else ""
    2875        reference = self.sql(expression, "reference")
    2876        reference = f" {reference}" if reference else ""
    2877        delete = self.sql(expression, "delete")
    2878        delete = f" ON DELETE {delete}" if delete else ""
    2879        update = self.sql(expression, "update")
    2880        update = f" ON UPDATE {update}" if update else ""
    2881        return f"FOREIGN KEY{expressions}{reference}{delete}{update}"

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

    2883    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    2884        expressions = self.expressions(expression, flat=True)
    2885        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2886        options = f" {options}" if options else ""
    2887        return f"PRIMARY KEY ({expressions}){options}"

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

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

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

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

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

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

    2900    def jsonpath_sql(self, expression: exp.JSONPath) -> str:
    2901        path = self.expressions(expression, sep="", flat=True).lstrip(".")
    2902
    2903        if expression.args.get("escape"):
    2904            path = self.escape_str(path)
    2905
    2906        if self.QUOTE_JSON_PATH:
    2907            path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"
    2908
    2909        return path

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

    2911    def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str:
    2912        if isinstance(expression, exp.JSONPathPart):
    2913            transform = self.TRANSFORMS.get(expression.__class__)
    2914            if not callable(transform):
    2915                self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}")
    2916                return ""
    2917
    2918            return transform(self, expression)
    2919
    2920        if isinstance(expression, int):
    2921            return str(expression)
    2922
    2923        if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE:
    2924            escaped = expression.replace("'", "\\'")
    2925            escaped = f"\\'{expression}\\'"
    2926        else:
    2927            escaped = expression.replace('"', '\\"')
    2928            escaped = f'"{escaped}"'
    2929
    2930        return escaped

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

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

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

    2935    def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str:
    2936        null_handling = expression.args.get("null_handling")
    2937        null_handling = f" {null_handling}" if null_handling else ""
    2938
    2939        unique_keys = expression.args.get("unique_keys")
    2940        if unique_keys is not None:
    2941            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    2942        else:
    2943            unique_keys = ""
    2944
    2945        return_type = self.sql(expression, "return_type")
    2946        return_type = f" RETURNING {return_type}" if return_type else ""
    2947        encoding = self.sql(expression, "encoding")
    2948        encoding = f" ENCODING {encoding}" if encoding else ""
    2949
    2950        return self.func(
    2951            "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG",
    2952            *expression.expressions,
    2953            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
    2954        )

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

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

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

    2959    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
    2960        null_handling = expression.args.get("null_handling")
    2961        null_handling = f" {null_handling}" if null_handling else ""
    2962        return_type = self.sql(expression, "return_type")
    2963        return_type = f" RETURNING {return_type}" if return_type else ""
    2964        strict = " STRICT" if expression.args.get("strict") else ""
    2965        return self.func(
    2966            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
    2967        )

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

    2969    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
    2970        this = self.sql(expression, "this")
    2971        order = self.sql(expression, "order")
    2972        null_handling = expression.args.get("null_handling")
    2973        null_handling = f" {null_handling}" if null_handling else ""
    2974        return_type = self.sql(expression, "return_type")
    2975        return_type = f" RETURNING {return_type}" if return_type else ""
    2976        strict = " STRICT" if expression.args.get("strict") else ""
    2977        return self.func(
    2978            "JSON_ARRAYAGG",
    2979            this,
    2980            suffix=f"{order}{null_handling}{return_type}{strict})",
    2981        )

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

    2983    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
    2984        path = self.sql(expression, "path")
    2985        path = f" PATH {path}" if path else ""
    2986        nested_schema = self.sql(expression, "nested_schema")
    2987
    2988        if nested_schema:
    2989            return f"NESTED{path} {nested_schema}"
    2990
    2991        this = self.sql(expression, "this")
    2992        kind = self.sql(expression, "kind")
    2993        kind = f" {kind}" if kind else ""
    2994        return f"{this}{kind}{path}"

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

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

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

    2999    def jsontable_sql(self, expression: exp.JSONTable) -> str:
    3000        this = self.sql(expression, "this")
    3001        path = self.sql(expression, "path")
    3002        path = f", {path}" if path else ""
    3003        error_handling = expression.args.get("error_handling")
    3004        error_handling = f" {error_handling}" if error_handling else ""
    3005        empty_handling = expression.args.get("empty_handling")
    3006        empty_handling = f" {empty_handling}" if empty_handling else ""
    3007        schema = self.sql(expression, "schema")
    3008        return self.func(
    3009            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
    3010        )

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

    3012    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    3013        this = self.sql(expression, "this")
    3014        kind = self.sql(expression, "kind")
    3015        path = self.sql(expression, "path")
    3016        path = f" {path}" if path else ""
    3017        as_json = " AS JSON" if expression.args.get("as_json") else ""
    3018        return f"{this} {kind}{path}{as_json}"

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

    3020    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    3021        this = self.sql(expression, "this")
    3022        path = self.sql(expression, "path")
    3023        path = f", {path}" if path else ""
    3024        expressions = self.expressions(expression)
    3025        with_ = (
    3026            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    3027            if expressions
    3028            else ""
    3029        )
    3030        return f"OPENJSON({this}{path}){with_}"

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

    3032    def in_sql(self, expression: exp.In) -> str:
    3033        query = expression.args.get("query")
    3034        unnest = expression.args.get("unnest")
    3035        field = expression.args.get("field")
    3036        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    3037
    3038        if query:
    3039            in_sql = self.sql(query)
    3040        elif unnest:
    3041            in_sql = self.in_unnest_op(unnest)
    3042        elif field:
    3043            in_sql = self.sql(field)
    3044        else:
    3045            in_sql = f"({self.expressions(expression, flat=True)})"
    3046
    3047        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"

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

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

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

    3052    def interval_sql(self, expression: exp.Interval) -> str:
    3053        unit = self.sql(expression, "unit")
    3054        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    3055            unit = self.TIME_PART_SINGULARS.get(unit, unit)
    3056        unit = f" {unit}" if unit else ""
    3057
    3058        if self.SINGLE_STRING_INTERVAL:
    3059            this = expression.this.name if expression.this else ""
    3060            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    3061
    3062        this = self.sql(expression, "this")
    3063        if this:
    3064            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    3065            this = f" {this}" if unwrapped else f" ({this})"
    3066
    3067        return f"INTERVAL{this}{unit}"

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

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

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

    3072    def reference_sql(self, expression: exp.Reference) -> str:
    3073        this = self.sql(expression, "this")
    3074        expressions = self.expressions(expression, flat=True)
    3075        expressions = f"({expressions})" if expressions else ""
    3076        options = self.expressions(expression, key="options", flat=True, sep=" ")
    3077        options = f" {options}" if options else ""
    3078        return f"REFERENCES {this}{expressions}{options}"

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

    3080    def anonymous_sql(self, expression: exp.Anonymous) -> str:
    3081        # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive
    3082        parent = expression.parent
    3083        is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression
    3084        return self.func(
    3085            self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified
    3086        )

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

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

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

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

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

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

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

    3101    def alias_sql(self, expression: exp.Alias) -> str:
    3102        alias = self.sql(expression, "alias")
    3103        alias = f" AS {alias}" if alias else ""
    3104        return f"{self.sql(expression, 'this')}{alias}"

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

    3106    def pivotalias_sql(self, expression: exp.PivotAlias) -> str:
    3107        alias = expression.args["alias"]
    3108
    3109        identifier_alias = isinstance(alias, exp.Identifier)
    3110        literal_alias = isinstance(alias, exp.Literal)
    3111
    3112        if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    3113            alias.replace(exp.Literal.string(alias.output_name))
    3114        elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    3115            alias.replace(exp.to_identifier(alias.output_name))
    3116
    3117        return self.alias_sql(expression)

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

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

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

    3122    def atindex_sql(self, expression: exp.AtTimeZone) -> str:
    3123        this = self.sql(expression, "this")
    3124        index = self.sql(expression, "expression")
    3125        return f"{this} AT {index}"

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

    3127    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    3128        this = self.sql(expression, "this")
    3129        zone = self.sql(expression, "zone")
    3130        return f"{this} AT TIME ZONE {zone}"

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

    3132    def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str:
    3133        this = self.sql(expression, "this")
    3134        zone = self.sql(expression, "zone")
    3135        return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'"

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

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

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

    3140    def and_sql(
    3141        self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None
    3142    ) -> str:
    3143        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

    3145    def or_sql(
    3146        self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None
    3147    ) -> str:
    3148        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

    3150    def xor_sql(
    3151        self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None
    3152    ) -> str:
    3153        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

    3155    def connector_sql(
    3156        self,
    3157        expression: exp.Connector,
    3158        op: str,
    3159        stack: t.Optional[t.List[str | exp.Expression]] = None,
    3160    ) -> str:
    3161        if stack is not None:
    3162            if expression.expressions:
    3163                stack.append(self.expressions(expression, sep=f" {op} "))
    3164            else:
    3165                stack.append(expression.right)
    3166                if expression.comments and self.comments:
    3167                    for comment in expression.comments:
    3168                        if comment:
    3169                            op += f" /*{self.pad_comment(comment)}*/"
    3170                stack.extend((op, expression.left))
    3171            return op
    3172
    3173        stack = [expression]
    3174        sqls: t.List[str] = []
    3175        ops = set()
    3176
    3177        while stack:
    3178            node = stack.pop()
    3179            if isinstance(node, exp.Connector):
    3180                ops.add(getattr(self, f"{node.key}_sql")(node, stack))
    3181            else:
    3182                sql = self.sql(node)
    3183                if sqls and sqls[-1] in ops:
    3184                    sqls[-1] += f" {sql}"
    3185                else:
    3186                    sqls.append(sql)
    3187
    3188        sep = "\n" if self.pretty and self.too_wide(sqls) else " "
    3189        return sep.join(sqls)

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

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

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

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

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

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

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

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

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

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

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

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

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

    3209    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    3210        format_sql = self.sql(expression, "format")
    3211        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    3212        to_sql = self.sql(expression, "to")
    3213        to_sql = f" {to_sql}" if to_sql else ""
    3214        action = self.sql(expression, "action")
    3215        action = f" {action}" if action else ""
    3216        default = self.sql(expression, "default")
    3217        default = f" DEFAULT {default} ON CONVERSION ERROR" if default else ""
    3218        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

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

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

    3224    def collate_sql(self, expression: exp.Collate) -> str:
    3225        if self.COLLATE_IS_FUNC:
    3226            return self.function_fallback_sql(expression)
    3227        return self.binary(expression, "COLLATE")

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

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

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

    3232    def comment_sql(self, expression: exp.Comment) -> str:
    3233        this = self.sql(expression, "this")
    3234        kind = expression.args["kind"]
    3235        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    3236        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    3237        expression_sql = self.sql(expression, "expression")
    3238        return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"

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

    3240    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    3241        this = self.sql(expression, "this")
    3242        delete = " DELETE" if expression.args.get("delete") else ""
    3243        recompress = self.sql(expression, "recompress")
    3244        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    3245        to_disk = self.sql(expression, "to_disk")
    3246        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    3247        to_volume = self.sql(expression, "to_volume")
    3248        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    3249        return f"{this}{delete}{recompress}{to_disk}{to_volume}"

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

    3251    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    3252        where = self.sql(expression, "where")
    3253        group = self.sql(expression, "group")
    3254        aggregates = self.expressions(expression, key="aggregates")
    3255        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    3256
    3257        if not (where or group or aggregates) and len(expression.expressions) == 1:
    3258            return f"TTL {self.expressions(expression, flat=True)}"
    3259
    3260        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"

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

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

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

    3265    def commit_sql(self, expression: exp.Commit) -> str:
    3266        chain = expression.args.get("chain")
    3267        if chain is not None:
    3268            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    3269
    3270        return f"COMMIT{chain or ''}"

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

    3272    def rollback_sql(self, expression: exp.Rollback) -> str:
    3273        savepoint = expression.args.get("savepoint")
    3274        savepoint = f" TO {savepoint}" if savepoint else ""
    3275        return f"ROLLBACK{savepoint}"

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

    3277    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    3278        this = self.sql(expression, "this")
    3279
    3280        dtype = self.sql(expression, "dtype")
    3281        if dtype:
    3282            collate = self.sql(expression, "collate")
    3283            collate = f" COLLATE {collate}" if collate else ""
    3284            using = self.sql(expression, "using")
    3285            using = f" USING {using}" if using else ""
    3286            return f"ALTER COLUMN {this} {self.ALTER_SET_TYPE} {dtype}{collate}{using}"
    3287
    3288        default = self.sql(expression, "default")
    3289        if default:
    3290            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    3291
    3292        comment = self.sql(expression, "comment")
    3293        if comment:
    3294            return f"ALTER COLUMN {this} COMMENT {comment}"
    3295
    3296        visible = expression.args.get("visible")
    3297        if visible:
    3298            return f"ALTER COLUMN {this} SET {visible}"
    3299
    3300        allow_null = expression.args.get("allow_null")
    3301        drop = expression.args.get("drop")
    3302
    3303        if not drop and not allow_null:
    3304            self.unsupported("Unsupported ALTER COLUMN syntax")
    3305
    3306        if allow_null is not None:
    3307            keyword = "DROP" if drop else "SET"
    3308            return f"ALTER COLUMN {this} {keyword} NOT NULL"
    3309
    3310        return f"ALTER COLUMN {this} DROP DEFAULT"

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

    3312    def alterindex_sql(self, expression: exp.AlterIndex) -> str:
    3313        this = self.sql(expression, "this")
    3314
    3315        visible = expression.args.get("visible")
    3316        visible_sql = "VISIBLE" if visible else "INVISIBLE"
    3317
    3318        return f"ALTER INDEX {this} {visible_sql}"

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

    3320    def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str:
    3321        this = self.sql(expression, "this")
    3322        if not isinstance(expression.this, exp.Var):
    3323            this = f"KEY DISTKEY {this}"
    3324        return f"ALTER DISTSTYLE {this}"

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

    3326    def altersortkey_sql(self, expression: exp.AlterSortKey) -> str:
    3327        compound = " COMPOUND" if expression.args.get("compound") else ""
    3328        this = self.sql(expression, "this")
    3329        expressions = self.expressions(expression, flat=True)
    3330        expressions = f"({expressions})" if expressions else ""
    3331        return f"ALTER{compound} SORTKEY {this or expressions}"

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

    3333    def alterrename_sql(self, expression: exp.AlterRename) -> str:
    3334        if not self.RENAME_TABLE_WITH_DB:
    3335            # Remove db from tables
    3336            expression = expression.transform(
    3337                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    3338            ).assert_is(exp.AlterRename)
    3339        this = self.sql(expression, "this")
    3340        return f"RENAME TO {this}"

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

    3342    def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
    3343        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3344        old_column = self.sql(expression, "this")
    3345        new_column = self.sql(expression, "to")
    3346        return f"RENAME COLUMN{exists} {old_column} TO {new_column}"

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

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

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

    3352    def alter_sql(self, expression: exp.Alter) -> str:
    3353        actions = expression.args["actions"]
    3354
    3355        if isinstance(actions[0], exp.ColumnDef):
    3356            actions = self.add_column_sql(expression)
    3357        elif isinstance(actions[0], exp.Schema):
    3358            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    3359        elif isinstance(actions[0], exp.Delete):
    3360            actions = self.expressions(expression, key="actions", flat=True)
    3361        elif isinstance(actions[0], exp.Query):
    3362            actions = "AS " + self.expressions(expression, key="actions")
    3363        else:
    3364            actions = self.expressions(expression, key="actions", flat=True)
    3365
    3366        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3367        on_cluster = self.sql(expression, "cluster")
    3368        on_cluster = f" {on_cluster}" if on_cluster else ""
    3369        only = " ONLY" if expression.args.get("only") else ""
    3370        options = self.expressions(expression, key="options")
    3371        options = f", {options}" if options else ""
    3372        kind = self.sql(expression, "kind")
    3373        not_valid = " NOT VALID" if expression.args.get("not_valid") else ""
    3374
    3375        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

    3377    def add_column_sql(self, expression: exp.Alter) -> str:
    3378        if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD:
    3379            return self.expressions(
    3380                expression,
    3381                key="actions",
    3382                prefix="ADD COLUMN ",
    3383                skip_first=True,
    3384            )
    3385        return f"ADD {self.expressions(expression, key='actions', flat=True)}"

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

    3387    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    3388        expressions = self.expressions(expression)
    3389        exists = " IF EXISTS " if expression.args.get("exists") else " "
    3390        return f"DROP{exists}{expressions}"

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

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

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

    3395    def distinct_sql(self, expression: exp.Distinct) -> str:
    3396        this = self.expressions(expression, flat=True)
    3397
    3398        if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1:
    3399            case = exp.case()
    3400            for arg in expression.expressions:
    3401                case = case.when(arg.is_(exp.null()), exp.null())
    3402            this = self.sql(case.else_(f"({this})"))
    3403
    3404        this = f" {this}" if this else ""
    3405
    3406        on = self.sql(expression, "on")
    3407        on = f" ON {on}" if on else ""
    3408        return f"DISTINCT{this}{on}"

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

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

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

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

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

    3416    def havingmax_sql(self, expression: exp.HavingMax) -> str:
    3417        this_sql = self.sql(expression, "this")
    3418        expression_sql = self.sql(expression, "expression")
    3419        kind = "MAX" if expression.args.get("max") else "MIN"
    3420        return f"{this_sql} HAVING {kind} {expression_sql}"

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

    3422    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    3423        return self.sql(
    3424            exp.Cast(
    3425                this=exp.Div(this=expression.this, expression=expression.expression),
    3426                to=exp.DataType(this=exp.DataType.Type.INT),
    3427            )
    3428        )

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

    3430    def dpipe_sql(self, expression: exp.DPipe) -> str:
    3431        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    3432            return self.func(
    3433                "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten())
    3434            )
    3435        return self.binary(expression, "||")

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

    3437    def div_sql(self, expression: exp.Div) -> str:
    3438        l, r = expression.left, expression.right
    3439
    3440        if not self.dialect.SAFE_DIVISION and expression.args.get("safe"):
    3441            r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0)))
    3442
    3443        if self.dialect.TYPED_DIVISION and not expression.args.get("typed"):
    3444            if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES):
    3445                l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE))
    3446
    3447        elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"):
    3448            if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES):
    3449                return self.sql(
    3450                    exp.cast(
    3451                        l / r,
    3452                        to=exp.DataType.Type.BIGINT,
    3453                    )
    3454                )
    3455
    3456        return self.binary(expression, "/")

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

    3458    def safedivide_sql(self, expression: exp.SafeDivide) -> str:
    3459        n = exp._wrap(expression.this, exp.Binary)
    3460        d = exp._wrap(expression.expression, exp.Binary)
    3461        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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3496    def is_sql(self, expression: exp.Is) -> str:
    3497        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    3498            return self.sql(
    3499                expression.this if expression.expression.this else exp.not_(expression.this)
    3500            )
    3501        return self.binary(expression, "IS")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3545    def try_sql(self, expression: exp.Try) -> str:
    3546        if not self.TRY_SUPPORTED:
    3547            self.unsupported("Unsupported TRY function")
    3548            return self.sql(expression, "this")
    3549
    3550        return self.func("TRY", expression.this)

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

    3552    def log_sql(self, expression: exp.Log) -> str:
    3553        this = expression.this
    3554        expr = expression.expression
    3555
    3556        if self.dialect.LOG_BASE_FIRST is False:
    3557            this, expr = expr, this
    3558        elif self.dialect.LOG_BASE_FIRST is None and expr:
    3559            if this.name in ("2", "10"):
    3560                return self.func(f"LOG{this.name}", expr)
    3561
    3562            self.unsupported(f"Unsupported logarithm with base {self.sql(this)}")
    3563
    3564        return self.func("LOG", this, expr)

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

    3566    def use_sql(self, expression: exp.Use) -> str:
    3567        kind = self.sql(expression, "kind")
    3568        kind = f" {kind}" if kind else ""
    3569        this = self.sql(expression, "this") or self.expressions(expression, flat=True)
    3570        this = f" {this}" if this else ""
    3571        return f"USE{kind}{this}"

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

    3573    def binary(self, expression: exp.Binary, op: str) -> str:
    3574        sqls: t.List[str] = []
    3575        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    3576        binary_type = type(expression)
    3577
    3578        while stack:
    3579            node = stack.pop()
    3580
    3581            if type(node) is binary_type:
    3582                op_func = node.args.get("operator")
    3583                if op_func:
    3584                    op = f"OPERATOR({self.sql(op_func)})"
    3585
    3586                stack.append(node.right)
    3587                stack.append(f" {self.maybe_comment(op, comments=node.comments)} ")
    3588                stack.append(node.left)
    3589            else:
    3590                sqls.append(self.sql(node))
    3591
    3592        return "".join(sqls)

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

    3594    def ceil_floor(self, expression: exp.Ceil | exp.Floor) -> str:
    3595        to_clause = self.sql(expression, "to")
    3596        if to_clause:
    3597            return f"{expression.sql_name()}({self.sql(expression, 'this')} TO {to_clause})"
    3598
    3599        return self.function_fallback_sql(expression)

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

    3601    def function_fallback_sql(self, expression: exp.Func) -> str:
    3602        args = []
    3603
    3604        for key in expression.arg_types:
    3605            arg_value = expression.args.get(key)
    3606
    3607            if isinstance(arg_value, list):
    3608                for value in arg_value:
    3609                    args.append(value)
    3610            elif arg_value is not None:
    3611                args.append(arg_value)
    3612
    3613        if self.dialect.PRESERVE_ORIGINAL_NAMES:
    3614            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
    3615        else:
    3616            name = expression.sql_name()
    3617
    3618        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

    3620    def func(
    3621        self,
    3622        name: str,
    3623        *args: t.Optional[exp.Expression | str],
    3624        prefix: str = "(",
    3625        suffix: str = ")",
    3626        normalize: bool = True,
    3627    ) -> str:
    3628        name = self.normalize_func(name) if normalize else name
    3629        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

    3631    def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str:
    3632        arg_sqls = tuple(
    3633            self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool)
    3634        )
    3635        if self.pretty and self.too_wide(arg_sqls):
    3636            return self.indent(
    3637                "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True
    3638            )
    3639        return sep.join(arg_sqls)

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

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

    3644    def format_time(
    3645        self,
    3646        expression: exp.Expression,
    3647        inverse_time_mapping: t.Optional[t.Dict[str, str]] = None,
    3648        inverse_time_trie: t.Optional[t.Dict] = None,
    3649    ) -> t.Optional[str]:
    3650        return format_time(
    3651            self.sql(expression, "format"),
    3652            inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING,
    3653            inverse_time_trie or self.dialect.INVERSE_TIME_TRIE,
    3654        )

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

    3656    def expressions(
    3657        self,
    3658        expression: t.Optional[exp.Expression] = None,
    3659        key: t.Optional[str] = None,
    3660        sqls: t.Optional[t.Collection[str | exp.Expression]] = None,
    3661        flat: bool = False,
    3662        indent: bool = True,
    3663        skip_first: bool = False,
    3664        skip_last: bool = False,
    3665        sep: str = ", ",
    3666        prefix: str = "",
    3667        dynamic: bool = False,
    3668        new_line: bool = False,
    3669    ) -> str:
    3670        expressions = expression.args.get(key or "expressions") if expression else sqls
    3671
    3672        if not expressions:
    3673            return ""
    3674
    3675        if flat:
    3676            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
    3677
    3678        num_sqls = len(expressions)
    3679        result_sqls = []
    3680
    3681        for i, e in enumerate(expressions):
    3682            sql = self.sql(e, comment=False)
    3683            if not sql:
    3684                continue
    3685
    3686            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    3687
    3688            if self.pretty:
    3689                if self.leading_comma:
    3690                    result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}")
    3691                else:
    3692                    result_sqls.append(
    3693                        f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}"
    3694                    )
    3695            else:
    3696                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    3697
    3698        if self.pretty and (not dynamic or self.too_wide(result_sqls)):
    3699            if new_line:
    3700                result_sqls.insert(0, "")
    3701                result_sqls.append("")
    3702            result_sql = "\n".join(s.rstrip() for s in result_sqls)
    3703        else:
    3704            result_sql = "".join(result_sqls)
    3705
    3706        return (
    3707            self.indent(result_sql, skip_first=skip_first, skip_last=skip_last)
    3708            if indent
    3709            else result_sql
    3710        )

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

    3712    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    3713        flat = flat or isinstance(expression.parent, exp.Properties)
    3714        expressions_sql = self.expressions(expression, flat=flat)
    3715        if flat:
    3716            return f"{op} {expressions_sql}"
    3717        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"

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

    3719    def naked_property(self, expression: exp.Property) -> str:
    3720        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    3721        if not property_name:
    3722            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    3723        return f"{property_name} {self.sql(expression, 'this')}"

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

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

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

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

    3731    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    3732        this = self.sql(expression, "this")
    3733        expressions = self.no_identify(self.expressions, expression)
    3734        expressions = (
    3735            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    3736        )
    3737        return f"{this}{expressions}" if expressions.strip() != "" else this

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

    3739    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    3740        this = self.sql(expression, "this")
    3741        expressions = self.expressions(expression, flat=True)
    3742        return f"{this}({expressions})"

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

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

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

    3747    def when_sql(self, expression: exp.When) -> str:
    3748        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    3749        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    3750        condition = self.sql(expression, "condition")
    3751        condition = f" AND {condition}" if condition else ""
    3752
    3753        then_expression = expression.args.get("then")
    3754        if isinstance(then_expression, exp.Insert):
    3755            this = self.sql(then_expression, "this")
    3756            this = f"INSERT {this}" if this else "INSERT"
    3757            then = self.sql(then_expression, "expression")
    3758            then = f"{this} VALUES {then}" if then else this
    3759        elif isinstance(then_expression, exp.Update):
    3760            if isinstance(then_expression.args.get("expressions"), exp.Star):
    3761                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    3762            else:
    3763                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    3764        else:
    3765            then = self.sql(then_expression)
    3766        return f"WHEN {matched}{source}{condition} THEN {then}"

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

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

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

    3771    def merge_sql(self, expression: exp.Merge) -> str:
    3772        table = expression.this
    3773        table_alias = ""
    3774
    3775        hints = table.args.get("hints")
    3776        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
    3777            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
    3778            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
    3779
    3780        this = self.sql(table)
    3781        using = f"USING {self.sql(expression, 'using')}"
    3782        on = f"ON {self.sql(expression, 'on')}"
    3783        whens = self.sql(expression, "whens")
    3784
    3785        returning = self.sql(expression, "returning")
    3786        if returning:
    3787            whens = f"{whens}{returning}"
    3788
    3789        sep = self.sep()
    3790
    3791        return self.prepend_ctes(
    3792            expression,
    3793            f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}",
    3794        )

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

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

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

    3800    def tonumber_sql(self, expression: exp.ToNumber) -> str:
    3801        if not self.SUPPORTS_TO_NUMBER:
    3802            self.unsupported("Unsupported TO_NUMBER function")
    3803            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3804
    3805        fmt = expression.args.get("format")
    3806        if not fmt:
    3807            self.unsupported("Conversion format is required for TO_NUMBER")
    3808            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3809
    3810        return self.func("TO_NUMBER", expression.this, fmt)

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

    3812    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    3813        this = self.sql(expression, "this")
    3814        kind = self.sql(expression, "kind")
    3815        settings_sql = self.expressions(expression, key="settings", sep=" ")
    3816        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    3817        return f"{this}({kind}{args})"

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

    3819    def dictrange_sql(self, expression: exp.DictRange) -> str:
    3820        this = self.sql(expression, "this")
    3821        max = self.sql(expression, "max")
    3822        min = self.sql(expression, "min")
    3823        return f"{this}(MIN {min} MAX {max})"

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

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

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

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

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

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

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

    3836    def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str:
    3837        expressions = self.expressions(expression, flat=True)
    3838        expressions = f" {self.wrap(expressions)}" if expressions else ""
    3839        buckets = self.sql(expression, "buckets")
    3840        kind = self.sql(expression, "kind")
    3841        buckets = f" BUCKETS {buckets}" if buckets else ""
    3842        order = self.sql(expression, "order")
    3843        return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}"

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

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

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

    3848    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    3849        expressions = self.expressions(expression, key="expressions", flat=True)
    3850        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    3851        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    3852        buckets = self.sql(expression, "buckets")
    3853        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"

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

    3855    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    3856        this = self.sql(expression, "this")
    3857        having = self.sql(expression, "having")
    3858
    3859        if having:
    3860            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    3861
    3862        return self.func("ANY_VALUE", this)

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

    3864    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
    3865        transform = self.func("TRANSFORM", *expression.expressions)
    3866        row_format_before = self.sql(expression, "row_format_before")
    3867        row_format_before = f" {row_format_before}" if row_format_before else ""
    3868        record_writer = self.sql(expression, "record_writer")
    3869        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
    3870        using = f" USING {self.sql(expression, 'command_script')}"
    3871        schema = self.sql(expression, "schema")
    3872        schema = f" AS {schema}" if schema else ""
    3873        row_format_after = self.sql(expression, "row_format_after")
    3874        row_format_after = f" {row_format_after}" if row_format_after else ""
    3875        record_reader = self.sql(expression, "record_reader")
    3876        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
    3877        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

    3879    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
    3880        key_block_size = self.sql(expression, "key_block_size")
    3881        if key_block_size:
    3882            return f"KEY_BLOCK_SIZE = {key_block_size}"
    3883
    3884        using = self.sql(expression, "using")
    3885        if using:
    3886            return f"USING {using}"
    3887
    3888        parser = self.sql(expression, "parser")
    3889        if parser:
    3890            return f"WITH PARSER {parser}"
    3891
    3892        comment = self.sql(expression, "comment")
    3893        if comment:
    3894            return f"COMMENT {comment}"
    3895
    3896        visible = expression.args.get("visible")
    3897        if visible is not None:
    3898            return "VISIBLE" if visible else "INVISIBLE"
    3899
    3900        engine_attr = self.sql(expression, "engine_attr")
    3901        if engine_attr:
    3902            return f"ENGINE_ATTRIBUTE = {engine_attr}"
    3903
    3904        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
    3905        if secondary_engine_attr:
    3906            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
    3907
    3908        self.unsupported("Unsupported index constraint option.")
    3909        return ""

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

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

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

    3915    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
    3916        kind = self.sql(expression, "kind")
    3917        kind = f"{kind} INDEX" if kind else "INDEX"
    3918        this = self.sql(expression, "this")
    3919        this = f" {this}" if this else ""
    3920        index_type = self.sql(expression, "index_type")
    3921        index_type = f" USING {index_type}" if index_type else ""
    3922        expressions = self.expressions(expression, flat=True)
    3923        expressions = f" ({expressions})" if expressions else ""
    3924        options = self.expressions(expression, key="options", sep=" ")
    3925        options = f" {options}" if options else ""
    3926        return f"{kind}{this}{index_type}{expressions}{options}"

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

    3928    def nvl2_sql(self, expression: exp.Nvl2) -> str:
    3929        if self.NVL2_SUPPORTED:
    3930            return self.function_fallback_sql(expression)
    3931
    3932        case = exp.Case().when(
    3933            expression.this.is_(exp.null()).not_(copy=False),
    3934            expression.args["true"],
    3935            copy=False,
    3936        )
    3937        else_cond = expression.args.get("false")
    3938        if else_cond:
    3939            case.else_(else_cond, copy=False)
    3940
    3941        return self.sql(case)

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

    3943    def comprehension_sql(self, expression: exp.Comprehension) -> str:
    3944        this = self.sql(expression, "this")
    3945        expr = self.sql(expression, "expression")
    3946        iterator = self.sql(expression, "iterator")
    3947        condition = self.sql(expression, "condition")
    3948        condition = f" IF {condition}" if condition else ""
    3949        return f"{this} FOR {expr} IN {iterator}{condition}"

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

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

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

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

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

    3957    def predict_sql(self, expression: exp.Predict) -> str:
    3958        model = self.sql(expression, "this")
    3959        model = f"MODEL {model}"
    3960        table = self.sql(expression, "expression")
    3961        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
    3962        parameters = self.sql(expression, "params_struct")
    3963        return self.func("PREDICT", model, table, parameters or None)

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

    3965    def forin_sql(self, expression: exp.ForIn) -> str:
    3966        this = self.sql(expression, "this")
    3967        expression_sql = self.sql(expression, "expression")
    3968        return f"FOR {this} DO {expression_sql}"

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

    3970    def refresh_sql(self, expression: exp.Refresh) -> str:
    3971        this = self.sql(expression, "this")
    3972        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
    3973        return f"REFRESH {table}{this}"

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

    3975    def toarray_sql(self, expression: exp.ToArray) -> str:
    3976        arg = expression.this
    3977        if not arg.type:
    3978            from sqlglot.optimizer.annotate_types import annotate_types
    3979
    3980            arg = annotate_types(arg)
    3981
    3982        if arg.is_type(exp.DataType.Type.ARRAY):
    3983            return self.sql(arg)
    3984
    3985        cond_for_null = arg.is_(exp.null())
    3986        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

    3988    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
    3989        this = expression.this
    3990        time_format = self.format_time(expression)
    3991
    3992        if time_format:
    3993            return self.sql(
    3994                exp.cast(
    3995                    exp.StrToTime(this=this, format=expression.args["format"]),
    3996                    exp.DataType.Type.TIME,
    3997                )
    3998            )
    3999
    4000        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
    4001            return self.sql(this)
    4002
    4003        return self.sql(exp.cast(this, exp.DataType.Type.TIME))

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

    4005    def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str:
    4006        this = expression.this
    4007        if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP):
    4008            return self.sql(this)
    4009
    4010        return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect))

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

    4012    def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str:
    4013        this = expression.this
    4014        if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME):
    4015            return self.sql(this)
    4016
    4017        return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect))

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

    4019    def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:
    4020        this = expression.this
    4021        time_format = self.format_time(expression)
    4022
    4023        if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT):
    4024            return self.sql(
    4025                exp.cast(
    4026                    exp.StrToTime(this=this, format=expression.args["format"]),
    4027                    exp.DataType.Type.DATE,
    4028                )
    4029            )
    4030
    4031        if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE):
    4032            return self.sql(this)
    4033
    4034        return self.sql(exp.cast(this, exp.DataType.Type.DATE))

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

    4036    def unixdate_sql(self, expression: exp.UnixDate) -> str:
    4037        return self.sql(
    4038            exp.func(
    4039                "DATEDIFF",
    4040                expression.this,
    4041                exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE),
    4042                "day",
    4043            )
    4044        )

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

    4046    def lastday_sql(self, expression: exp.LastDay) -> str:
    4047        if self.LAST_DAY_SUPPORTS_DATE_PART:
    4048            return self.function_fallback_sql(expression)
    4049
    4050        unit = expression.text("unit")
    4051        if unit and unit != "MONTH":
    4052            self.unsupported("Date parts are not supported in LAST_DAY.")
    4053
    4054        return self.func("LAST_DAY", expression.this)

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

    4056    def dateadd_sql(self, expression: exp.DateAdd) -> str:
    4057        from sqlglot.dialects.dialect import unit_to_str
    4058
    4059        return self.func(
    4060            "DATE_ADD", expression.this, expression.expression, unit_to_str(expression)
    4061        )

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

    4063    def arrayany_sql(self, expression: exp.ArrayAny) -> str:
    4064        if self.CAN_IMPLEMENT_ARRAY_ANY:
    4065            filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression)
    4066            filtered_not_empty = exp.ArraySize(this=filtered).neq(0)
    4067            original_is_empty = exp.ArraySize(this=expression.this).eq(0)
    4068            return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty)))
    4069
    4070        from sqlglot.dialects import Dialect
    4071
    4072        # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect
    4073        if self.dialect.__class__ != Dialect:
    4074            self.unsupported("ARRAY_ANY is unsupported")
    4075
    4076        return self.function_fallback_sql(expression)

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

    4078    def struct_sql(self, expression: exp.Struct) -> str:
    4079        expression.set(
    4080            "expressions",
    4081            [
    4082                exp.alias_(e.expression, e.name if e.this.is_string else e.this)
    4083                if isinstance(e, exp.PropertyEQ)
    4084                else e
    4085                for e in expression.expressions
    4086            ],
    4087        )
    4088
    4089        return self.function_fallback_sql(expression)

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

    4091    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
    4092        low = self.sql(expression, "this")
    4093        high = self.sql(expression, "expression")
    4094
    4095        return f"{low} TO {high}"

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

    4097    def truncatetable_sql(self, expression: exp.TruncateTable) -> str:
    4098        target = "DATABASE" if expression.args.get("is_database") else "TABLE"
    4099        tables = f" {self.expressions(expression)}"
    4100
    4101        exists = " IF EXISTS" if expression.args.get("exists") else ""
    4102
    4103        on_cluster = self.sql(expression, "cluster")
    4104        on_cluster = f" {on_cluster}" if on_cluster else ""
    4105
    4106        identity = self.sql(expression, "identity")
    4107        identity = f" {identity} IDENTITY" if identity else ""
    4108
    4109        option = self.sql(expression, "option")
    4110        option = f" {option}" if option else ""
    4111
    4112        partition = self.sql(expression, "partition")
    4113        partition = f" {partition}" if partition else ""
    4114
    4115        return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"

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

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

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

    4219    def copyparameter_sql(self, expression: exp.CopyParameter) -> str:
    4220        option = self.sql(expression, "this")
    4221
    4222        if expression.expressions:
    4223            upper = option.upper()
    4224
    4225            # Snowflake FILE_FORMAT options are separated by whitespace
    4226            sep = " " if upper == "FILE_FORMAT" else ", "
    4227
    4228            # Databricks copy/format options do not set their list of values with EQ
    4229            op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = "
    4230            values = self.expressions(expression, flat=True, sep=sep)
    4231            return f"{option}{op}({values})"
    4232
    4233        value = self.sql(expression, "expression")
    4234
    4235        if not value:
    4236            return option
    4237
    4238        op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " "
    4239
    4240        return f"{option}{op}{value}"

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

    4242    def credentials_sql(self, expression: exp.Credentials) -> str:
    4243        cred_expr = expression.args.get("credentials")
    4244        if isinstance(cred_expr, exp.Literal):
    4245            # Redshift case: CREDENTIALS <string>
    4246            credentials = self.sql(expression, "credentials")
    4247            credentials = f"CREDENTIALS {credentials}" if credentials else ""
    4248        else:
    4249            # Snowflake case: CREDENTIALS = (...)
    4250            credentials = self.expressions(expression, key="credentials", flat=True, sep=" ")
    4251            credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else ""
    4252
    4253        storage = self.sql(expression, "storage")
    4254        storage = f"STORAGE_INTEGRATION = {storage}" if storage else ""
    4255
    4256        encryption = self.expressions(expression, key="encryption", flat=True, sep=" ")
    4257        encryption = f" ENCRYPTION = ({encryption})" if encryption else ""
    4258
    4259        iam_role = self.sql(expression, "iam_role")
    4260        iam_role = f"IAM_ROLE {iam_role}" if iam_role else ""
    4261
    4262        region = self.sql(expression, "region")
    4263        region = f" REGION {region}" if region else ""
    4264
    4265        return f"{credentials}{storage}{encryption}{iam_role}{region}"

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

    4267    def copy_sql(self, expression: exp.Copy) -> str:
    4268        this = self.sql(expression, "this")
    4269        this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}"
    4270
    4271        credentials = self.sql(expression, "credentials")
    4272        credentials = self.seg(credentials) if credentials else ""
    4273        kind = self.seg("FROM" if expression.args.get("kind") else "TO")
    4274        files = self.expressions(expression, key="files", flat=True)
    4275
    4276        sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " "
    4277        params = self.expressions(
    4278            expression,
    4279            key="params",
    4280            sep=sep,
    4281            new_line=True,
    4282            skip_last=True,
    4283            skip_first=True,
    4284            indent=self.COPY_PARAMS_ARE_WRAPPED,
    4285        )
    4286
    4287        if params:
    4288            if self.COPY_PARAMS_ARE_WRAPPED:
    4289                params = f" WITH ({params})"
    4290            elif not self.pretty:
    4291                params = f" {params}"
    4292
    4293        return f"COPY{this}{kind} {files}{credentials}{params}"

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

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

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

    4298    def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str:
    4299        on_sql = "ON" if expression.args.get("on") else "OFF"
    4300        filter_col: t.Optional[str] = self.sql(expression, "filter_column")
    4301        filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None
    4302        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    4303        retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None
    4304
    4305        if filter_col or retention_period:
    4306            on_sql = self.func("ON", filter_col, retention_period)
    4307
    4308        return f"DATA_DELETION={on_sql}"

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

    4310    def maskingpolicycolumnconstraint_sql(
    4311        self, expression: exp.MaskingPolicyColumnConstraint
    4312    ) -> str:
    4313        this = self.sql(expression, "this")
    4314        expressions = self.expressions(expression, flat=True)
    4315        expressions = f" USING ({expressions})" if expressions else ""
    4316        return f"MASKING POLICY {this}{expressions}"

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

    4318    def gapfill_sql(self, expression: exp.GapFill) -> str:
    4319        this = self.sql(expression, "this")
    4320        this = f"TABLE {this}"
    4321        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

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

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

    4326    def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str:
    4327        this = self.sql(expression, "this")
    4328        expr = expression.expression
    4329
    4330        if isinstance(expr, exp.Func):
    4331            # T-SQL's CLR functions are case sensitive
    4332            expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})"
    4333        else:
    4334            expr = self.sql(expression, "expression")
    4335
    4336        return self.scope_resolution(expr, this)

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

    4338    def parsejson_sql(self, expression: exp.ParseJSON) -> str:
    4339        if self.PARSE_JSON_NAME is None:
    4340            return self.sql(expression.this)
    4341
    4342        return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression)

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

    4344    def rand_sql(self, expression: exp.Rand) -> str:
    4345        lower = self.sql(expression, "lower")
    4346        upper = self.sql(expression, "upper")
    4347
    4348        if lower and upper:
    4349            return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}"
    4350        return self.func("RAND", expression.this)

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

    4352    def changes_sql(self, expression: exp.Changes) -> str:
    4353        information = self.sql(expression, "information")
    4354        information = f"INFORMATION => {information}"
    4355        at_before = self.sql(expression, "at_before")
    4356        at_before = f"{self.seg('')}{at_before}" if at_before else ""
    4357        end = self.sql(expression, "end")
    4358        end = f"{self.seg('')}{end}" if end else ""
    4359
    4360        return f"CHANGES ({information}){at_before}{end}"

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

    4362    def pad_sql(self, expression: exp.Pad) -> str:
    4363        prefix = "L" if expression.args.get("is_left") else "R"
    4364
    4365        fill_pattern = self.sql(expression, "fill_pattern") or None
    4366        if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED:
    4367            fill_pattern = "' '"
    4368
    4369        return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)

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

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

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

    4375    def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str:
    4376        generate_series = exp.GenerateSeries(**expression.args)
    4377
    4378        parent = expression.parent
    4379        if isinstance(parent, (exp.Alias, exp.TableAlias)):
    4380            parent = parent.parent
    4381
    4382        if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)):
    4383            return self.sql(exp.Unnest(expressions=[generate_series]))
    4384
    4385        if isinstance(parent, exp.Select):
    4386            self.unsupported("GenerateSeries projection unnesting is not supported.")
    4387
    4388        return self.sql(generate_series)

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

    4390    def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str:
    4391        exprs = expression.expressions
    4392        if not self.ARRAY_CONCAT_IS_VAR_LEN:
    4393            rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs)
    4394        else:
    4395            rhs = self.expressions(expression)
    4396
    4397        return self.func(name, expression.this, rhs or None)

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

    4399    def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str:
    4400        if self.SUPPORTS_CONVERT_TIMEZONE:
    4401            return self.function_fallback_sql(expression)
    4402
    4403        source_tz = expression.args.get("source_tz")
    4404        target_tz = expression.args.get("target_tz")
    4405        timestamp = expression.args.get("timestamp")
    4406
    4407        if source_tz and timestamp:
    4408            timestamp = exp.AtTimeZone(
    4409                this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz
    4410            )
    4411
    4412        expr = exp.AtTimeZone(this=timestamp, zone=target_tz)
    4413
    4414        return self.sql(expr)

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

    4416    def json_sql(self, expression: exp.JSON) -> str:
    4417        this = self.sql(expression, "this")
    4418        this = f" {this}" if this else ""
    4419
    4420        _with = expression.args.get("with")
    4421
    4422        if _with is None:
    4423            with_sql = ""
    4424        elif not _with:
    4425            with_sql = " WITHOUT"
    4426        else:
    4427            with_sql = " WITH"
    4428
    4429        unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else ""
    4430
    4431        return f"JSON{this}{with_sql}{unique_sql}"

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

    4433    def jsonvalue_sql(self, expression: exp.JSONValue) -> str:
    4434        def _generate_on_options(arg: t.Any) -> str:
    4435            return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}"
    4436
    4437        path = self.sql(expression, "path")
    4438        returning = self.sql(expression, "returning")
    4439        returning = f" RETURNING {returning}" if returning else ""
    4440
    4441        on_condition = self.sql(expression, "on_condition")
    4442        on_condition = f" {on_condition}" if on_condition else ""
    4443
    4444        return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}")

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

    4446    def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str:
    4447        else_ = "ELSE " if expression.args.get("else_") else ""
    4448        condition = self.sql(expression, "expression")
    4449        condition = f"WHEN {condition} THEN " if condition else else_
    4450        insert = self.sql(expression, "this")[len("INSERT") :].strip()
    4451        return f"{condition}{insert}"

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

    4453    def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str:
    4454        kind = self.sql(expression, "kind")
    4455        expressions = self.seg(self.expressions(expression, sep=" "))
    4456        res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}"
    4457        return res

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

    4459    def oncondition_sql(self, expression: exp.OnCondition) -> str:
    4460        # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR"
    4461        empty = expression.args.get("empty")
    4462        empty = (
    4463            f"DEFAULT {empty} ON EMPTY"
    4464            if isinstance(empty, exp.Expression)
    4465            else self.sql(expression, "empty")
    4466        )
    4467
    4468        error = expression.args.get("error")
    4469        error = (
    4470            f"DEFAULT {error} ON ERROR"
    4471            if isinstance(error, exp.Expression)
    4472            else self.sql(expression, "error")
    4473        )
    4474
    4475        if error and empty:
    4476            error = (
    4477                f"{empty} {error}"
    4478                if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR
    4479                else f"{error} {empty}"
    4480            )
    4481            empty = ""
    4482
    4483        null = self.sql(expression, "null")
    4484
    4485        return f"{empty}{error}{null}"

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

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

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

    4491    def jsonexists_sql(self, expression: exp.JSONExists) -> str:
    4492        this = self.sql(expression, "this")
    4493        path = self.sql(expression, "path")
    4494
    4495        passing = self.expressions(expression, "passing")
    4496        passing = f" PASSING {passing}" if passing else ""
    4497
    4498        on_condition = self.sql(expression, "on_condition")
    4499        on_condition = f" {on_condition}" if on_condition else ""
    4500
    4501        path = f"{path}{passing}{on_condition}"
    4502
    4503        return self.func("JSON_EXISTS", this, path)

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

    4505    def arrayagg_sql(self, expression: exp.ArrayAgg) -> str:
    4506        array_agg = self.function_fallback_sql(expression)
    4507
    4508        # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls
    4509        # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB)
    4510        if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"):
    4511            parent = expression.parent
    4512            if isinstance(parent, exp.Filter):
    4513                parent_cond = parent.expression.this
    4514                parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_()))
    4515            else:
    4516                this = expression.this
    4517                # Do not add the filter if the input is not a column (e.g. literal, struct etc)
    4518                if this.find(exp.Column):
    4519                    # DISTINCT is already present in the agg function, do not propagate it to FILTER as well
    4520                    this_sql = (
    4521                        self.expressions(this)
    4522                        if isinstance(this, exp.Distinct)
    4523                        else self.sql(expression, "this")
    4524                    )
    4525
    4526                    array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)"
    4527
    4528        return array_agg

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

    4530    def apply_sql(self, expression: exp.Apply) -> str:
    4531        this = self.sql(expression, "this")
    4532        expr = self.sql(expression, "expression")
    4533
    4534        return f"{this} APPLY({expr})"

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

    4536    def grant_sql(self, expression: exp.Grant) -> str:
    4537        privileges_sql = self.expressions(expression, key="privileges", flat=True)
    4538
    4539        kind = self.sql(expression, "kind")
    4540        kind = f" {kind}" if kind else ""
    4541
    4542        securable = self.sql(expression, "securable")
    4543        securable = f" {securable}" if securable else ""
    4544
    4545        principals = self.expressions(expression, key="principals", flat=True)
    4546
    4547        grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else ""
    4548
    4549        return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}"

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

    4551    def grantprivilege_sql(self, expression: exp.GrantPrivilege):
    4552        this = self.sql(expression, "this")
    4553        columns = self.expressions(expression, flat=True)
    4554        columns = f"({columns})" if columns else ""
    4555
    4556        return f"{this}{columns}"

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

    4558    def grantprincipal_sql(self, expression: exp.GrantPrincipal):
    4559        this = self.sql(expression, "this")
    4560
    4561        kind = self.sql(expression, "kind")
    4562        kind = f"{kind} " if kind else ""
    4563
    4564        return f"{kind}{this}"

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

    4566    def columns_sql(self, expression: exp.Columns):
    4567        func = self.function_fallback_sql(expression)
    4568        if expression.args.get("unpack"):
    4569            func = f"*{func}"
    4570
    4571        return func

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

    4573    def overlay_sql(self, expression: exp.Overlay):
    4574        this = self.sql(expression, "this")
    4575        expr = self.sql(expression, "expression")
    4576        from_sql = self.sql(expression, "from")
    4577        for_sql = self.sql(expression, "for")
    4578        for_sql = f" FOR {for_sql}" if for_sql else ""
    4579
    4580        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

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

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

    4586    def string_sql(self, expression: exp.String) -> str:
    4587        this = expression.this
    4588        zone = expression.args.get("zone")
    4589
    4590        if zone:
    4591            # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>)
    4592            # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC
    4593            # set for source_tz to transpile the time conversion before the STRING cast
    4594            this = exp.ConvertTimezone(
    4595                source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this
    4596            )
    4597
    4598        return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR))

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

    4600    def median_sql(self, expression: exp.Median):
    4601        if not self.SUPPORTS_MEDIAN:
    4602            return self.sql(
    4603                exp.PercentileCont(this=expression.this, expression=exp.Literal.number(0.5))
    4604            )
    4605
    4606        return self.function_fallback_sql(expression)

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

    4608    def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str:
    4609        filler = self.sql(expression, "this")
    4610        filler = f" {filler}" if filler else ""
    4611        with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT"
    4612        return f"TRUNCATE{filler} {with_count}"

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

    4614    def unixseconds_sql(self, expression: exp.UnixSeconds) -> str:
    4615        if self.SUPPORTS_UNIX_SECONDS:
    4616            return self.function_fallback_sql(expression)
    4617
    4618        start_ts = exp.cast(
    4619            exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ
    4620        )
    4621
    4622        return self.sql(
    4623            exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS"))
    4624        )

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

    4626    def arraysize_sql(self, expression: exp.ArraySize) -> str:
    4627        dim = expression.expression
    4628
    4629        # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension)
    4630        if dim and self.ARRAY_SIZE_DIM_REQUIRED is None:
    4631            if not (dim.is_int and dim.name == "1"):
    4632                self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH")
    4633            dim = None
    4634
    4635        # If dimension is required but not specified, default initialize it
    4636        if self.ARRAY_SIZE_DIM_REQUIRED and not dim:
    4637            dim = exp.Literal.number(1)
    4638
    4639        return self.func(self.ARRAY_SIZE_NAME, expression.this, dim)

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

    4641    def attach_sql(self, expression: exp.Attach) -> str:
    4642        this = self.sql(expression, "this")
    4643        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
    4644        expressions = self.expressions(expression)
    4645        expressions = f" ({expressions})" if expressions else ""
    4646
    4647        return f"ATTACH{exists_sql} {this}{expressions}"

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

    4649    def detach_sql(self, expression: exp.Detach) -> str:
    4650        this = self.sql(expression, "this")
    4651        exists_sql = " IF EXISTS" if expression.args.get("exists") else ""
    4652
    4653        return f"DETACH{exists_sql} {this}"

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

    4655    def attachoption_sql(self, expression: exp.AttachOption) -> str:
    4656        this = self.sql(expression, "this")
    4657        value = self.sql(expression, "expression")
    4658        value = f" {value}" if value else ""
    4659        return f"{this}{value}"

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

    4661    def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str:
    4662        this_sql = self.sql(expression, "this")
    4663        if isinstance(expression.this, exp.Table):
    4664            this_sql = f"TABLE {this_sql}"
    4665
    4666        return self.func(
    4667            "FEATURES_AT_TIME",
    4668            this_sql,
    4669            expression.args.get("time"),
    4670            expression.args.get("num_rows"),
    4671            expression.args.get("ignore_feature_nulls"),
    4672        )

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

    4674    def watermarkcolumnconstraint_sql(self, expression: exp.WatermarkColumnConstraint) -> str:
    4675        return (
    4676            f"WATERMARK FOR {self.sql(expression, 'this')} AS {self.sql(expression, 'expression')}"
    4677        )

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

    4679    def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str:
    4680        encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE"
    4681        encode = f"{encode} {self.sql(expression, 'this')}"
    4682
    4683        properties = expression.args.get("properties")
    4684        if properties:
    4685            encode = f"{encode} {self.properties(properties)}"
    4686
    4687        return encode

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

    4689    def includeproperty_sql(self, expression: exp.IncludeProperty) -> str:
    4690        this = self.sql(expression, "this")
    4691        include = f"INCLUDE {this}"
    4692
    4693        column_def = self.sql(expression, "column_def")
    4694        if column_def:
    4695            include = f"{include} {column_def}"
    4696
    4697        alias = self.sql(expression, "alias")
    4698        if alias:
    4699            include = f"{include} AS {alias}"
    4700
    4701        return include

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

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

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

    4707    def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str:
    4708        partitions = self.expressions(expression, "partition_expressions")
    4709        create = self.expressions(expression, "create_expressions")
    4710        return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}"

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

    4712    def partitionbyrangepropertydynamic_sql(
    4713        self, expression: exp.PartitionByRangePropertyDynamic
    4714    ) -> str:
    4715        start = self.sql(expression, "start")
    4716        end = self.sql(expression, "end")
    4717
    4718        every = expression.args["every"]
    4719        if isinstance(every, exp.Interval) and every.this.is_string:
    4720            every.this.replace(exp.Literal.number(every.name))
    4721
    4722        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

    4724    def unpivotcolumns_sql(self, expression: exp.UnpivotColumns) -> str:
    4725        name = self.sql(expression, "this")
    4726        values = self.expressions(expression, flat=True)
    4727
    4728        return f"NAME {name} VALUE {values}"

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

    4730    def analyzesample_sql(self, expression: exp.AnalyzeSample) -> str:
    4731        kind = self.sql(expression, "kind")
    4732        sample = self.sql(expression, "sample")
    4733        return f"SAMPLE {sample} {kind}"

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

    4735    def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str:
    4736        kind = self.sql(expression, "kind")
    4737        option = self.sql(expression, "option")
    4738        option = f" {option}" if option else ""
    4739        this = self.sql(expression, "this")
    4740        this = f" {this}" if this else ""
    4741        columns = self.expressions(expression)
    4742        columns = f" {columns}" if columns else ""
    4743        return f"{kind}{option} STATISTICS{this}{columns}"

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

    4745    def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str:
    4746        this = self.sql(expression, "this")
    4747        columns = self.expressions(expression)
    4748        inner_expression = self.sql(expression, "expression")
    4749        inner_expression = f" {inner_expression}" if inner_expression else ""
    4750        update_options = self.sql(expression, "update_options")
    4751        update_options = f" {update_options} UPDATE" if update_options else ""
    4752        return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}"

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

    4754    def analyzedelete_sql(self, expression: exp.AnalyzeDelete) -> str:
    4755        kind = self.sql(expression, "kind")
    4756        kind = f" {kind}" if kind else ""
    4757        return f"DELETE{kind} STATISTICS"

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

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

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

    4763    def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str:
    4764        kind = self.sql(expression, "kind")
    4765        this = self.sql(expression, "this")
    4766        this = f" {this}" if this else ""
    4767        inner_expression = self.sql(expression, "expression")
    4768        return f"VALIDATE {kind}{this}{inner_expression}"

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

    4770    def analyze_sql(self, expression: exp.Analyze) -> str:
    4771        options = self.expressions(expression, key="options", sep=" ")
    4772        options = f" {options}" if options else ""
    4773        kind = self.sql(expression, "kind")
    4774        kind = f" {kind}" if kind else ""
    4775        this = self.sql(expression, "this")
    4776        this = f" {this}" if this else ""
    4777        mode = self.sql(expression, "mode")
    4778        mode = f" {mode}" if mode else ""
    4779        properties = self.sql(expression, "properties")
    4780        properties = f" {properties}" if properties else ""
    4781        partition = self.sql(expression, "partition")
    4782        partition = f" {partition}" if partition else ""
    4783        inner_expression = self.sql(expression, "expression")
    4784        inner_expression = f" {inner_expression}" if inner_expression else ""
    4785        return f"ANALYZE{options}{kind}{this}{partition}{mode}{inner_expression}{properties}"

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

    4787    def xmltable_sql(self, expression: exp.XMLTable) -> str:
    4788        this = self.sql(expression, "this")
    4789        namespaces = self.expressions(expression, key="namespaces")
    4790        namespaces = f"XMLNAMESPACES({namespaces}), " if namespaces else ""
    4791        passing = self.expressions(expression, key="passing")
    4792        passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else ""
    4793        columns = self.expressions(expression, key="columns")
    4794        columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else ""
    4795        by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else ""
    4796        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

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

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

    4802    def export_sql(self, expression: exp.Export) -> str:
    4803        this = self.sql(expression, "this")
    4804        connection = self.sql(expression, "connection")
    4805        connection = f"WITH CONNECTION {connection} " if connection else ""
    4806        options = self.sql(expression, "options")
    4807        return f"EXPORT DATA {connection}{options} AS {this}"

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

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

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

    4812    def declareitem_sql(self, expression: exp.DeclareItem) -> str:
    4813        variable = self.sql(expression, "this")
    4814        default = self.sql(expression, "default")
    4815        default = f" = {default}" if default else ""
    4816
    4817        kind = self.sql(expression, "kind")
    4818        if isinstance(expression.args.get("kind"), exp.Schema):
    4819            kind = f"TABLE {kind}"
    4820
    4821        return f"{variable} AS {kind}{default}"

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

    4823    def recursivewithsearch_sql(self, expression: exp.RecursiveWithSearch) -> str:
    4824        kind = self.sql(expression, "kind")
    4825        this = self.sql(expression, "this")
    4826        set = self.sql(expression, "expression")
    4827        using = self.sql(expression, "using")
    4828        using = f" USING {using}" if using else ""
    4829
    4830        kind_sql = kind if kind == "CYCLE" else f"SEARCH {kind} FIRST BY"
    4831
    4832        return f"{kind_sql} {this} SET {set}{using}"

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

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

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

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

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

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

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

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

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

    4847    def show_sql(self, expression: exp.Show) -> str:
    4848        self.unsupported("Unsupported SHOW statement")
    4849        return ""