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

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

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

    706    def __init__(
    707        self,
    708        pretty: t.Optional[bool] = None,
    709        identify: str | bool = False,
    710        normalize: bool = False,
    711        pad: int = 2,
    712        indent: int = 2,
    713        normalize_functions: t.Optional[str | bool] = None,
    714        unsupported_level: ErrorLevel = ErrorLevel.WARN,
    715        max_unsupported: int = 3,
    716        leading_comma: bool = False,
    717        max_text_width: int = 80,
    718        comments: bool = True,
    719        dialect: DialectType = None,
    720    ):
    721        import sqlglot
    722        from sqlglot.dialects import Dialect
    723
    724        self.pretty = pretty if pretty is not None else sqlglot.pretty
    725        self.identify = identify
    726        self.normalize = normalize
    727        self.pad = pad
    728        self._indent = indent
    729        self.unsupported_level = unsupported_level
    730        self.max_unsupported = max_unsupported
    731        self.leading_comma = leading_comma
    732        self.max_text_width = max_text_width
    733        self.comments = comments
    734        self.dialect = Dialect.get_or_raise(dialect)
    735
    736        # This is both a Dialect property and a Generator argument, so we prioritize the latter
    737        self.normalize_functions = (
    738            self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions
    739        )
    740
    741        self.unsupported_messages: t.List[str] = []
    742        self._escaped_quote_end: str = (
    743            self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END
    744        )
    745        self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2
    746
    747        self._next_name = name_sequence("_t")
    748
    749        self._identifier_start = self.dialect.IDENTIFIER_START
    750        self._identifier_end = self.dialect.IDENTIFIER_END
    751
    752        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.ConvertToCharset'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CredentialsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DateFormatColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DefaultColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DynamicProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EmptyProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EncodeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EnviromentProperty'>: <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.Get'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.GlobalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.HeapProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.IcebergProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InheritsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InlineLengthColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Intersect'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.IntervalSpan'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Int64'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LanguageProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LocationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.MaterializedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NonClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NotForReplicationColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnCommitProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnUpdateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Operator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OutputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PartitionedByBucket'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PartitionByTruncate'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PivotAny'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ProjectionPolicyColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Put'>: <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.TableColumn'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Tags'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TemporaryProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Union'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UnloggedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UsingTemplateProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UsingData'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Uuid'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VarMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ViewAttributeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithProcedureOptions'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithSchemaBindingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithOperator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ForceProperty'>: <function Generator.<lambda>>}
NULL_ORDERING_SUPPORTED: Optional[bool] = True
IGNORE_NULLS_IN_FUNC = False
LOCKING_READS_SUPPORTED = False
EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = True
WRAP_DERIVED_VALUES = True
CREATE_FUNCTION_RETURN_AS = True
MATCHED_BY_SOURCE = True
SINGLE_STRING_INTERVAL = False
INTERVAL_ALLOWS_PLURAL_FORM = True
LIMIT_FETCH = 'ALL'
LIMIT_ONLY_LITERALS = False
RENAME_TABLE_WITH_DB = True
GROUPINGS_SEP = ','
INDEX_ON = 'ON'
JOIN_HINTS = True
TABLE_HINTS = True
QUERY_HINTS = True
QUERY_HINT_SEP = ', '
IS_BOOL_ALLOWED = True
DUPLICATE_KEY_UPDATE_WITH_SET = True
LIMIT_IS_TOP = False
RETURNING_END = True
EXTRACT_ALLOWS_QUOTES = True
TZ_TO_WITH_TIME_ZONE = False
NVL2_SUPPORTED = True
SELECT_KINDS: Tuple[str, ...] = ('STRUCT', 'VALUE')
VALUES_AS_TABLE = True
ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = True
UNNEST_WITH_ORDINALITY = True
AGGREGATE_FILTER_SUPPORTED = True
SEMI_ANTI_JOIN_WITH_SIDE = True
COMPUTED_COLUMN_WITH_TYPE = True
SUPPORTS_TABLE_COPY = True
TABLESAMPLE_REQUIRES_PARENS = True
TABLESAMPLE_SIZE_IS_ROWS = True
TABLESAMPLE_KEYWORDS = 'TABLESAMPLE'
TABLESAMPLE_WITH_METHOD = True
TABLESAMPLE_SEED_KEYWORD = 'SEED'
COLLATE_IS_FUNC = False
DATA_TYPE_SPECIFIERS_ALLOWED = False
ENSURE_BOOLS = False
CTE_RECURSIVE_KEYWORD_REQUIRED = True
SUPPORTS_SINGLE_ARG_CONCAT = True
LAST_DAY_SUPPORTS_DATE_PART = True
SUPPORTS_TABLE_ALIAS_COLUMNS = True
UNPIVOT_ALIASES_ARE_IDENTIFIERS = True
JSON_KEY_VALUE_PAIR_SEP = ':'
INSERT_OVERWRITE = ' OVERWRITE TABLE'
SUPPORTS_SELECT_INTO = False
SUPPORTS_UNLOGGED_TABLES = False
SUPPORTS_CREATE_TABLE_LIKE = True
LIKE_PROPERTY_INSIDE_SCHEMA = False
MULTI_ARG_DISTINCT = True
JSON_TYPE_REQUIRED_FOR_EXTRACTION = False
JSON_PATH_BRACKETED_KEY_SUPPORTED = True
JSON_PATH_SINGLE_QUOTE_ESCAPE = False
SUPPORTED_JSON_PATH_PARTS = {<class 'sqlglot.expressions.JSONPathWildcard'>, <class 'sqlglot.expressions.JSONPathUnion'>, <class 'sqlglot.expressions.JSONPathRoot'>, <class 'sqlglot.expressions.JSONPathSubscript'>, <class 'sqlglot.expressions.JSONPathRecursive'>, <class 'sqlglot.expressions.JSONPathSelector'>, <class 'sqlglot.expressions.JSONPathKey'>, <class 'sqlglot.expressions.JSONPathSlice'>, <class 'sqlglot.expressions.JSONPathFilter'>, <class 'sqlglot.expressions.JSONPathScript'>}
CAN_IMPLEMENT_ARRAY_ANY = False
SUPPORTS_TO_NUMBER = True
SUPPORTS_WINDOW_EXCLUDE = False
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
ALTER_SET_WRAPPED = False
NORMALIZE_EXTRACT_DATE_PARTS = False
PARSE_JSON_NAME: Optional[str] = 'PARSE_JSON'
ARRAY_SIZE_NAME: str = 'ARRAY_LENGTH'
ALTER_SET_TYPE = 'SET DATA TYPE'
ARRAY_SIZE_DIM_REQUIRED: Optional[bool] = None
TYPE_MAPPING = {<Type.DATETIME2: 'DATETIME2'>: 'TIMESTAMP', <Type.NCHAR: 'NCHAR'>: 'CHAR', <Type.NVARCHAR: 'NVARCHAR'>: 'VARCHAR', <Type.MEDIUMTEXT: 'MEDIUMTEXT'>: 'TEXT', <Type.LONGTEXT: 'LONGTEXT'>: 'TEXT', <Type.TINYTEXT: 'TINYTEXT'>: 'TEXT', <Type.BLOB: 'BLOB'>: 'VARBINARY', <Type.MEDIUMBLOB: 'MEDIUMBLOB'>: 'BLOB', <Type.LONGBLOB: 'LONGBLOB'>: 'BLOB', <Type.TINYBLOB: 'TINYBLOB'>: 'BLOB', <Type.INET: 'INET'>: 'INET', <Type.ROWVERSION: 'ROWVERSION'>: 'VARBINARY', <Type.SMALLDATETIME: 'SMALLDATETIME'>: 'TIMESTAMP'}
TIME_PART_SINGULARS = {'MICROSECONDS': 'MICROSECOND', 'SECONDS': 'SECOND', 'MINUTES': 'MINUTE', 'HOURS': 'HOUR', 'DAYS': 'DAY', 'WEEKS': 'WEEK', 'MONTHS': 'MONTH', 'QUARTERS': 'QUARTER', 'YEARS': 'YEAR'}
AFTER_HAVING_MODIFIER_TRANSFORMS = {'cluster': <function Generator.<lambda>>, 'distribute': <function Generator.<lambda>>, 'sort': <function Generator.<lambda>>, 'windows': <function Generator.<lambda>>, 'qualify': <function Generator.<lambda>>}
TOKEN_MAPPING: Dict[sqlglot.tokens.TokenType, str] = {}
STRUCT_DELIMITER = ('<', '>')
PARAMETER_TOKEN = '@'
NAMED_PLACEHOLDER_TOKEN = ':'
EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: Set[str] = set()
PROPERTIES_LOCATION = {<class 'sqlglot.expressions.AllowedValuesProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.AlgorithmProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.AutoIncrementProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.AutoRefreshProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.BackupProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.BlockCompressionProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CharacterSetProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ChecksumProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CollateProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Cluster'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ClusteredByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistributedByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DuplicateKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DataBlocksizeProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.DataDeletionProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DefinerProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.DictRange'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DictProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DynamicProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.DistKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistStyleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EmptyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EncodeProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.EngineProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EnviromentProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExternalProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.FallbackProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.FileFormatProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.FreespaceProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.GlobalProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.HeapProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.InheritsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.IcebergProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.IncludeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.InputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.IsolatedLoadingProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.JournalProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.LanguageProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LikeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LocationProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LockProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LockingProperty'>: <Location.POST_ALIAS: 'POST_ALIAS'>, <class 'sqlglot.expressions.LogProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.MaterializedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.MergeBlockRatioProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.OnProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OnCommitProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.Order'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OutputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PartitionedByProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.PartitionedOfProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PrimaryKey'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Property'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ReturnsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatDelimitedProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatSerdeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SampleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SchemaCommentProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SecureProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.SecurityProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SerdeProperties'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Set'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SettingsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SetProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.SetConfigProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SharingProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.SequenceProperties'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.SortKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlReadWriteProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StabilityProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.StorageHandlerProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.StreamingTableProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StrictProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Tags'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.TemporaryProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.ToTableProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TransientProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.TransformModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.MergeTreeTTL'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.UnloggedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.UsingTemplateProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ViewAttributeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.VolatileProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.WithDataProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.WithProcedureOptions'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.WithSchemaBindingProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.WithSystemVersioningProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ForceProperty'>: <Location.POST_CREATE: 'POST_CREATE'>}
RESERVED_KEYWORDS: Set[str] = set()
WITH_SEPARATED_COMMENTS: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Command'>, <class 'sqlglot.expressions.Create'>, <class 'sqlglot.expressions.Describe'>, <class 'sqlglot.expressions.Delete'>, <class 'sqlglot.expressions.Drop'>, <class 'sqlglot.expressions.From'>, <class 'sqlglot.expressions.Insert'>, <class 'sqlglot.expressions.Join'>, <class 'sqlglot.expressions.MultitableInserts'>, <class 'sqlglot.expressions.Select'>, <class 'sqlglot.expressions.SetOperation'>, <class 'sqlglot.expressions.Update'>, <class 'sqlglot.expressions.Where'>, <class 'sqlglot.expressions.With'>)
EXCLUDE_COMMENTS: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Binary'>, <class 'sqlglot.expressions.SetOperation'>)
UNWRAPPED_INTERVAL_VALUES: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Column'>, <class 'sqlglot.expressions.Literal'>, <class 'sqlglot.expressions.Neg'>, <class 'sqlglot.expressions.Paren'>)
PARAMETERIZABLE_TEXT_TYPES = {<Type.NVARCHAR: 'NVARCHAR'>, <Type.CHAR: 'CHAR'>, <Type.VARCHAR: 'VARCHAR'>, <Type.NCHAR: 'NCHAR'>}
EXPRESSIONS_WITHOUT_NESTED_CTES: Set[Type[sqlglot.expressions.Expression]] = set()
RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS: Tuple[Type[sqlglot.expressions.Expression], ...] = ()
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

    754    def generate(self, expression: exp.Expression, copy: bool = True) -> str:
    755        """
    756        Generates the SQL string corresponding to the given syntax tree.
    757
    758        Args:
    759            expression: The syntax tree.
    760            copy: Whether to copy the expression. The generator performs mutations so
    761                it is safer to copy.
    762
    763        Returns:
    764            The SQL string corresponding to `expression`.
    765        """
    766        if copy:
    767            expression = expression.copy()
    768
    769        expression = self.preprocess(expression)
    770
    771        self.unsupported_messages = []
    772        sql = self.sql(expression).strip()
    773
    774        if self.pretty:
    775            sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n")
    776
    777        if self.unsupported_level == ErrorLevel.IGNORE:
    778            return sql
    779
    780        if self.unsupported_level == ErrorLevel.WARN:
    781            for msg in self.unsupported_messages:
    782                logger.warning(msg)
    783        elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages:
    784            raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported))
    785
    786        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

    788    def preprocess(self, expression: exp.Expression) -> exp.Expression:
    789        """Apply generic preprocessing transformations to a given expression."""
    790        expression = self._move_ctes_to_top_level(expression)
    791
    792        if self.ENSURE_BOOLS:
    793            from sqlglot.transforms import ensure_bools
    794
    795            expression = ensure_bools(expression)
    796
    797        return expression

Apply generic preprocessing transformations to a given expression.

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

    810    def unsupported(self, message: str) -> None:
    811        if self.unsupported_level == ErrorLevel.IMMEDIATE:
    812            raise UnsupportedError(message)
    813        self.unsupported_messages.append(message)

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

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

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

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

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

    821    def sanitize_comment(self, comment: str) -> str:
    822        comment = " " + comment if comment[0].strip() else comment
    823        comment = comment + " " if comment[-1].strip() else comment
    824
    825        if not self.dialect.tokenizer_class.NESTED_COMMENTS:
    826            # Necessary workaround to avoid syntax errors due to nesting: /* ... */ ... */
    827            comment = comment.replace("*/", "* /")
    828
    829        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

    831    def maybe_comment(
    832        self,
    833        sql: str,
    834        expression: t.Optional[exp.Expression] = None,
    835        comments: t.Optional[t.List[str]] = None,
    836        separated: bool = False,
    837    ) -> str:
    838        comments = (
    839            ((expression and expression.comments) if comments is None else comments)  # type: ignore
    840            if self.comments
    841            else None
    842        )
    843
    844        if not comments or isinstance(expression, self.EXCLUDE_COMMENTS):
    845            return sql
    846
    847        comments_sql = " ".join(
    848            f"/*{self.sanitize_comment(comment)}*/" for comment in comments if comment
    849        )
    850
    851        if not comments_sql:
    852            return sql
    853
    854        comments_sql = self._replace_line_breaks(comments_sql)
    855
    856        if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS):
    857            return (
    858                f"{self.sep()}{comments_sql}{sql}"
    859                if not sql or sql[0].isspace()
    860                else f"{comments_sql}{self.sep()}{sql}"
    861            )
    862
    863        return f"{sql} {comments_sql}"

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

    865    def wrap(self, expression: exp.Expression | str) -> str:
    866        this_sql = (
    867            self.sql(expression)
    868            if isinstance(expression, exp.UNWRAPPED_QUERIES)
    869            else self.sql(expression, "this")
    870        )
    871        if not this_sql:
    872            return "()"
    873
    874        this_sql = self.indent(this_sql, level=1, pad=0)
    875        return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"

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

    877    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
    878        original = self.identify
    879        self.identify = False
    880        result = func(*args, **kwargs)
    881        self.identify = original
    882        return result

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

    884    def normalize_func(self, name: str) -> str:
    885        if self.normalize_functions == "upper" or self.normalize_functions is True:
    886            return name.upper()
    887        if self.normalize_functions == "lower":
    888            return name.lower()
    889        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

    891    def indent(
    892        self,
    893        sql: str,
    894        level: int = 0,
    895        pad: t.Optional[int] = None,
    896        skip_first: bool = False,
    897        skip_last: bool = False,
    898    ) -> str:
    899        if not self.pretty or not sql:
    900            return sql
    901
    902        pad = self.pad if pad is None else pad
    903        lines = sql.split("\n")
    904
    905        return "\n".join(
    906            (
    907                line
    908                if (skip_first and i == 0) or (skip_last and i == len(lines) - 1)
    909                else f"{' ' * (level * self._indent + pad)}{line}"
    910            )
    911            for i, line in enumerate(lines)
    912        )

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

    914    def sql(
    915        self,
    916        expression: t.Optional[str | exp.Expression],
    917        key: t.Optional[str] = None,
    918        comment: bool = True,
    919    ) -> str:
    920        if not expression:
    921            return ""
    922
    923        if isinstance(expression, str):
    924            return expression
    925
    926        if key:
    927            value = expression.args.get(key)
    928            if value:
    929                return self.sql(value)
    930            return ""
    931
    932        transform = self.TRANSFORMS.get(expression.__class__)
    933
    934        if callable(transform):
    935            sql = transform(self, expression)
    936        elif isinstance(expression, exp.Expression):
    937            exp_handler_name = f"{expression.key}_sql"
    938
    939            if hasattr(self, exp_handler_name):
    940                sql = getattr(self, exp_handler_name)(expression)
    941            elif isinstance(expression, exp.Func):
    942                sql = self.function_fallback_sql(expression)
    943            elif isinstance(expression, exp.Property):
    944                sql = self.property_sql(expression)
    945            else:
    946                raise ValueError(f"Unsupported expression type {expression.__class__.__name__}")
    947        else:
    948            raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}")
    949
    950        return self.maybe_comment(sql, expression) if self.comments and comment else sql

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

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

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

    957    def cache_sql(self, expression: exp.Cache) -> str:
    958        lazy = " LAZY" if expression.args.get("lazy") else ""
    959        table = self.sql(expression, "this")
    960        options = expression.args.get("options")
    961        options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else ""
    962        sql = self.sql(expression, "expression")
    963        sql = f" AS{self.sep()}{sql}" if sql else ""
    964        sql = f"CACHE{lazy} TABLE {table}{options}{sql}"
    965        return self.prepend_ctes(expression, sql)

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

    967    def characterset_sql(self, expression: exp.CharacterSet) -> str:
    968        if isinstance(expression.parent, exp.Cast):
    969            return f"CHAR CHARACTER SET {self.sql(expression, 'this')}"
    970        default = "DEFAULT " if expression.args.get("default") else ""
    971        return f"{default}CHARACTER SET={self.sql(expression, 'this')}"

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

    973    def column_parts(self, expression: exp.Column) -> str:
    974        return ".".join(
    975            self.sql(part)
    976            for part in (
    977                expression.args.get("catalog"),
    978                expression.args.get("db"),
    979                expression.args.get("table"),
    980                expression.args.get("this"),
    981            )
    982            if part
    983        )

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

    985    def column_sql(self, expression: exp.Column) -> str:
    986        join_mark = " (+)" if expression.args.get("join_mark") else ""
    987
    988        if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS:
    989            join_mark = ""
    990            self.unsupported("Outer join syntax using the (+) operator is not supported.")
    991
    992        return f"{self.column_parts(expression)}{join_mark}"

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

    994    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
    995        this = self.sql(expression, "this")
    996        this = f" {this}" if this else ""
    997        position = self.sql(expression, "position")
    998        return f"{position}{this}"

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

    1000    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
    1001        column = self.sql(expression, "this")
    1002        kind = self.sql(expression, "kind")
    1003        constraints = self.expressions(expression, key="constraints", sep=" ", flat=True)
    1004        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
    1005        kind = f"{sep}{kind}" if kind else ""
    1006        constraints = f" {constraints}" if constraints else ""
    1007        position = self.sql(expression, "position")
    1008        position = f" {position}" if position else ""
    1009
    1010        if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE:
    1011            kind = ""
    1012
    1013        return f"{exists}{column}{kind}{constraints}{position}"

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

    1015    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
    1016        this = self.sql(expression, "this")
    1017        kind_sql = self.sql(expression, "kind").strip()
    1018        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql

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

    1020    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
    1021        this = self.sql(expression, "this")
    1022        if expression.args.get("not_null"):
    1023            persisted = " PERSISTED NOT NULL"
    1024        elif expression.args.get("persisted"):
    1025            persisted = " PERSISTED"
    1026        else:
    1027            persisted = ""
    1028
    1029        return f"AS {this}{persisted}"

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

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

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

    1034    def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str:
    1035        if isinstance(expression.this, list):
    1036            this = self.wrap(self.expressions(expression, key="this", flat=True))
    1037        else:
    1038            this = self.sql(expression, "this")
    1039
    1040        return f"COMPRESS {this}"

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

    1042    def generatedasidentitycolumnconstraint_sql(
    1043        self, expression: exp.GeneratedAsIdentityColumnConstraint
    1044    ) -> str:
    1045        this = ""
    1046        if expression.this is not None:
    1047            on_null = " ON NULL" if expression.args.get("on_null") else ""
    1048            this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}"
    1049
    1050        start = expression.args.get("start")
    1051        start = f"START WITH {start}" if start else ""
    1052        increment = expression.args.get("increment")
    1053        increment = f" INCREMENT BY {increment}" if increment else ""
    1054        minvalue = expression.args.get("minvalue")
    1055        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    1056        maxvalue = expression.args.get("maxvalue")
    1057        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    1058        cycle = expression.args.get("cycle")
    1059        cycle_sql = ""
    1060
    1061        if cycle is not None:
    1062            cycle_sql = f"{' NO' if not cycle else ''} CYCLE"
    1063            cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql
    1064
    1065        sequence_opts = ""
    1066        if start or increment or cycle_sql:
    1067            sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}"
    1068            sequence_opts = f" ({sequence_opts.strip()})"
    1069
    1070        expr = self.sql(expression, "expression")
    1071        expr = f"({expr})" if expr else "IDENTITY"
    1072
    1073        return f"GENERATED{this} AS {expr}{sequence_opts}"

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

    1075    def generatedasrowcolumnconstraint_sql(
    1076        self, expression: exp.GeneratedAsRowColumnConstraint
    1077    ) -> str:
    1078        start = "START" if expression.args.get("start") else "END"
    1079        hidden = " HIDDEN" if expression.args.get("hidden") else ""
    1080        return f"GENERATED ALWAYS AS ROW {start}{hidden}"

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

    1082    def periodforsystemtimeconstraint_sql(
    1083        self, expression: exp.PeriodForSystemTimeConstraint
    1084    ) -> str:
    1085        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

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

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

    1090    def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str:
    1091        desc = expression.args.get("desc")
    1092        if desc is not None:
    1093            return f"PRIMARY KEY{' DESC' if desc else ' ASC'}"
    1094        options = self.expressions(expression, key="options", flat=True, sep=" ")
    1095        options = f" {options}" if options else ""
    1096        return f"PRIMARY KEY{options}"

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

    1098    def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str:
    1099        this = self.sql(expression, "this")
    1100        this = f" {this}" if this else ""
    1101        index_type = expression.args.get("index_type")
    1102        index_type = f" USING {index_type}" if index_type else ""
    1103        on_conflict = self.sql(expression, "on_conflict")
    1104        on_conflict = f" {on_conflict}" if on_conflict else ""
    1105        nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else ""
    1106        options = self.expressions(expression, key="options", flat=True, sep=" ")
    1107        options = f" {options}" if options else ""
    1108        return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}{options}"

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

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

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

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

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

    1222    def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str:
    1223        start = self.sql(expression, "start")
    1224        start = f"START WITH {start}" if start else ""
    1225        increment = self.sql(expression, "increment")
    1226        increment = f" INCREMENT BY {increment}" if increment else ""
    1227        minvalue = self.sql(expression, "minvalue")
    1228        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    1229        maxvalue = self.sql(expression, "maxvalue")
    1230        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    1231        owned = self.sql(expression, "owned")
    1232        owned = f" OWNED BY {owned}" if owned else ""
    1233
    1234        cache = expression.args.get("cache")
    1235        if cache is None:
    1236            cache_str = ""
    1237        elif cache is True:
    1238            cache_str = " CACHE"
    1239        else:
    1240            cache_str = f" CACHE {cache}"
    1241
    1242        options = self.expressions(expression, key="options", flat=True, sep=" ")
    1243        options = f" {options}" if options else ""
    1244
    1245        return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip()

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

    1247    def clone_sql(self, expression: exp.Clone) -> str:
    1248        this = self.sql(expression, "this")
    1249        shallow = "SHALLOW " if expression.args.get("shallow") else ""
    1250        keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE"
    1251        return f"{shallow}{keyword} {this}"

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

    1253    def describe_sql(self, expression: exp.Describe) -> str:
    1254        style = expression.args.get("style")
    1255        style = f" {style}" if style else ""
    1256        partition = self.sql(expression, "partition")
    1257        partition = f" {partition}" if partition else ""
    1258        format = self.sql(expression, "format")
    1259        format = f" {format}" if format else ""
    1260
    1261        return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}"

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

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

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

    1267    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
    1268        with_ = self.sql(expression, "with")
    1269        if with_:
    1270            sql = f"{with_}{self.sep()}{sql}"
    1271        return sql

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

    1273    def with_sql(self, expression: exp.With) -> str:
    1274        sql = self.expressions(expression, flat=True)
    1275        recursive = (
    1276            "RECURSIVE "
    1277            if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive")
    1278            else ""
    1279        )
    1280        search = self.sql(expression, "search")
    1281        search = f" {search}" if search else ""
    1282
    1283        return f"WITH {recursive}{sql}{search}"

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

    1285    def cte_sql(self, expression: exp.CTE) -> str:
    1286        alias = expression.args.get("alias")
    1287        if alias:
    1288            alias.add_comments(expression.pop_comments())
    1289
    1290        alias_sql = self.sql(expression, "alias")
    1291
    1292        materialized = expression.args.get("materialized")
    1293        if materialized is False:
    1294            materialized = "NOT MATERIALIZED "
    1295        elif materialized:
    1296            materialized = "MATERIALIZED "
    1297
    1298        return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}"

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

    1300    def tablealias_sql(self, expression: exp.TableAlias) -> str:
    1301        alias = self.sql(expression, "this")
    1302        columns = self.expressions(expression, key="columns", flat=True)
    1303        columns = f"({columns})" if columns else ""
    1304
    1305        if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS:
    1306            columns = ""
    1307            self.unsupported("Named columns are not supported in table alias.")
    1308
    1309        if not alias and not self.dialect.UNNEST_COLUMN_ONLY:
    1310            alias = self._next_name()
    1311
    1312        return f"{alias}{columns}"

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

    1314    def bitstring_sql(self, expression: exp.BitString) -> str:
    1315        this = self.sql(expression, "this")
    1316        if self.dialect.BIT_START:
    1317            return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}"
    1318        return f"{int(this, 2)}"

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

    1320    def hexstring_sql(
    1321        self, expression: exp.HexString, binary_function_repr: t.Optional[str] = None
    1322    ) -> str:
    1323        this = self.sql(expression, "this")
    1324        is_integer_type = expression.args.get("is_integer")
    1325
    1326        if (is_integer_type and not self.dialect.HEX_STRING_IS_INTEGER_TYPE) or (
    1327            not self.dialect.HEX_START and not binary_function_repr
    1328        ):
    1329            # Integer representation will be returned if:
    1330            # - The read dialect treats the hex value as integer literal but not the write
    1331            # - The transpilation is not supported (write dialect hasn't set HEX_START or the param flag)
    1332            return f"{int(this, 16)}"
    1333
    1334        if not is_integer_type:
    1335            # Read dialect treats the hex value as BINARY/BLOB
    1336            if binary_function_repr:
    1337                # The write dialect supports the transpilation to its equivalent BINARY/BLOB
    1338                return self.func(binary_function_repr, exp.Literal.string(this))
    1339            if self.dialect.HEX_STRING_IS_INTEGER_TYPE:
    1340                # The write dialect does not support the transpilation, it'll treat the hex value as INTEGER
    1341                self.unsupported("Unsupported transpilation from BINARY/BLOB hex string")
    1342
    1343        return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"

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

    1345    def bytestring_sql(self, expression: exp.ByteString) -> str:
    1346        this = self.sql(expression, "this")
    1347        if self.dialect.BYTE_START:
    1348            return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}"
    1349        return this

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

    1351    def unicodestring_sql(self, expression: exp.UnicodeString) -> str:
    1352        this = self.sql(expression, "this")
    1353        escape = expression.args.get("escape")
    1354
    1355        if self.dialect.UNICODE_START:
    1356            escape_substitute = r"\\\1"
    1357            left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END
    1358        else:
    1359            escape_substitute = r"\\u\1"
    1360            left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END
    1361
    1362        if escape:
    1363            escape_pattern = re.compile(rf"{escape.name}(\d+)")
    1364            escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else ""
    1365        else:
    1366            escape_pattern = ESCAPED_UNICODE_RE
    1367            escape_sql = ""
    1368
    1369        if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE):
    1370            this = escape_pattern.sub(escape_substitute, this)
    1371
    1372        return f"{left_quote}{this}{right_quote}{escape_sql}"

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

    1374    def rawstring_sql(self, expression: exp.RawString) -> str:
    1375        string = expression.this
    1376        if "\\" in self.dialect.tokenizer_class.STRING_ESCAPES:
    1377            string = string.replace("\\", "\\\\")
    1378
    1379        string = self.escape_str(string, escape_backslash=False)
    1380        return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}"

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

    1382    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
    1383        this = self.sql(expression, "this")
    1384        specifier = self.sql(expression, "expression")
    1385        specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else ""
    1386        return f"{this}{specifier}"

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

    1388    def datatype_sql(self, expression: exp.DataType) -> str:
    1389        nested = ""
    1390        values = ""
    1391        interior = self.expressions(expression, flat=True)
    1392
    1393        type_value = expression.this
    1394        if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"):
    1395            type_sql = self.sql(expression, "kind")
    1396        else:
    1397            type_sql = (
    1398                self.TYPE_MAPPING.get(type_value, type_value.value)
    1399                if isinstance(type_value, exp.DataType.Type)
    1400                else type_value
    1401            )
    1402
    1403        if interior:
    1404            if expression.args.get("nested"):
    1405                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
    1406                if expression.args.get("values") is not None:
    1407                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
    1408                    values = self.expressions(expression, key="values", flat=True)
    1409                    values = f"{delimiters[0]}{values}{delimiters[1]}"
    1410            elif type_value == exp.DataType.Type.INTERVAL:
    1411                nested = f" {interior}"
    1412            else:
    1413                nested = f"({interior})"
    1414
    1415        type_sql = f"{type_sql}{nested}{values}"
    1416        if self.TZ_TO_WITH_TIME_ZONE and type_value in (
    1417            exp.DataType.Type.TIMETZ,
    1418            exp.DataType.Type.TIMESTAMPTZ,
    1419        ):
    1420            type_sql = f"{type_sql} WITH TIME ZONE"
    1421
    1422        return type_sql

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

    1424    def directory_sql(self, expression: exp.Directory) -> str:
    1425        local = "LOCAL " if expression.args.get("local") else ""
    1426        row_format = self.sql(expression, "row_format")
    1427        row_format = f" {row_format}" if row_format else ""
    1428        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"

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

    1430    def delete_sql(self, expression: exp.Delete) -> str:
    1431        this = self.sql(expression, "this")
    1432        this = f" FROM {this}" if this else ""
    1433        using = self.sql(expression, "using")
    1434        using = f" USING {using}" if using else ""
    1435        cluster = self.sql(expression, "cluster")
    1436        cluster = f" {cluster}" if cluster else ""
    1437        where = self.sql(expression, "where")
    1438        returning = self.sql(expression, "returning")
    1439        limit = self.sql(expression, "limit")
    1440        tables = self.expressions(expression, key="tables")
    1441        tables = f" {tables}" if tables else ""
    1442        if self.RETURNING_END:
    1443            expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}"
    1444        else:
    1445            expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}"
    1446        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")

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

    1448    def drop_sql(self, expression: exp.Drop) -> str:
    1449        this = self.sql(expression, "this")
    1450        expressions = self.expressions(expression, flat=True)
    1451        expressions = f" ({expressions})" if expressions else ""
    1452        kind = expression.args["kind"]
    1453        kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind
    1454        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    1455        concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else ""
    1456        on_cluster = self.sql(expression, "cluster")
    1457        on_cluster = f" {on_cluster}" if on_cluster else ""
    1458        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    1459        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    1460        cascade = " CASCADE" if expression.args.get("cascade") else ""
    1461        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
    1462        purge = " PURGE" if expression.args.get("purge") else ""
    1463        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

    1465    def set_operation(self, expression: exp.SetOperation) -> str:
    1466        op_type = type(expression)
    1467        op_name = op_type.key.upper()
    1468
    1469        distinct = expression.args.get("distinct")
    1470        if (
    1471            distinct is False
    1472            and op_type in (exp.Except, exp.Intersect)
    1473            and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE
    1474        ):
    1475            self.unsupported(f"{op_name} ALL is not supported")
    1476
    1477        default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type]
    1478
    1479        if distinct is None:
    1480            distinct = default_distinct
    1481            if distinct is None:
    1482                self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified")
    1483
    1484        if distinct is default_distinct:
    1485            distinct_or_all = ""
    1486        else:
    1487            distinct_or_all = " DISTINCT" if distinct else " ALL"
    1488
    1489        side_kind = " ".join(filter(None, [expression.side, expression.kind]))
    1490        side_kind = f"{side_kind} " if side_kind else ""
    1491
    1492        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1493        on = self.expressions(expression, key="on", flat=True)
    1494        on = f" ON ({on})" if on else ""
    1495
    1496        return f"{side_kind}{op_name}{distinct_or_all}{by_name}{on}"

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

    1498    def set_operations(self, expression: exp.SetOperation) -> str:
    1499        if not self.SET_OP_MODIFIERS:
    1500            limit = expression.args.get("limit")
    1501            order = expression.args.get("order")
    1502
    1503            if limit or order:
    1504                select = self._move_ctes_to_top_level(
    1505                    exp.subquery(expression, "_l_0", copy=False).select("*", copy=False)
    1506                )
    1507
    1508                if limit:
    1509                    select = select.limit(limit.pop(), copy=False)
    1510                if order:
    1511                    select = select.order_by(order.pop(), copy=False)
    1512                return self.sql(select)
    1513
    1514        sqls: t.List[str] = []
    1515        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    1516
    1517        while stack:
    1518            node = stack.pop()
    1519
    1520            if isinstance(node, exp.SetOperation):
    1521                stack.append(node.expression)
    1522                stack.append(
    1523                    self.maybe_comment(
    1524                        self.set_operation(node), comments=node.comments, separated=True
    1525                    )
    1526                )
    1527                stack.append(node.this)
    1528            else:
    1529                sqls.append(self.sql(node))
    1530
    1531        this = self.sep().join(sqls)
    1532        this = self.query_modifiers(expression, this)
    1533        return self.prepend_ctes(expression, this)

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

    1535    def fetch_sql(self, expression: exp.Fetch) -> str:
    1536        direction = expression.args.get("direction")
    1537        direction = f" {direction}" if direction else ""
    1538        count = self.sql(expression, "count")
    1539        count = f" {count}" if count else ""
    1540        limit_options = self.sql(expression, "limit_options")
    1541        limit_options = f"{limit_options}" if limit_options else " ROWS ONLY"
    1542        return f"{self.seg('FETCH')}{direction}{count}{limit_options}"

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

    1544    def limitoptions_sql(self, expression: exp.LimitOptions) -> str:
    1545        percent = " PERCENT" if expression.args.get("percent") else ""
    1546        rows = " ROWS" if expression.args.get("rows") else ""
    1547        with_ties = " WITH TIES" if expression.args.get("with_ties") else ""
    1548        if not with_ties and rows:
    1549            with_ties = " ONLY"
    1550        return f"{percent}{rows}{with_ties}"

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

    1552    def filter_sql(self, expression: exp.Filter) -> str:
    1553        if self.AGGREGATE_FILTER_SUPPORTED:
    1554            this = self.sql(expression, "this")
    1555            where = self.sql(expression, "expression").strip()
    1556            return f"{this} FILTER({where})"
    1557
    1558        agg = expression.this
    1559        agg_arg = agg.this
    1560        cond = expression.expression.this
    1561        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
    1562        return self.sql(agg)

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

    1564    def hint_sql(self, expression: exp.Hint) -> str:
    1565        if not self.QUERY_HINTS:
    1566            self.unsupported("Hints are not supported")
    1567            return ""
    1568
    1569        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"

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

    1571    def indexparameters_sql(self, expression: exp.IndexParameters) -> str:
    1572        using = self.sql(expression, "using")
    1573        using = f" USING {using}" if using else ""
    1574        columns = self.expressions(expression, key="columns", flat=True)
    1575        columns = f"({columns})" if columns else ""
    1576        partition_by = self.expressions(expression, key="partition_by", flat=True)
    1577        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
    1578        where = self.sql(expression, "where")
    1579        include = self.expressions(expression, key="include", flat=True)
    1580        if include:
    1581            include = f" INCLUDE ({include})"
    1582        with_storage = self.expressions(expression, key="with_storage", flat=True)
    1583        with_storage = f" WITH ({with_storage})" if with_storage else ""
    1584        tablespace = self.sql(expression, "tablespace")
    1585        tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else ""
    1586        on = self.sql(expression, "on")
    1587        on = f" ON {on}" if on else ""
    1588
    1589        return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"

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

    1591    def index_sql(self, expression: exp.Index) -> str:
    1592        unique = "UNIQUE " if expression.args.get("unique") else ""
    1593        primary = "PRIMARY " if expression.args.get("primary") else ""
    1594        amp = "AMP " if expression.args.get("amp") else ""
    1595        name = self.sql(expression, "this")
    1596        name = f"{name} " if name else ""
    1597        table = self.sql(expression, "table")
    1598        table = f"{self.INDEX_ON} {table}" if table else ""
    1599
    1600        index = "INDEX " if not table else ""
    1601
    1602        params = self.sql(expression, "params")
    1603        return f"{unique}{primary}{amp}{index}{name}{table}{params}"

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

    1605    def identifier_sql(self, expression: exp.Identifier) -> str:
    1606        text = expression.name
    1607        lower = text.lower()
    1608        text = lower if self.normalize and not expression.quoted else text
    1609        text = text.replace(self._identifier_end, self._escaped_identifier_end)
    1610        if (
    1611            expression.quoted
    1612            or self.dialect.can_identify(text, self.identify)
    1613            or lower in self.RESERVED_KEYWORDS
    1614            or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
    1615        ):
    1616            text = f"{self._identifier_start}{text}{self._identifier_end}"
    1617        return text

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

    1619    def hex_sql(self, expression: exp.Hex) -> str:
    1620        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1621        if self.dialect.HEX_LOWERCASE:
    1622            text = self.func("LOWER", text)
    1623
    1624        return text

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

    1626    def lowerhex_sql(self, expression: exp.LowerHex) -> str:
    1627        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1628        if not self.dialect.HEX_LOWERCASE:
    1629            text = self.func("LOWER", text)
    1630        return text

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

    1632    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    1633        input_format = self.sql(expression, "input_format")
    1634        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    1635        output_format = self.sql(expression, "output_format")
    1636        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    1637        return self.sep().join((input_format, output_format))

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

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

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

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

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

    1647    def properties_sql(self, expression: exp.Properties) -> str:
    1648        root_properties = []
    1649        with_properties = []
    1650
    1651        for p in expression.expressions:
    1652            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1653            if p_loc == exp.Properties.Location.POST_WITH:
    1654                with_properties.append(p)
    1655            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    1656                root_properties.append(p)
    1657
    1658        root_props = self.root_properties(exp.Properties(expressions=root_properties))
    1659        with_props = self.with_properties(exp.Properties(expressions=with_properties))
    1660
    1661        if root_props and with_props and not self.pretty:
    1662            with_props = " " + with_props
    1663
    1664        return root_props + with_props

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

    1666    def root_properties(self, properties: exp.Properties) -> str:
    1667        if properties.expressions:
    1668            return self.expressions(properties, indent=False, sep=" ")
    1669        return ""

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

    1671    def properties(
    1672        self,
    1673        properties: exp.Properties,
    1674        prefix: str = "",
    1675        sep: str = ", ",
    1676        suffix: str = "",
    1677        wrapped: bool = True,
    1678    ) -> str:
    1679        if properties.expressions:
    1680            expressions = self.expressions(properties, sep=sep, indent=False)
    1681            if expressions:
    1682                expressions = self.wrap(expressions) if wrapped else expressions
    1683                return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}"
    1684        return ""

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

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

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

    1689    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
    1690        properties_locs = defaultdict(list)
    1691        for p in properties.expressions:
    1692            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1693            if p_loc != exp.Properties.Location.UNSUPPORTED:
    1694                properties_locs[p_loc].append(p)
    1695            else:
    1696                self.unsupported(f"Unsupported property {p.key}")
    1697
    1698        return properties_locs

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

    1700    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
    1701        if isinstance(expression.this, exp.Dot):
    1702            return self.sql(expression, "this")
    1703        return f"'{expression.name}'" if string_key else expression.name

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

    1705    def property_sql(self, expression: exp.Property) -> str:
    1706        property_cls = expression.__class__
    1707        if property_cls == exp.Property:
    1708            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
    1709
    1710        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    1711        if not property_name:
    1712            self.unsupported(f"Unsupported property {expression.key}")
    1713
    1714        return f"{property_name}={self.sql(expression, 'this')}"

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

    1716    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
    1717        if self.SUPPORTS_CREATE_TABLE_LIKE:
    1718            options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
    1719            options = f" {options}" if options else ""
    1720
    1721            like = f"LIKE {self.sql(expression, 'this')}{options}"
    1722            if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema):
    1723                like = f"({like})"
    1724
    1725            return like
    1726
    1727        if expression.expressions:
    1728            self.unsupported("Transpilation of LIKE property options is unsupported")
    1729
    1730        select = exp.select("*").from_(expression.this).limit(0)
    1731        return f"AS {self.sql(select)}"

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

    1733    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1734        no = "NO " if expression.args.get("no") else ""
    1735        protection = " PROTECTION" if expression.args.get("protection") else ""
    1736        return f"{no}FALLBACK{protection}"

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

    1738    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1739        no = "NO " if expression.args.get("no") else ""
    1740        local = expression.args.get("local")
    1741        local = f"{local} " if local else ""
    1742        dual = "DUAL " if expression.args.get("dual") else ""
    1743        before = "BEFORE " if expression.args.get("before") else ""
    1744        after = "AFTER " if expression.args.get("after") else ""
    1745        return f"{no}{local}{dual}{before}{after}JOURNAL"

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

    1747    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1748        freespace = self.sql(expression, "this")
    1749        percent = " PERCENT" if expression.args.get("percent") else ""
    1750        return f"FREESPACE={freespace}{percent}"

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

    1752    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1753        if expression.args.get("default"):
    1754            property = "DEFAULT"
    1755        elif expression.args.get("on"):
    1756            property = "ON"
    1757        else:
    1758            property = "OFF"
    1759        return f"CHECKSUM={property}"

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

    1761    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1762        if expression.args.get("no"):
    1763            return "NO MERGEBLOCKRATIO"
    1764        if expression.args.get("default"):
    1765            return "DEFAULT MERGEBLOCKRATIO"
    1766
    1767        percent = " PERCENT" if expression.args.get("percent") else ""
    1768        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"

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

    1770    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1771        default = expression.args.get("default")
    1772        minimum = expression.args.get("minimum")
    1773        maximum = expression.args.get("maximum")
    1774        if default or minimum or maximum:
    1775            if default:
    1776                prop = "DEFAULT"
    1777            elif minimum:
    1778                prop = "MINIMUM"
    1779            else:
    1780                prop = "MAXIMUM"
    1781            return f"{prop} DATABLOCKSIZE"
    1782        units = expression.args.get("units")
    1783        units = f" {units}" if units else ""
    1784        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"

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

    1786    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1787        autotemp = expression.args.get("autotemp")
    1788        always = expression.args.get("always")
    1789        default = expression.args.get("default")
    1790        manual = expression.args.get("manual")
    1791        never = expression.args.get("never")
    1792
    1793        if autotemp is not None:
    1794            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1795        elif always:
    1796            prop = "ALWAYS"
    1797        elif default:
    1798            prop = "DEFAULT"
    1799        elif manual:
    1800            prop = "MANUAL"
    1801        elif never:
    1802            prop = "NEVER"
    1803        return f"BLOCKCOMPRESSION={prop}"

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

    1805    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1806        no = expression.args.get("no")
    1807        no = " NO" if no else ""
    1808        concurrent = expression.args.get("concurrent")
    1809        concurrent = " CONCURRENT" if concurrent else ""
    1810        target = self.sql(expression, "target")
    1811        target = f" {target}" if target else ""
    1812        return f"WITH{no}{concurrent} ISOLATED LOADING{target}"

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

    1814    def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str:
    1815        if isinstance(expression.this, list):
    1816            return f"IN ({self.expressions(expression, key='this', flat=True)})"
    1817        if expression.this:
    1818            modulus = self.sql(expression, "this")
    1819            remainder = self.sql(expression, "expression")
    1820            return f"WITH (MODULUS {modulus}, REMAINDER {remainder})"
    1821
    1822        from_expressions = self.expressions(expression, key="from_expressions", flat=True)
    1823        to_expressions = self.expressions(expression, key="to_expressions", flat=True)
    1824        return f"FROM ({from_expressions}) TO ({to_expressions})"

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

    1826    def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str:
    1827        this = self.sql(expression, "this")
    1828
    1829        for_values_or_default = expression.expression
    1830        if isinstance(for_values_or_default, exp.PartitionBoundSpec):
    1831            for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}"
    1832        else:
    1833            for_values_or_default = " DEFAULT"
    1834
    1835        return f"PARTITION OF {this}{for_values_or_default}"

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

    1837    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1838        kind = expression.args.get("kind")
    1839        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1840        for_or_in = expression.args.get("for_or_in")
    1841        for_or_in = f" {for_or_in}" if for_or_in else ""
    1842        lock_type = expression.args.get("lock_type")
    1843        override = " OVERRIDE" if expression.args.get("override") else ""
    1844        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"

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

    1846    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1847        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1848        statistics = expression.args.get("statistics")
    1849        statistics_sql = ""
    1850        if statistics is not None:
    1851            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1852        return f"{data_sql}{statistics_sql}"

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

    1854    def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str:
    1855        this = self.sql(expression, "this")
    1856        this = f"HISTORY_TABLE={this}" if this else ""
    1857        data_consistency: t.Optional[str] = self.sql(expression, "data_consistency")
    1858        data_consistency = (
    1859            f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None
    1860        )
    1861        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    1862        retention_period = (
    1863            f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None
    1864        )
    1865
    1866        if this:
    1867            on_sql = self.func("ON", this, data_consistency, retention_period)
    1868        else:
    1869            on_sql = "ON" if expression.args.get("on") else "OFF"
    1870
    1871        sql = f"SYSTEM_VERSIONING={on_sql}"
    1872
    1873        return f"WITH({sql})" if expression.args.get("with") else sql

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

    1875    def insert_sql(self, expression: exp.Insert) -> str:
    1876        hint = self.sql(expression, "hint")
    1877        overwrite = expression.args.get("overwrite")
    1878
    1879        if isinstance(expression.this, exp.Directory):
    1880            this = " OVERWRITE" if overwrite else " INTO"
    1881        else:
    1882            this = self.INSERT_OVERWRITE if overwrite else " INTO"
    1883
    1884        stored = self.sql(expression, "stored")
    1885        stored = f" {stored}" if stored else ""
    1886        alternative = expression.args.get("alternative")
    1887        alternative = f" OR {alternative}" if alternative else ""
    1888        ignore = " IGNORE" if expression.args.get("ignore") else ""
    1889        is_function = expression.args.get("is_function")
    1890        if is_function:
    1891            this = f"{this} FUNCTION"
    1892        this = f"{this} {self.sql(expression, 'this')}"
    1893
    1894        exists = " IF EXISTS" if expression.args.get("exists") else ""
    1895        where = self.sql(expression, "where")
    1896        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
    1897        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
    1898        on_conflict = self.sql(expression, "conflict")
    1899        on_conflict = f" {on_conflict}" if on_conflict else ""
    1900        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1901        returning = self.sql(expression, "returning")
    1902
    1903        if self.RETURNING_END:
    1904            expression_sql = f"{expression_sql}{on_conflict}{returning}"
    1905        else:
    1906            expression_sql = f"{returning}{expression_sql}{on_conflict}"
    1907
    1908        partition_by = self.sql(expression, "partition")
    1909        partition_by = f" {partition_by}" if partition_by else ""
    1910        settings = self.sql(expression, "settings")
    1911        settings = f" {settings}" if settings else ""
    1912
    1913        source = self.sql(expression, "source")
    1914        source = f"TABLE {source}" if source else ""
    1915
    1916        sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}"
    1917        return self.prepend_ctes(expression, sql)

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

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

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

    1922    def kill_sql(self, expression: exp.Kill) -> str:
    1923        kind = self.sql(expression, "kind")
    1924        kind = f" {kind}" if kind else ""
    1925        this = self.sql(expression, "this")
    1926        this = f" {this}" if this else ""
    1927        return f"KILL{kind}{this}"

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

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

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

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

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

    1935    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1936        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1937
    1938        constraint = self.sql(expression, "constraint")
    1939        constraint = f" ON CONSTRAINT {constraint}" if constraint else ""
    1940
    1941        conflict_keys = self.expressions(expression, key="conflict_keys", flat=True)
    1942        conflict_keys = f"({conflict_keys}) " if conflict_keys else " "
    1943        action = self.sql(expression, "action")
    1944
    1945        expressions = self.expressions(expression, flat=True)
    1946        if expressions:
    1947            set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
    1948            expressions = f" {set_keyword}{expressions}"
    1949
    1950        where = self.sql(expression, "where")
    1951        return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}"

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

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

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

    1956    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1957        fields = self.sql(expression, "fields")
    1958        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1959        escaped = self.sql(expression, "escaped")
    1960        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1961        items = self.sql(expression, "collection_items")
    1962        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1963        keys = self.sql(expression, "map_keys")
    1964        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1965        lines = self.sql(expression, "lines")
    1966        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1967        null = self.sql(expression, "null")
    1968        null = f" NULL DEFINED AS {null}" if null else ""
    1969        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"

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

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

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

    1974    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1975        this = f"{self.sql(expression, 'this')} INDEX"
    1976        target = self.sql(expression, "target")
    1977        target = f" FOR {target}" if target else ""
    1978        return f"{this}{target} ({self.expressions(expression, flat=True)})"

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

    1980    def historicaldata_sql(self, expression: exp.HistoricalData) -> str:
    1981        this = self.sql(expression, "this")
    1982        kind = self.sql(expression, "kind")
    1983        expr = self.sql(expression, "expression")
    1984        return f"{this} ({kind} => {expr})"

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

    1986    def table_parts(self, expression: exp.Table) -> str:
    1987        return ".".join(
    1988            self.sql(part)
    1989            for part in (
    1990                expression.args.get("catalog"),
    1991                expression.args.get("db"),
    1992                expression.args.get("this"),
    1993            )
    1994            if part is not None
    1995        )

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

    1997    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1998        table = self.table_parts(expression)
    1999        only = "ONLY " if expression.args.get("only") else ""
    2000        partition = self.sql(expression, "partition")
    2001        partition = f" {partition}" if partition else ""
    2002        version = self.sql(expression, "version")
    2003        version = f" {version}" if version else ""
    2004        alias = self.sql(expression, "alias")
    2005        alias = f"{sep}{alias}" if alias else ""
    2006
    2007        sample = self.sql(expression, "sample")
    2008        if self.dialect.ALIAS_POST_TABLESAMPLE:
    2009            sample_pre_alias = sample
    2010            sample_post_alias = ""
    2011        else:
    2012            sample_pre_alias = ""
    2013            sample_post_alias = sample
    2014
    2015        hints = self.expressions(expression, key="hints", sep=" ")
    2016        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
    2017        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    2018        joins = self.indent(
    2019            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
    2020        )
    2021        laterals = self.expressions(expression, key="laterals", sep="")
    2022
    2023        file_format = self.sql(expression, "format")
    2024        if file_format:
    2025            pattern = self.sql(expression, "pattern")
    2026            pattern = f", PATTERN => {pattern}" if pattern else ""
    2027            file_format = f" (FILE_FORMAT => {file_format}{pattern})"
    2028
    2029        ordinality = expression.args.get("ordinality") or ""
    2030        if ordinality:
    2031            ordinality = f" WITH ORDINALITY{alias}"
    2032            alias = ""
    2033
    2034        when = self.sql(expression, "when")
    2035        if when:
    2036            table = f"{table} {when}"
    2037
    2038        changes = self.sql(expression, "changes")
    2039        changes = f" {changes}" if changes else ""
    2040
    2041        rows_from = self.expressions(expression, key="rows_from")
    2042        if rows_from:
    2043            table = f"ROWS FROM {self.wrap(rows_from)}"
    2044
    2045        return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}"

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

    2047    def tablefromrows_sql(self, expression: exp.TableFromRows) -> str:
    2048        table = self.func("TABLE", expression.this)
    2049        alias = self.sql(expression, "alias")
    2050        alias = f" AS {alias}" if alias else ""
    2051        sample = self.sql(expression, "sample")
    2052        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    2053        joins = self.indent(
    2054            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
    2055        )
    2056        return f"{table}{alias}{pivots}{sample}{joins}"

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

    2058    def tablesample_sql(
    2059        self,
    2060        expression: exp.TableSample,
    2061        tablesample_keyword: t.Optional[str] = None,
    2062    ) -> str:
    2063        method = self.sql(expression, "method")
    2064        method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    2065        numerator = self.sql(expression, "bucket_numerator")
    2066        denominator = self.sql(expression, "bucket_denominator")
    2067        field = self.sql(expression, "bucket_field")
    2068        field = f" ON {field}" if field else ""
    2069        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    2070        seed = self.sql(expression, "seed")
    2071        seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else ""
    2072
    2073        size = self.sql(expression, "size")
    2074        if size and self.TABLESAMPLE_SIZE_IS_ROWS:
    2075            size = f"{size} ROWS"
    2076
    2077        percent = self.sql(expression, "percent")
    2078        if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT:
    2079            percent = f"{percent} PERCENT"
    2080
    2081        expr = f"{bucket}{percent}{size}"
    2082        if self.TABLESAMPLE_REQUIRES_PARENS:
    2083            expr = f"({expr})"
    2084
    2085        return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}"

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

    2087    def pivot_sql(self, expression: exp.Pivot) -> str:
    2088        expressions = self.expressions(expression, flat=True)
    2089        direction = "UNPIVOT" if expression.unpivot else "PIVOT"
    2090
    2091        group = self.sql(expression, "group")
    2092
    2093        if expression.this:
    2094            this = self.sql(expression, "this")
    2095            if not expressions:
    2096                return f"UNPIVOT {this}"
    2097
    2098            on = f"{self.seg('ON')} {expressions}"
    2099            into = self.sql(expression, "into")
    2100            into = f"{self.seg('INTO')} {into}" if into else ""
    2101            using = self.expressions(expression, key="using", flat=True)
    2102            using = f"{self.seg('USING')} {using}" if using else ""
    2103            return f"{direction} {this}{on}{into}{using}{group}"
    2104
    2105        alias = self.sql(expression, "alias")
    2106        alias = f" AS {alias}" if alias else ""
    2107
    2108        fields = self.expressions(
    2109            expression,
    2110            "fields",
    2111            sep=" ",
    2112            dynamic=True,
    2113            new_line=True,
    2114            skip_first=True,
    2115            skip_last=True,
    2116        )
    2117
    2118        include_nulls = expression.args.get("include_nulls")
    2119        if include_nulls is not None:
    2120            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
    2121        else:
    2122            nulls = ""
    2123
    2124        default_on_null = self.sql(expression, "default_on_null")
    2125        default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else ""
    2126        return f"{self.seg(direction)}{nulls}({expressions} FOR {fields}{default_on_null}{group}){alias}"

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

    2128    def version_sql(self, expression: exp.Version) -> str:
    2129        this = f"FOR {expression.name}"
    2130        kind = expression.text("kind")
    2131        expr = self.sql(expression, "expression")
    2132        return f"{this} {kind} {expr}"

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

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

    2137    def update_sql(self, expression: exp.Update) -> str:
    2138        this = self.sql(expression, "this")
    2139        set_sql = self.expressions(expression, flat=True)
    2140        from_sql = self.sql(expression, "from")
    2141        where_sql = self.sql(expression, "where")
    2142        returning = self.sql(expression, "returning")
    2143        order = self.sql(expression, "order")
    2144        limit = self.sql(expression, "limit")
    2145        if self.RETURNING_END:
    2146            expression_sql = f"{from_sql}{where_sql}{returning}"
    2147        else:
    2148            expression_sql = f"{returning}{from_sql}{where_sql}"
    2149        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
    2150        return self.prepend_ctes(expression, sql)

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

    2152    def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str:
    2153        values_as_table = values_as_table and self.VALUES_AS_TABLE
    2154
    2155        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
    2156        if values_as_table or not expression.find_ancestor(exp.From, exp.Join):
    2157            args = self.expressions(expression)
    2158            alias = self.sql(expression, "alias")
    2159            values = f"VALUES{self.seg('')}{args}"
    2160            values = (
    2161                f"({values})"
    2162                if self.WRAP_DERIVED_VALUES
    2163                and (alias or isinstance(expression.parent, (exp.From, exp.Table)))
    2164                else values
    2165            )
    2166            return f"{values} AS {alias}" if alias else values
    2167
    2168        # Converts `VALUES...` expression into a series of select unions.
    2169        alias_node = expression.args.get("alias")
    2170        column_names = alias_node and alias_node.columns
    2171
    2172        selects: t.List[exp.Query] = []
    2173
    2174        for i, tup in enumerate(expression.expressions):
    2175            row = tup.expressions
    2176
    2177            if i == 0 and column_names:
    2178                row = [
    2179                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
    2180                ]
    2181
    2182            selects.append(exp.Select(expressions=row))
    2183
    2184        if self.pretty:
    2185            # This may result in poor performance for large-cardinality `VALUES` tables, due to
    2186            # the deep nesting of the resulting exp.Unions. If this is a problem, either increase
    2187            # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`.
    2188            query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects)
    2189            return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False))
    2190
    2191        alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else ""
    2192        unions = " UNION ALL ".join(self.sql(select) for select in selects)
    2193        return f"({unions}){alias}"

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

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

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

    2198    @unsupported_args("expressions")
    2199    def into_sql(self, expression: exp.Into) -> str:
    2200        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    2201        unlogged = " UNLOGGED" if expression.args.get("unlogged") else ""
    2202        return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"

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

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

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

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

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

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

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

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

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

    2219    def group_sql(self, expression: exp.Group) -> str:
    2220        group_by_all = expression.args.get("all")
    2221        if group_by_all is True:
    2222            modifier = " ALL"
    2223        elif group_by_all is False:
    2224            modifier = " DISTINCT"
    2225        else:
    2226            modifier = ""
    2227
    2228        group_by = self.op_expressions(f"GROUP BY{modifier}", expression)
    2229
    2230        grouping_sets = self.expressions(expression, key="grouping_sets")
    2231        cube = self.expressions(expression, key="cube")
    2232        rollup = self.expressions(expression, key="rollup")
    2233
    2234        groupings = csv(
    2235            self.seg(grouping_sets) if grouping_sets else "",
    2236            self.seg(cube) if cube else "",
    2237            self.seg(rollup) if rollup else "",
    2238            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    2239            sep=self.GROUPINGS_SEP,
    2240        )
    2241
    2242        if (
    2243            expression.expressions
    2244            and groupings
    2245            and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP")
    2246        ):
    2247            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    2248
    2249        return f"{group_by}{groupings}"

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

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

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

    2255    def connect_sql(self, expression: exp.Connect) -> str:
    2256        start = self.sql(expression, "start")
    2257        start = self.seg(f"START WITH {start}") if start else ""
    2258        nocycle = " NOCYCLE" if expression.args.get("nocycle") else ""
    2259        connect = self.sql(expression, "connect")
    2260        connect = self.seg(f"CONNECT BY{nocycle} {connect}")
    2261        return start + connect

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

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

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

    2266    def join_sql(self, expression: exp.Join) -> str:
    2267        if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"):
    2268            side = None
    2269        else:
    2270            side = expression.side
    2271
    2272        op_sql = " ".join(
    2273            op
    2274            for op in (
    2275                expression.method,
    2276                "GLOBAL" if expression.args.get("global") else None,
    2277                side,
    2278                expression.kind,
    2279                expression.hint if self.JOIN_HINTS else None,
    2280            )
    2281            if op
    2282        )
    2283        match_cond = self.sql(expression, "match_condition")
    2284        match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else ""
    2285        on_sql = self.sql(expression, "on")
    2286        using = expression.args.get("using")
    2287
    2288        if not on_sql and using:
    2289            on_sql = csv(*(self.sql(column) for column in using))
    2290
    2291        this = expression.this
    2292        this_sql = self.sql(this)
    2293
    2294        exprs = self.expressions(expression)
    2295        if exprs:
    2296            this_sql = f"{this_sql},{self.seg(exprs)}"
    2297
    2298        if on_sql:
    2299            on_sql = self.indent(on_sql, skip_first=True)
    2300            space = self.seg(" " * self.pad) if self.pretty else " "
    2301            if using:
    2302                on_sql = f"{space}USING ({on_sql})"
    2303            else:
    2304                on_sql = f"{space}ON {on_sql}"
    2305        elif not op_sql:
    2306            if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None:
    2307                return f" {this_sql}"
    2308
    2309            return f", {this_sql}"
    2310
    2311        if op_sql != "STRAIGHT_JOIN":
    2312            op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    2313
    2314        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    2315        return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}{pivots}"

def lambda_sql( self, expression: sqlglot.expressions.Lambda, arrow_sep: str = '->') -> str: View Source

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

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

    2322    def lateral_op(self, expression: exp.Lateral) -> str:
    2323        cross_apply = expression.args.get("cross_apply")
    2324
    2325        # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/
    2326        if cross_apply is True:
    2327            op = "INNER JOIN "
    2328        elif cross_apply is False:
    2329            op = "LEFT JOIN "
    2330        else:
    2331            op = ""
    2332
    2333        return f"{op}LATERAL"

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

    2335    def lateral_sql(self, expression: exp.Lateral) -> str:
    2336        this = self.sql(expression, "this")
    2337
    2338        if expression.args.get("view"):
    2339            alias = expression.args["alias"]
    2340            columns = self.expressions(alias, key="columns", flat=True)
    2341            table = f" {alias.name}" if alias.name else ""
    2342            columns = f" AS {columns}" if columns else ""
    2343            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    2344            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    2345
    2346        alias = self.sql(expression, "alias")
    2347        alias = f" AS {alias}" if alias else ""
    2348
    2349        ordinality = expression.args.get("ordinality") or ""
    2350        if ordinality:
    2351            ordinality = f" WITH ORDINALITY{alias}"
    2352            alias = ""
    2353
    2354        return f"{self.lateral_op(expression)} {this}{alias}{ordinality}"

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

    2356    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    2357        this = self.sql(expression, "this")
    2358
    2359        args = [
    2360            self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e
    2361            for e in (expression.args.get(k) for k in ("offset", "expression"))
    2362            if e
    2363        ]
    2364
    2365        args_sql = ", ".join(self.sql(e) for e in args)
    2366        args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql
    2367        expressions = self.expressions(expression, flat=True)
    2368        limit_options = self.sql(expression, "limit_options")
    2369        expressions = f" BY {expressions}" if expressions else ""
    2370
    2371        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

    2373    def offset_sql(self, expression: exp.Offset) -> str:
    2374        this = self.sql(expression, "this")
    2375        value = expression.expression
    2376        value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value
    2377        expressions = self.expressions(expression, flat=True)
    2378        expressions = f" BY {expressions}" if expressions else ""
    2379        return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"

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

    2381    def setitem_sql(self, expression: exp.SetItem) -> str:
    2382        kind = self.sql(expression, "kind")
    2383        kind = f"{kind} " if kind else ""
    2384        this = self.sql(expression, "this")
    2385        expressions = self.expressions(expression)
    2386        collate = self.sql(expression, "collate")
    2387        collate = f" COLLATE {collate}" if collate else ""
    2388        global_ = "GLOBAL " if expression.args.get("global") else ""
    2389        return f"{global_}{kind}{this}{expressions}{collate}"

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

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

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

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

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

    2399    def lock_sql(self, expression: exp.Lock) -> str:
    2400        if not self.LOCKING_READS_SUPPORTED:
    2401            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    2402            return ""
    2403
    2404        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    2405        expressions = self.expressions(expression, flat=True)
    2406        expressions = f" OF {expressions}" if expressions else ""
    2407        wait = expression.args.get("wait")
    2408
    2409        if wait is not None:
    2410            if isinstance(wait, exp.Literal):
    2411                wait = f" WAIT {self.sql(wait)}"
    2412            else:
    2413                wait = " NOWAIT" if wait else " SKIP LOCKED"
    2414
    2415        return f"{lock_type}{expressions}{wait or ''}"

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

    2417    def literal_sql(self, expression: exp.Literal) -> str:
    2418        text = expression.this or ""
    2419        if expression.is_string:
    2420            text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}"
    2421        return text

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

    2423    def escape_str(self, text: str, escape_backslash: bool = True) -> str:
    2424        if self.dialect.ESCAPED_SEQUENCES:
    2425            to_escaped = self.dialect.ESCAPED_SEQUENCES
    2426            text = "".join(
    2427                to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text
    2428            )
    2429
    2430        return self._replace_line_breaks(text).replace(
    2431            self.dialect.QUOTE_END, self._escaped_quote_end
    2432        )

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

    2434    def loaddata_sql(self, expression: exp.LoadData) -> str:
    2435        local = " LOCAL" if expression.args.get("local") else ""
    2436        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    2437        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    2438        this = f" INTO TABLE {self.sql(expression, 'this')}"
    2439        partition = self.sql(expression, "partition")
    2440        partition = f" {partition}" if partition else ""
    2441        input_format = self.sql(expression, "input_format")
    2442        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    2443        serde = self.sql(expression, "serde")
    2444        serde = f" SERDE {serde}" if serde else ""
    2445        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"

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

    2447    def null_sql(self, *_) -> str:
    2448        return "NULL"

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

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

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

    2453    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    2454        this = self.sql(expression, "this")
    2455        this = f"{this} " if this else this
    2456        siblings = "SIBLINGS " if expression.args.get("siblings") else ""
    2457        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

    2459    def withfill_sql(self, expression: exp.WithFill) -> str:
    2460        from_sql = self.sql(expression, "from")
    2461        from_sql = f" FROM {from_sql}" if from_sql else ""
    2462        to_sql = self.sql(expression, "to")
    2463        to_sql = f" TO {to_sql}" if to_sql else ""
    2464        step_sql = self.sql(expression, "step")
    2465        step_sql = f" STEP {step_sql}" if step_sql else ""
    2466        interpolated_values = [
    2467            f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}"
    2468            if isinstance(e, exp.Alias)
    2469            else self.sql(e, "this")
    2470            for e in expression.args.get("interpolate") or []
    2471        ]
    2472        interpolate = (
    2473            f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else ""
    2474        )
    2475        return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}"

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

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

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

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

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

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

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

    2486    def ordered_sql(self, expression: exp.Ordered) -> str:
    2487        desc = expression.args.get("desc")
    2488        asc = not desc
    2489
    2490        nulls_first = expression.args.get("nulls_first")
    2491        nulls_last = not nulls_first
    2492        nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large"
    2493        nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small"
    2494        nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last"
    2495
    2496        this = self.sql(expression, "this")
    2497
    2498        sort_order = " DESC" if desc else (" ASC" if desc is False else "")
    2499        nulls_sort_change = ""
    2500        if nulls_first and (
    2501            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
    2502        ):
    2503            nulls_sort_change = " NULLS FIRST"
    2504        elif (
    2505            nulls_last
    2506            and ((asc and nulls_are_small) or (desc and nulls_are_large))
    2507            and not nulls_are_last
    2508        ):
    2509            nulls_sort_change = " NULLS LAST"
    2510
    2511        # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it
    2512        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
    2513            window = expression.find_ancestor(exp.Window, exp.Select)
    2514            if isinstance(window, exp.Window) and window.args.get("spec"):
    2515                self.unsupported(
    2516                    f"'{nulls_sort_change.strip()}' translation not supported in window functions"
    2517                )
    2518                nulls_sort_change = ""
    2519            elif self.NULL_ORDERING_SUPPORTED is False and (
    2520                (asc and nulls_sort_change == " NULLS LAST")
    2521                or (desc and nulls_sort_change == " NULLS FIRST")
    2522            ):
    2523                # BigQuery does not allow these ordering/nulls combinations when used under
    2524                # an aggregation func or under a window containing one
    2525                ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select)
    2526
    2527                if isinstance(ancestor, exp.Window):
    2528                    ancestor = ancestor.this
    2529                if isinstance(ancestor, exp.AggFunc):
    2530                    self.unsupported(
    2531                        f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order"
    2532                    )
    2533                    nulls_sort_change = ""
    2534            elif self.NULL_ORDERING_SUPPORTED is None:
    2535                if expression.this.is_int:
    2536                    self.unsupported(
    2537                        f"'{nulls_sort_change.strip()}' translation not supported with positional ordering"
    2538                    )
    2539                elif not isinstance(expression.this, exp.Rand):
    2540                    null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else ""
    2541                    this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}"
    2542                nulls_sort_change = ""
    2543
    2544        with_fill = self.sql(expression, "with_fill")
    2545        with_fill = f" {with_fill}" if with_fill else ""
    2546
    2547        return f"{this}{sort_order}{nulls_sort_change}{with_fill}"

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

    2549    def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str:
    2550        window_frame = self.sql(expression, "window_frame")
    2551        window_frame = f"{window_frame} " if window_frame else ""
    2552
    2553        this = self.sql(expression, "this")
    2554
    2555        return f"{window_frame}{this}"

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

    2557    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    2558        partition = self.partition_by_sql(expression)
    2559        order = self.sql(expression, "order")
    2560        measures = self.expressions(expression, key="measures")
    2561        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    2562        rows = self.sql(expression, "rows")
    2563        rows = self.seg(rows) if rows else ""
    2564        after = self.sql(expression, "after")
    2565        after = self.seg(after) if after else ""
    2566        pattern = self.sql(expression, "pattern")
    2567        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    2568        definition_sqls = [
    2569            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    2570            for definition in expression.args.get("define", [])
    2571        ]
    2572        definitions = self.expressions(sqls=definition_sqls)
    2573        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    2574        body = "".join(
    2575            (
    2576                partition,
    2577                order,
    2578                measures,
    2579                rows,
    2580                after,
    2581                pattern,
    2582                define,
    2583            )
    2584        )
    2585        alias = self.sql(expression, "alias")
    2586        alias = f" {alias}" if alias else ""
    2587        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"

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

    2589    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    2590        limit = expression.args.get("limit")
    2591
    2592        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    2593            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
    2594        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    2595            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
    2596
    2597        return csv(
    2598            *sqls,
    2599            *[self.sql(join) for join in expression.args.get("joins") or []],
    2600            self.sql(expression, "match"),
    2601            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    2602            self.sql(expression, "prewhere"),
    2603            self.sql(expression, "where"),
    2604            self.sql(expression, "connect"),
    2605            self.sql(expression, "group"),
    2606            self.sql(expression, "having"),
    2607            *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()],
    2608            self.sql(expression, "order"),
    2609            *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit),
    2610            *self.after_limit_modifiers(expression),
    2611            self.options_modifier(expression),
    2612            self.for_modifiers(expression),
    2613            sep="",
    2614        )

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

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

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

    2620    def for_modifiers(self, expression: exp.Expression) -> str:
    2621        for_modifiers = self.expressions(expression, key="for")
    2622        return f"{self.sep()}FOR XML{self.seg(for_modifiers)}" if for_modifiers else ""

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

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

    2628    def offset_limit_modifiers(
    2629        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    2630    ) -> t.List[str]:
    2631        return [
    2632            self.sql(expression, "offset") if fetch else self.sql(limit),
    2633            self.sql(limit) if fetch else self.sql(expression, "offset"),
    2634        ]

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

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

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

    2641    def select_sql(self, expression: exp.Select) -> str:
    2642        into = expression.args.get("into")
    2643        if not self.SUPPORTS_SELECT_INTO and into:
    2644            into.pop()
    2645
    2646        hint = self.sql(expression, "hint")
    2647        distinct = self.sql(expression, "distinct")
    2648        distinct = f" {distinct}" if distinct else ""
    2649        kind = self.sql(expression, "kind")
    2650
    2651        limit = expression.args.get("limit")
    2652        if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP:
    2653            top = self.limit_sql(limit, top=True)
    2654            limit.pop()
    2655        else:
    2656            top = ""
    2657
    2658        expressions = self.expressions(expression)
    2659
    2660        if kind:
    2661            if kind in self.SELECT_KINDS:
    2662                kind = f" AS {kind}"
    2663            else:
    2664                if kind == "STRUCT":
    2665                    expressions = self.expressions(
    2666                        sqls=[
    2667                            self.sql(
    2668                                exp.Struct(
    2669                                    expressions=[
    2670                                        exp.PropertyEQ(this=e.args.get("alias"), expression=e.this)
    2671                                        if isinstance(e, exp.Alias)
    2672                                        else e
    2673                                        for e in expression.expressions
    2674                                    ]
    2675                                )
    2676                            )
    2677                        ]
    2678                    )
    2679                kind = ""
    2680
    2681        operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ")
    2682        operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else ""
    2683
    2684        # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata
    2685        # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first.
    2686        top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}"
    2687        expressions = f"{self.sep()}{expressions}" if expressions else expressions
    2688        sql = self.query_modifiers(
    2689            expression,
    2690            f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}",
    2691            self.sql(expression, "into", comment=False),
    2692            self.sql(expression, "from", comment=False),
    2693        )
    2694
    2695        # If both the CTE and SELECT clauses have comments, generate the latter earlier
    2696        if expression.args.get("with"):
    2697            sql = self.maybe_comment(sql, expression)
    2698            expression.pop_comments()
    2699
    2700        sql = self.prepend_ctes(expression, sql)
    2701
    2702        if not self.SUPPORTS_SELECT_INTO and into:
    2703            if into.args.get("temporary"):
    2704                table_kind = " TEMPORARY"
    2705            elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"):
    2706                table_kind = " UNLOGGED"
    2707            else:
    2708                table_kind = ""
    2709            sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}"
    2710
    2711        return sql

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

    2713    def schema_sql(self, expression: exp.Schema) -> str:
    2714        this = self.sql(expression, "this")
    2715        sql = self.schema_columns_sql(expression)
    2716        return f"{this} {sql}" if this and sql else this or sql

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

    2718    def schema_columns_sql(self, expression: exp.Schema) -> str:
    2719        if expression.expressions:
    2720            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
    2721        return ""

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

    2723    def star_sql(self, expression: exp.Star) -> str:
    2724        except_ = self.expressions(expression, key="except", flat=True)
    2725        except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else ""
    2726        replace = self.expressions(expression, key="replace", flat=True)
    2727        replace = f"{self.seg('REPLACE')} ({replace})" if replace else ""
    2728        rename = self.expressions(expression, key="rename", flat=True)
    2729        rename = f"{self.seg('RENAME')} ({rename})" if rename else ""
    2730        return f"*{except_}{replace}{rename}"

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

    2732    def parameter_sql(self, expression: exp.Parameter) -> str:
    2733        this = self.sql(expression, "this")
    2734        return f"{self.PARAMETER_TOKEN}{this}"

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

    2736    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    2737        this = self.sql(expression, "this")
    2738        kind = expression.text("kind")
    2739        if kind:
    2740            kind = f"{kind}."
    2741        return f"@@{kind}{this}"

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

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

    2746    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    2747        alias = self.sql(expression, "alias")
    2748        alias = f"{sep}{alias}" if alias else ""
    2749        sample = self.sql(expression, "sample")
    2750        if self.dialect.ALIAS_POST_TABLESAMPLE and sample:
    2751            alias = f"{sample}{alias}"
    2752
    2753            # Set to None so it's not generated again by self.query_modifiers()
    2754            expression.set("sample", None)
    2755
    2756        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    2757        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    2758        return self.prepend_ctes(expression, sql)

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

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

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

    2764    def unnest_sql(self, expression: exp.Unnest) -> str:
    2765        args = self.expressions(expression, flat=True)
    2766
    2767        alias = expression.args.get("alias")
    2768        offset = expression.args.get("offset")
    2769
    2770        if self.UNNEST_WITH_ORDINALITY:
    2771            if alias and isinstance(offset, exp.Expression):
    2772                alias.append("columns", offset)
    2773
    2774        if alias and self.dialect.UNNEST_COLUMN_ONLY:
    2775            columns = alias.columns
    2776            alias = self.sql(columns[0]) if columns else ""
    2777        else:
    2778            alias = self.sql(alias)
    2779
    2780        alias = f" AS {alias}" if alias else alias
    2781        if self.UNNEST_WITH_ORDINALITY:
    2782            suffix = f" WITH ORDINALITY{alias}" if offset else alias
    2783        else:
    2784            if isinstance(offset, exp.Expression):
    2785                suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}"
    2786            elif offset:
    2787                suffix = f"{alias} WITH OFFSET"
    2788            else:
    2789                suffix = alias
    2790
    2791        return f"UNNEST({args}){suffix}"

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

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

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

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

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

    2800    def window_sql(self, expression: exp.Window) -> str:
    2801        this = self.sql(expression, "this")
    2802        partition = self.partition_by_sql(expression)
    2803        order = expression.args.get("order")
    2804        order = self.order_sql(order, flat=True) if order else ""
    2805        spec = self.sql(expression, "spec")
    2806        alias = self.sql(expression, "alias")
    2807        over = self.sql(expression, "over") or "OVER"
    2808
    2809        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    2810
    2811        first = expression.args.get("first")
    2812        if first is None:
    2813            first = ""
    2814        else:
    2815            first = "FIRST" if first else "LAST"
    2816
    2817        if not partition and not order and not spec and alias:
    2818            return f"{this} {alias}"
    2819
    2820        args = self.format_args(
    2821            *[arg for arg in (alias, first, partition, order, spec) if arg], sep=" "
    2822        )
    2823        return f"{this} ({args})"

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

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

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

    2829    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    2830        kind = self.sql(expression, "kind")
    2831        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    2832        end = (
    2833            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    2834            or "CURRENT ROW"
    2835        )
    2836
    2837        window_spec = f"{kind} BETWEEN {start} AND {end}"
    2838
    2839        exclude = self.sql(expression, "exclude")
    2840        if exclude:
    2841            if self.SUPPORTS_WINDOW_EXCLUDE:
    2842                window_spec += f" EXCLUDE {exclude}"
    2843            else:
    2844                self.unsupported("EXCLUDE clause is not supported in the WINDOW clause")
    2845
    2846        return window_spec

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

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

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

    2853    def between_sql(self, expression: exp.Between) -> str:
    2854        this = self.sql(expression, "this")
    2855        low = self.sql(expression, "low")
    2856        high = self.sql(expression, "high")
    2857        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

    2859    def bracket_offset_expressions(
    2860        self, expression: exp.Bracket, index_offset: t.Optional[int] = None
    2861    ) -> t.List[exp.Expression]:
    2862        return apply_index_offset(
    2863            expression.this,
    2864            expression.expressions,
    2865            (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0),
    2866            dialect=self.dialect,
    2867        )

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

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

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

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

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

    2877    def any_sql(self, expression: exp.Any) -> str:
    2878        this = self.sql(expression, "this")
    2879        if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)):
    2880            if isinstance(expression.this, exp.UNWRAPPED_QUERIES):
    2881                this = self.wrap(this)
    2882            return f"ANY{this}"
    2883        return f"ANY {this}"

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

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

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

    2888    def case_sql(self, expression: exp.Case) -> str:
    2889        this = self.sql(expression, "this")
    2890        statements = [f"CASE {this}" if this else "CASE"]
    2891
    2892        for e in expression.args["ifs"]:
    2893            statements.append(f"WHEN {self.sql(e, 'this')}")
    2894            statements.append(f"THEN {self.sql(e, 'true')}")
    2895
    2896        default = self.sql(expression, "default")
    2897
    2898        if default:
    2899            statements.append(f"ELSE {default}")
    2900
    2901        statements.append("END")
    2902
    2903        if self.pretty and self.too_wide(statements):
    2904            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    2905
    2906        return " ".join(statements)

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

    2908    def constraint_sql(self, expression: exp.Constraint) -> str:
    2909        this = self.sql(expression, "this")
    2910        expressions = self.expressions(expression, flat=True)
    2911        return f"CONSTRAINT {this} {expressions}"

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

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

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

    2918    def extract_sql(self, expression: exp.Extract) -> str:
    2919        from sqlglot.dialects.dialect import map_date_part
    2920
    2921        this = (
    2922            map_date_part(expression.this, self.dialect)
    2923            if self.NORMALIZE_EXTRACT_DATE_PARTS
    2924            else expression.this
    2925        )
    2926        this_sql = self.sql(this) if self.EXTRACT_ALLOWS_QUOTES else this.name
    2927        expression_sql = self.sql(expression, "expression")
    2928
    2929        return f"EXTRACT({this_sql} FROM {expression_sql})"

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

    2931    def trim_sql(self, expression: exp.Trim) -> str:
    2932        trim_type = self.sql(expression, "position")
    2933
    2934        if trim_type == "LEADING":
    2935            func_name = "LTRIM"
    2936        elif trim_type == "TRAILING":
    2937            func_name = "RTRIM"
    2938        else:
    2939            func_name = "TRIM"
    2940
    2941        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

    2943    def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]:
    2944        args = expression.expressions
    2945        if isinstance(expression, exp.ConcatWs):
    2946            args = args[1:]  # Skip the delimiter
    2947
    2948        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    2949            args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args]
    2950
    2951        if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"):
    2952            args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args]
    2953
    2954        return args

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

    2956    def concat_sql(self, expression: exp.Concat) -> str:
    2957        expressions = self.convert_concat_args(expression)
    2958
    2959        # Some dialects don't allow a single-argument CONCAT call
    2960        if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1:
    2961            return self.sql(expressions[0])
    2962
    2963        return self.func("CONCAT", *expressions)

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

    2965    def concatws_sql(self, expression: exp.ConcatWs) -> str:
    2966        return self.func(
    2967            "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression)
    2968        )

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

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

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

    2974    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    2975        expressions = self.expressions(expression, flat=True)
    2976        expressions = f" ({expressions})" if expressions else ""
    2977        reference = self.sql(expression, "reference")
    2978        reference = f" {reference}" if reference else ""
    2979        delete = self.sql(expression, "delete")
    2980        delete = f" ON DELETE {delete}" if delete else ""
    2981        update = self.sql(expression, "update")
    2982        update = f" ON UPDATE {update}" if update else ""
    2983        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2984        options = f" {options}" if options else ""
    2985        return f"FOREIGN KEY{expressions}{reference}{delete}{update}{options}"

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

    2987    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    2988        expressions = self.expressions(expression, flat=True)
    2989        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2990        options = f" {options}" if options else ""
    2991        return f"PRIMARY KEY ({expressions}){options}"

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

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

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

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

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

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

    3004    def jsonpath_sql(self, expression: exp.JSONPath) -> str:
    3005        path = self.expressions(expression, sep="", flat=True).lstrip(".")
    3006
    3007        if expression.args.get("escape"):
    3008            path = self.escape_str(path)
    3009
    3010        if self.QUOTE_JSON_PATH:
    3011            path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"
    3012
    3013        return path

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

    3015    def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str:
    3016        if isinstance(expression, exp.JSONPathPart):
    3017            transform = self.TRANSFORMS.get(expression.__class__)
    3018            if not callable(transform):
    3019                self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}")
    3020                return ""
    3021
    3022            return transform(self, expression)
    3023
    3024        if isinstance(expression, int):
    3025            return str(expression)
    3026
    3027        if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE:
    3028            escaped = expression.replace("'", "\\'")
    3029            escaped = f"\\'{expression}\\'"
    3030        else:
    3031            escaped = expression.replace('"', '\\"')
    3032            escaped = f'"{escaped}"'
    3033
    3034        return escaped

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

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

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

    3039    def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str:
    3040        null_handling = expression.args.get("null_handling")
    3041        null_handling = f" {null_handling}" if null_handling else ""
    3042
    3043        unique_keys = expression.args.get("unique_keys")
    3044        if unique_keys is not None:
    3045            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    3046        else:
    3047            unique_keys = ""
    3048
    3049        return_type = self.sql(expression, "return_type")
    3050        return_type = f" RETURNING {return_type}" if return_type else ""
    3051        encoding = self.sql(expression, "encoding")
    3052        encoding = f" ENCODING {encoding}" if encoding else ""
    3053
    3054        return self.func(
    3055            "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG",
    3056            *expression.expressions,
    3057            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
    3058        )

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

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

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

    3063    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
    3064        null_handling = expression.args.get("null_handling")
    3065        null_handling = f" {null_handling}" if null_handling else ""
    3066        return_type = self.sql(expression, "return_type")
    3067        return_type = f" RETURNING {return_type}" if return_type else ""
    3068        strict = " STRICT" if expression.args.get("strict") else ""
    3069        return self.func(
    3070            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
    3071        )

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

    3073    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
    3074        this = self.sql(expression, "this")
    3075        order = self.sql(expression, "order")
    3076        null_handling = expression.args.get("null_handling")
    3077        null_handling = f" {null_handling}" if null_handling else ""
    3078        return_type = self.sql(expression, "return_type")
    3079        return_type = f" RETURNING {return_type}" if return_type else ""
    3080        strict = " STRICT" if expression.args.get("strict") else ""
    3081        return self.func(
    3082            "JSON_ARRAYAGG",
    3083            this,
    3084            suffix=f"{order}{null_handling}{return_type}{strict})",
    3085        )

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

    3087    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
    3088        path = self.sql(expression, "path")
    3089        path = f" PATH {path}" if path else ""
    3090        nested_schema = self.sql(expression, "nested_schema")
    3091
    3092        if nested_schema:
    3093            return f"NESTED{path} {nested_schema}"
    3094
    3095        this = self.sql(expression, "this")
    3096        kind = self.sql(expression, "kind")
    3097        kind = f" {kind}" if kind else ""
    3098        return f"{this}{kind}{path}"

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

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

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

    3103    def jsontable_sql(self, expression: exp.JSONTable) -> str:
    3104        this = self.sql(expression, "this")
    3105        path = self.sql(expression, "path")
    3106        path = f", {path}" if path else ""
    3107        error_handling = expression.args.get("error_handling")
    3108        error_handling = f" {error_handling}" if error_handling else ""
    3109        empty_handling = expression.args.get("empty_handling")
    3110        empty_handling = f" {empty_handling}" if empty_handling else ""
    3111        schema = self.sql(expression, "schema")
    3112        return self.func(
    3113            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
    3114        )

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

    3116    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    3117        this = self.sql(expression, "this")
    3118        kind = self.sql(expression, "kind")
    3119        path = self.sql(expression, "path")
    3120        path = f" {path}" if path else ""
    3121        as_json = " AS JSON" if expression.args.get("as_json") else ""
    3122        return f"{this} {kind}{path}{as_json}"

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

    3124    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    3125        this = self.sql(expression, "this")
    3126        path = self.sql(expression, "path")
    3127        path = f", {path}" if path else ""
    3128        expressions = self.expressions(expression)
    3129        with_ = (
    3130            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    3131            if expressions
    3132            else ""
    3133        )
    3134        return f"OPENJSON({this}{path}){with_}"

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

    3136    def in_sql(self, expression: exp.In) -> str:
    3137        query = expression.args.get("query")
    3138        unnest = expression.args.get("unnest")
    3139        field = expression.args.get("field")
    3140        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    3141
    3142        if query:
    3143            in_sql = self.sql(query)
    3144        elif unnest:
    3145            in_sql = self.in_unnest_op(unnest)
    3146        elif field:
    3147            in_sql = self.sql(field)
    3148        else:
    3149            in_sql = f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})"
    3150
    3151        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"

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

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

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

    3156    def interval_sql(self, expression: exp.Interval) -> str:
    3157        unit = self.sql(expression, "unit")
    3158        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    3159            unit = self.TIME_PART_SINGULARS.get(unit, unit)
    3160        unit = f" {unit}" if unit else ""
    3161
    3162        if self.SINGLE_STRING_INTERVAL:
    3163            this = expression.this.name if expression.this else ""
    3164            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    3165
    3166        this = self.sql(expression, "this")
    3167        if this:
    3168            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    3169            this = f" {this}" if unwrapped else f" ({this})"
    3170
    3171        return f"INTERVAL{this}{unit}"

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

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

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

    3176    def reference_sql(self, expression: exp.Reference) -> str:
    3177        this = self.sql(expression, "this")
    3178        expressions = self.expressions(expression, flat=True)
    3179        expressions = f"({expressions})" if expressions else ""
    3180        options = self.expressions(expression, key="options", flat=True, sep=" ")
    3181        options = f" {options}" if options else ""
    3182        return f"REFERENCES {this}{expressions}{options}"

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

    3184    def anonymous_sql(self, expression: exp.Anonymous) -> str:
    3185        # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive
    3186        parent = expression.parent
    3187        is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression
    3188        return self.func(
    3189            self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified
    3190        )

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

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

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

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

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

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

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

    3205    def alias_sql(self, expression: exp.Alias) -> str:
    3206        alias = self.sql(expression, "alias")
    3207        alias = f" AS {alias}" if alias else ""
    3208        return f"{self.sql(expression, 'this')}{alias}"

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

    3210    def pivotalias_sql(self, expression: exp.PivotAlias) -> str:
    3211        alias = expression.args["alias"]
    3212
    3213        parent = expression.parent
    3214        pivot = parent and parent.parent
    3215
    3216        if isinstance(pivot, exp.Pivot) and pivot.unpivot:
    3217            identifier_alias = isinstance(alias, exp.Identifier)
    3218            literal_alias = isinstance(alias, exp.Literal)
    3219
    3220            if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    3221                alias.replace(exp.Literal.string(alias.output_name))
    3222            elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    3223                alias.replace(exp.to_identifier(alias.output_name))
    3224
    3225        return self.alias_sql(expression)

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

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

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

    3230    def atindex_sql(self, expression: exp.AtTimeZone) -> str:
    3231        this = self.sql(expression, "this")
    3232        index = self.sql(expression, "expression")
    3233        return f"{this} AT {index}"

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

    3235    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    3236        this = self.sql(expression, "this")
    3237        zone = self.sql(expression, "zone")
    3238        return f"{this} AT TIME ZONE {zone}"

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

    3240    def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str:
    3241        this = self.sql(expression, "this")
    3242        zone = self.sql(expression, "zone")
    3243        return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'"

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

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

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

    3248    def and_sql(
    3249        self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None
    3250    ) -> str:
    3251        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

    3253    def or_sql(
    3254        self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None
    3255    ) -> str:
    3256        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

    3258    def xor_sql(
    3259        self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None
    3260    ) -> str:
    3261        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

    3263    def connector_sql(
    3264        self,
    3265        expression: exp.Connector,
    3266        op: str,
    3267        stack: t.Optional[t.List[str | exp.Expression]] = None,
    3268    ) -> str:
    3269        if stack is not None:
    3270            if expression.expressions:
    3271                stack.append(self.expressions(expression, sep=f" {op} "))
    3272            else:
    3273                stack.append(expression.right)
    3274                if expression.comments and self.comments:
    3275                    for comment in expression.comments:
    3276                        if comment:
    3277                            op += f" /*{self.sanitize_comment(comment)}*/"
    3278                stack.extend((op, expression.left))
    3279            return op
    3280
    3281        stack = [expression]
    3282        sqls: t.List[str] = []
    3283        ops = set()
    3284
    3285        while stack:
    3286            node = stack.pop()
    3287            if isinstance(node, exp.Connector):
    3288                ops.add(getattr(self, f"{node.key}_sql")(node, stack))
    3289            else:
    3290                sql = self.sql(node)
    3291                if sqls and sqls[-1] in ops:
    3292                    sqls[-1] += f" {sql}"
    3293                else:
    3294                    sqls.append(sql)
    3295
    3296        sep = "\n" if self.pretty and self.too_wide(sqls) else " "
    3297        return sep.join(sqls)

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

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

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

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

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

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

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

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

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

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

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

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

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

    3317    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    3318        format_sql = self.sql(expression, "format")
    3319        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    3320        to_sql = self.sql(expression, "to")
    3321        to_sql = f" {to_sql}" if to_sql else ""
    3322        action = self.sql(expression, "action")
    3323        action = f" {action}" if action else ""
    3324        default = self.sql(expression, "default")
    3325        default = f" DEFAULT {default} ON CONVERSION ERROR" if default else ""
    3326        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

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

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

    3332    def collate_sql(self, expression: exp.Collate) -> str:
    3333        if self.COLLATE_IS_FUNC:
    3334            return self.function_fallback_sql(expression)
    3335        return self.binary(expression, "COLLATE")

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

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

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

    3340    def comment_sql(self, expression: exp.Comment) -> str:
    3341        this = self.sql(expression, "this")
    3342        kind = expression.args["kind"]
    3343        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    3344        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    3345        expression_sql = self.sql(expression, "expression")
    3346        return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"

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

    3348    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    3349        this = self.sql(expression, "this")
    3350        delete = " DELETE" if expression.args.get("delete") else ""
    3351        recompress = self.sql(expression, "recompress")
    3352        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    3353        to_disk = self.sql(expression, "to_disk")
    3354        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    3355        to_volume = self.sql(expression, "to_volume")
    3356        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    3357        return f"{this}{delete}{recompress}{to_disk}{to_volume}"

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

    3359    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    3360        where = self.sql(expression, "where")
    3361        group = self.sql(expression, "group")
    3362        aggregates = self.expressions(expression, key="aggregates")
    3363        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    3364
    3365        if not (where or group or aggregates) and len(expression.expressions) == 1:
    3366            return f"TTL {self.expressions(expression, flat=True)}"
    3367
    3368        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"

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

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

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

    3373    def commit_sql(self, expression: exp.Commit) -> str:
    3374        chain = expression.args.get("chain")
    3375        if chain is not None:
    3376            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    3377
    3378        return f"COMMIT{chain or ''}"

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

    3380    def rollback_sql(self, expression: exp.Rollback) -> str:
    3381        savepoint = expression.args.get("savepoint")
    3382        savepoint = f" TO {savepoint}" if savepoint else ""
    3383        return f"ROLLBACK{savepoint}"

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

    3385    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    3386        this = self.sql(expression, "this")
    3387
    3388        dtype = self.sql(expression, "dtype")
    3389        if dtype:
    3390            collate = self.sql(expression, "collate")
    3391            collate = f" COLLATE {collate}" if collate else ""
    3392            using = self.sql(expression, "using")
    3393            using = f" USING {using}" if using else ""
    3394            alter_set_type = self.ALTER_SET_TYPE + " " if self.ALTER_SET_TYPE else ""
    3395            return f"ALTER COLUMN {this} {alter_set_type}{dtype}{collate}{using}"
    3396
    3397        default = self.sql(expression, "default")
    3398        if default:
    3399            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    3400
    3401        comment = self.sql(expression, "comment")
    3402        if comment:
    3403            return f"ALTER COLUMN {this} COMMENT {comment}"
    3404
    3405        visible = expression.args.get("visible")
    3406        if visible:
    3407            return f"ALTER COLUMN {this} SET {visible}"
    3408
    3409        allow_null = expression.args.get("allow_null")
    3410        drop = expression.args.get("drop")
    3411
    3412        if not drop and not allow_null:
    3413            self.unsupported("Unsupported ALTER COLUMN syntax")
    3414
    3415        if allow_null is not None:
    3416            keyword = "DROP" if drop else "SET"
    3417            return f"ALTER COLUMN {this} {keyword} NOT NULL"
    3418
    3419        return f"ALTER COLUMN {this} DROP DEFAULT"

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

    3421    def alterindex_sql(self, expression: exp.AlterIndex) -> str:
    3422        this = self.sql(expression, "this")
    3423
    3424        visible = expression.args.get("visible")
    3425        visible_sql = "VISIBLE" if visible else "INVISIBLE"
    3426
    3427        return f"ALTER INDEX {this} {visible_sql}"

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

    3429    def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str:
    3430        this = self.sql(expression, "this")
    3431        if not isinstance(expression.this, exp.Var):
    3432            this = f"KEY DISTKEY {this}"
    3433        return f"ALTER DISTSTYLE {this}"

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

    3435    def altersortkey_sql(self, expression: exp.AlterSortKey) -> str:
    3436        compound = " COMPOUND" if expression.args.get("compound") else ""
    3437        this = self.sql(expression, "this")
    3438        expressions = self.expressions(expression, flat=True)
    3439        expressions = f"({expressions})" if expressions else ""
    3440        return f"ALTER{compound} SORTKEY {this or expressions}"

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

    3442    def alterrename_sql(self, expression: exp.AlterRename) -> str:
    3443        if not self.RENAME_TABLE_WITH_DB:
    3444            # Remove db from tables
    3445            expression = expression.transform(
    3446                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    3447            ).assert_is(exp.AlterRename)
    3448        this = self.sql(expression, "this")
    3449        return f"RENAME TO {this}"

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

    3451    def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
    3452        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3453        old_column = self.sql(expression, "this")
    3454        new_column = self.sql(expression, "to")
    3455        return f"RENAME COLUMN{exists} {old_column} TO {new_column}"

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

    3457    def alterset_sql(self, expression: exp.AlterSet) -> str:
    3458        exprs = self.expressions(expression, flat=True)
    3459        if self.ALTER_SET_WRAPPED:
    3460            exprs = f"({exprs})"
    3461
    3462        return f"SET {exprs}"

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

    3464    def alter_sql(self, expression: exp.Alter) -> str:
    3465        actions = expression.args["actions"]
    3466
    3467        if not self.dialect.ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN and isinstance(
    3468            actions[0], exp.ColumnDef
    3469        ):
    3470            actions_sql = self.expressions(expression, key="actions", flat=True)
    3471            actions_sql = f"ADD {actions_sql}"
    3472        else:
    3473            actions_list = []
    3474            for action in actions:
    3475                if isinstance(action, (exp.ColumnDef, exp.Schema)):
    3476                    action_sql = self.add_column_sql(action)
    3477                else:
    3478                    action_sql = self.sql(action)
    3479                    if isinstance(action, exp.Query):
    3480                        action_sql = f"AS {action_sql}"
    3481
    3482                actions_list.append(action_sql)
    3483
    3484            actions_sql = self.format_args(*actions_list).lstrip("\n")
    3485
    3486        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3487        on_cluster = self.sql(expression, "cluster")
    3488        on_cluster = f" {on_cluster}" if on_cluster else ""
    3489        only = " ONLY" if expression.args.get("only") else ""
    3490        options = self.expressions(expression, key="options")
    3491        options = f", {options}" if options else ""
    3492        kind = self.sql(expression, "kind")
    3493        not_valid = " NOT VALID" if expression.args.get("not_valid") else ""
    3494
    3495        return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster}{self.sep()}{actions_sql}{not_valid}{options}"

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

    3497    def add_column_sql(self, expression: exp.Expression) -> str:
    3498        sql = self.sql(expression)
    3499        if isinstance(expression, exp.Schema):
    3500            column_text = " COLUMNS"
    3501        elif isinstance(expression, exp.ColumnDef) and self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD:
    3502            column_text = " COLUMN"
    3503        else:
    3504            column_text = ""
    3505
    3506        return f"ADD{column_text} {sql}"

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

    3508    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    3509        expressions = self.expressions(expression)
    3510        exists = " IF EXISTS " if expression.args.get("exists") else " "
    3511        return f"DROP{exists}{expressions}"

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

    3513    def addconstraint_sql(self, expression: exp.AddConstraint) -> str:
    3514        return f"ADD {self.expressions(expression, indent=False)}"

def addpartition_sql(self, expression: sqlglot.expressions.AddPartition) -> str: View Source

    3516    def addpartition_sql(self, expression: exp.AddPartition) -> str:
    3517        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
    3518        return f"ADD {exists}{self.sql(expression.this)}"

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

    3520    def distinct_sql(self, expression: exp.Distinct) -> str:
    3521        this = self.expressions(expression, flat=True)
    3522
    3523        if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1:
    3524            case = exp.case()
    3525            for arg in expression.expressions:
    3526                case = case.when(arg.is_(exp.null()), exp.null())
    3527            this = self.sql(case.else_(f"({this})"))
    3528
    3529        this = f" {this}" if this else ""
    3530
    3531        on = self.sql(expression, "on")
    3532        on = f" ON {on}" if on else ""
    3533        return f"DISTINCT{this}{on}"

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

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

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

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

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

    3541    def havingmax_sql(self, expression: exp.HavingMax) -> str:
    3542        this_sql = self.sql(expression, "this")
    3543        expression_sql = self.sql(expression, "expression")
    3544        kind = "MAX" if expression.args.get("max") else "MIN"
    3545        return f"{this_sql} HAVING {kind} {expression_sql}"

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

    3547    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    3548        return self.sql(
    3549            exp.Cast(
    3550                this=exp.Div(this=expression.this, expression=expression.expression),
    3551                to=exp.DataType(this=exp.DataType.Type.INT),
    3552            )
    3553        )

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

    3555    def dpipe_sql(self, expression: exp.DPipe) -> str:
    3556        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    3557            return self.func(
    3558                "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten())
    3559            )
    3560        return self.binary(expression, "||")

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

    3562    def div_sql(self, expression: exp.Div) -> str:
    3563        l, r = expression.left, expression.right
    3564
    3565        if not self.dialect.SAFE_DIVISION and expression.args.get("safe"):
    3566            r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0)))
    3567
    3568        if self.dialect.TYPED_DIVISION and not expression.args.get("typed"):
    3569            if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES):
    3570                l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE))
    3571
    3572        elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"):
    3573            if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES):
    3574                return self.sql(
    3575                    exp.cast(
    3576                        l / r,
    3577                        to=exp.DataType.Type.BIGINT,
    3578                    )
    3579                )
    3580
    3581        return self.binary(expression, "/")

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

    3583    def safedivide_sql(self, expression: exp.SafeDivide) -> str:
    3584        n = exp._wrap(expression.this, exp.Binary)
    3585        d = exp._wrap(expression.expression, exp.Binary)
    3586        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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3621    def is_sql(self, expression: exp.Is) -> str:
    3622        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    3623            return self.sql(
    3624                expression.this if expression.expression.this else exp.not_(expression.this)
    3625            )
    3626        return self.binary(expression, "IS")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3670    def try_sql(self, expression: exp.Try) -> str:
    3671        if not self.TRY_SUPPORTED:
    3672            self.unsupported("Unsupported TRY function")
    3673            return self.sql(expression, "this")
    3674
    3675        return self.func("TRY", expression.this)

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

    3677    def log_sql(self, expression: exp.Log) -> str:
    3678        this = expression.this
    3679        expr = expression.expression
    3680
    3681        if self.dialect.LOG_BASE_FIRST is False:
    3682            this, expr = expr, this
    3683        elif self.dialect.LOG_BASE_FIRST is None and expr:
    3684            if this.name in ("2", "10"):
    3685                return self.func(f"LOG{this.name}", expr)
    3686
    3687            self.unsupported(f"Unsupported logarithm with base {self.sql(this)}")
    3688
    3689        return self.func("LOG", this, expr)

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

    3691    def use_sql(self, expression: exp.Use) -> str:
    3692        kind = self.sql(expression, "kind")
    3693        kind = f" {kind}" if kind else ""
    3694        this = self.sql(expression, "this") or self.expressions(expression, flat=True)
    3695        this = f" {this}" if this else ""
    3696        return f"USE{kind}{this}"

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

    3698    def binary(self, expression: exp.Binary, op: str) -> str:
    3699        sqls: t.List[str] = []
    3700        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    3701        binary_type = type(expression)
    3702
    3703        while stack:
    3704            node = stack.pop()
    3705
    3706            if type(node) is binary_type:
    3707                op_func = node.args.get("operator")
    3708                if op_func:
    3709                    op = f"OPERATOR({self.sql(op_func)})"
    3710
    3711                stack.append(node.right)
    3712                stack.append(f" {self.maybe_comment(op, comments=node.comments)} ")
    3713                stack.append(node.left)
    3714            else:
    3715                sqls.append(self.sql(node))
    3716
    3717        return "".join(sqls)

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

    3719    def ceil_floor(self, expression: exp.Ceil | exp.Floor) -> str:
    3720        to_clause = self.sql(expression, "to")
    3721        if to_clause:
    3722            return f"{expression.sql_name()}({self.sql(expression, 'this')} TO {to_clause})"
    3723
    3724        return self.function_fallback_sql(expression)

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

    3726    def function_fallback_sql(self, expression: exp.Func) -> str:
    3727        args = []
    3728
    3729        for key in expression.arg_types:
    3730            arg_value = expression.args.get(key)
    3731
    3732            if isinstance(arg_value, list):
    3733                for value in arg_value:
    3734                    args.append(value)
    3735            elif arg_value is not None:
    3736                args.append(arg_value)
    3737
    3738        if self.dialect.PRESERVE_ORIGINAL_NAMES:
    3739            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
    3740        else:
    3741            name = expression.sql_name()
    3742
    3743        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

    3745    def func(
    3746        self,
    3747        name: str,
    3748        *args: t.Optional[exp.Expression | str],
    3749        prefix: str = "(",
    3750        suffix: str = ")",
    3751        normalize: bool = True,
    3752    ) -> str:
    3753        name = self.normalize_func(name) if normalize else name
    3754        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

    3756    def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str:
    3757        arg_sqls = tuple(
    3758            self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool)
    3759        )
    3760        if self.pretty and self.too_wide(arg_sqls):
    3761            return self.indent(
    3762                "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True
    3763            )
    3764        return sep.join(arg_sqls)

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

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

    3769    def format_time(
    3770        self,
    3771        expression: exp.Expression,
    3772        inverse_time_mapping: t.Optional[t.Dict[str, str]] = None,
    3773        inverse_time_trie: t.Optional[t.Dict] = None,
    3774    ) -> t.Optional[str]:
    3775        return format_time(
    3776            self.sql(expression, "format"),
    3777            inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING,
    3778            inverse_time_trie or self.dialect.INVERSE_TIME_TRIE,
    3779        )

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

    3781    def expressions(
    3782        self,
    3783        expression: t.Optional[exp.Expression] = None,
    3784        key: t.Optional[str] = None,
    3785        sqls: t.Optional[t.Collection[str | exp.Expression]] = None,
    3786        flat: bool = False,
    3787        indent: bool = True,
    3788        skip_first: bool = False,
    3789        skip_last: bool = False,
    3790        sep: str = ", ",
    3791        prefix: str = "",
    3792        dynamic: bool = False,
    3793        new_line: bool = False,
    3794    ) -> str:
    3795        expressions = expression.args.get(key or "expressions") if expression else sqls
    3796
    3797        if not expressions:
    3798            return ""
    3799
    3800        if flat:
    3801            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
    3802
    3803        num_sqls = len(expressions)
    3804        result_sqls = []
    3805
    3806        for i, e in enumerate(expressions):
    3807            sql = self.sql(e, comment=False)
    3808            if not sql:
    3809                continue
    3810
    3811            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    3812
    3813            if self.pretty:
    3814                if self.leading_comma:
    3815                    result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}")
    3816                else:
    3817                    result_sqls.append(
    3818                        f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}"
    3819                    )
    3820            else:
    3821                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    3822
    3823        if self.pretty and (not dynamic or self.too_wide(result_sqls)):
    3824            if new_line:
    3825                result_sqls.insert(0, "")
    3826                result_sqls.append("")
    3827            result_sql = "\n".join(s.rstrip() for s in result_sqls)
    3828        else:
    3829            result_sql = "".join(result_sqls)
    3830
    3831        return (
    3832            self.indent(result_sql, skip_first=skip_first, skip_last=skip_last)
    3833            if indent
    3834            else result_sql
    3835        )

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

    3837    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    3838        flat = flat or isinstance(expression.parent, exp.Properties)
    3839        expressions_sql = self.expressions(expression, flat=flat)
    3840        if flat:
    3841            return f"{op} {expressions_sql}"
    3842        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"

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

    3844    def naked_property(self, expression: exp.Property) -> str:
    3845        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    3846        if not property_name:
    3847            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    3848        return f"{property_name} {self.sql(expression, 'this')}"

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

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

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

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

    3856    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    3857        this = self.sql(expression, "this")
    3858        expressions = self.no_identify(self.expressions, expression)
    3859        expressions = (
    3860            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    3861        )
    3862        return f"{this}{expressions}" if expressions.strip() != "" else this

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

    3864    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    3865        this = self.sql(expression, "this")
    3866        expressions = self.expressions(expression, flat=True)
    3867        return f"{this}({expressions})"

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

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

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

    3872    def when_sql(self, expression: exp.When) -> str:
    3873        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    3874        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    3875        condition = self.sql(expression, "condition")
    3876        condition = f" AND {condition}" if condition else ""
    3877
    3878        then_expression = expression.args.get("then")
    3879        if isinstance(then_expression, exp.Insert):
    3880            this = self.sql(then_expression, "this")
    3881            this = f"INSERT {this}" if this else "INSERT"
    3882            then = self.sql(then_expression, "expression")
    3883            then = f"{this} VALUES {then}" if then else this
    3884        elif isinstance(then_expression, exp.Update):
    3885            if isinstance(then_expression.args.get("expressions"), exp.Star):
    3886                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    3887            else:
    3888                then = f"UPDATE SET{self.sep()}{self.expressions(then_expression)}"
    3889        else:
    3890            then = self.sql(then_expression)
    3891        return f"WHEN {matched}{source}{condition} THEN {then}"

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

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

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

    3896    def merge_sql(self, expression: exp.Merge) -> str:
    3897        table = expression.this
    3898        table_alias = ""
    3899
    3900        hints = table.args.get("hints")
    3901        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
    3902            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
    3903            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
    3904
    3905        this = self.sql(table)
    3906        using = f"USING {self.sql(expression, 'using')}"
    3907        on = f"ON {self.sql(expression, 'on')}"
    3908        whens = self.sql(expression, "whens")
    3909
    3910        returning = self.sql(expression, "returning")
    3911        if returning:
    3912            whens = f"{whens}{returning}"
    3913
    3914        sep = self.sep()
    3915
    3916        return self.prepend_ctes(
    3917            expression,
    3918            f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}",
    3919        )

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

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

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

    3925    def tonumber_sql(self, expression: exp.ToNumber) -> str:
    3926        if not self.SUPPORTS_TO_NUMBER:
    3927            self.unsupported("Unsupported TO_NUMBER function")
    3928            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3929
    3930        fmt = expression.args.get("format")
    3931        if not fmt:
    3932            self.unsupported("Conversion format is required for TO_NUMBER")
    3933            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3934
    3935        return self.func("TO_NUMBER", expression.this, fmt)

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

    3937    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    3938        this = self.sql(expression, "this")
    3939        kind = self.sql(expression, "kind")
    3940        settings_sql = self.expressions(expression, key="settings", sep=" ")
    3941        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    3942        return f"{this}({kind}{args})"

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

    3944    def dictrange_sql(self, expression: exp.DictRange) -> str:
    3945        this = self.sql(expression, "this")
    3946        max = self.sql(expression, "max")
    3947        min = self.sql(expression, "min")
    3948        return f"{this}(MIN {min} MAX {max})"

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

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

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

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

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

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

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

    3961    def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str:
    3962        expressions = self.expressions(expression, flat=True)
    3963        expressions = f" {self.wrap(expressions)}" if expressions else ""
    3964        buckets = self.sql(expression, "buckets")
    3965        kind = self.sql(expression, "kind")
    3966        buckets = f" BUCKETS {buckets}" if buckets else ""
    3967        order = self.sql(expression, "order")
    3968        return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}"

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

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

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

    3973    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    3974        expressions = self.expressions(expression, key="expressions", flat=True)
    3975        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    3976        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    3977        buckets = self.sql(expression, "buckets")
    3978        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"

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

    3980    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    3981        this = self.sql(expression, "this")
    3982        having = self.sql(expression, "having")
    3983
    3984        if having:
    3985            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    3986
    3987        return self.func("ANY_VALUE", this)

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

    3989    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
    3990        transform = self.func("TRANSFORM", *expression.expressions)
    3991        row_format_before = self.sql(expression, "row_format_before")
    3992        row_format_before = f" {row_format_before}" if row_format_before else ""
    3993        record_writer = self.sql(expression, "record_writer")
    3994        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
    3995        using = f" USING {self.sql(expression, 'command_script')}"
    3996        schema = self.sql(expression, "schema")
    3997        schema = f" AS {schema}" if schema else ""
    3998        row_format_after = self.sql(expression, "row_format_after")
    3999        row_format_after = f" {row_format_after}" if row_format_after else ""
    4000        record_reader = self.sql(expression, "record_reader")
    4001        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
    4002        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

    4004    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
    4005        key_block_size = self.sql(expression, "key_block_size")
    4006        if key_block_size:
    4007            return f"KEY_BLOCK_SIZE = {key_block_size}"
    4008
    4009        using = self.sql(expression, "using")
    4010        if using:
    4011            return f"USING {using}"
    4012
    4013        parser = self.sql(expression, "parser")
    4014        if parser:
    4015            return f"WITH PARSER {parser}"
    4016
    4017        comment = self.sql(expression, "comment")
    4018        if comment:
    4019            return f"COMMENT {comment}"
    4020
    4021        visible = expression.args.get("visible")
    4022        if visible is not None:
    4023            return "VISIBLE" if visible else "INVISIBLE"
    4024
    4025        engine_attr = self.sql(expression, "engine_attr")
    4026        if engine_attr:
    4027            return f"ENGINE_ATTRIBUTE = {engine_attr}"
    4028
    4029        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
    4030        if secondary_engine_attr:
    4031            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
    4032
    4033        self.unsupported("Unsupported index constraint option.")
    4034        return ""

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

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

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

    4040    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
    4041        kind = self.sql(expression, "kind")
    4042        kind = f"{kind} INDEX" if kind else "INDEX"
    4043        this = self.sql(expression, "this")
    4044        this = f" {this}" if this else ""
    4045        index_type = self.sql(expression, "index_type")
    4046        index_type = f" USING {index_type}" if index_type else ""
    4047        expressions = self.expressions(expression, flat=True)
    4048        expressions = f" ({expressions})" if expressions else ""
    4049        options = self.expressions(expression, key="options", sep=" ")
    4050        options = f" {options}" if options else ""
    4051        return f"{kind}{this}{index_type}{expressions}{options}"

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

    4053    def nvl2_sql(self, expression: exp.Nvl2) -> str:
    4054        if self.NVL2_SUPPORTED:
    4055            return self.function_fallback_sql(expression)
    4056
    4057        case = exp.Case().when(
    4058            expression.this.is_(exp.null()).not_(copy=False),
    4059            expression.args["true"],
    4060            copy=False,
    4061        )
    4062        else_cond = expression.args.get("false")
    4063        if else_cond:
    4064            case.else_(else_cond, copy=False)
    4065
    4066        return self.sql(case)

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

    4068    def comprehension_sql(self, expression: exp.Comprehension) -> str:
    4069        this = self.sql(expression, "this")
    4070        expr = self.sql(expression, "expression")
    4071        iterator = self.sql(expression, "iterator")
    4072        condition = self.sql(expression, "condition")
    4073        condition = f" IF {condition}" if condition else ""
    4074        return f"{this} FOR {expr} IN {iterator}{condition}"

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

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

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

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

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

    4082    def predict_sql(self, expression: exp.Predict) -> str:
    4083        model = self.sql(expression, "this")
    4084        model = f"MODEL {model}"
    4085        table = self.sql(expression, "expression")
    4086        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
    4087        parameters = self.sql(expression, "params_struct")
    4088        return self.func("PREDICT", model, table, parameters or None)

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

    4090    def forin_sql(self, expression: exp.ForIn) -> str:
    4091        this = self.sql(expression, "this")
    4092        expression_sql = self.sql(expression, "expression")
    4093        return f"FOR {this} DO {expression_sql}"

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

    4095    def refresh_sql(self, expression: exp.Refresh) -> str:
    4096        this = self.sql(expression, "this")
    4097        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
    4098        return f"REFRESH {table}{this}"

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

    4100    def toarray_sql(self, expression: exp.ToArray) -> str:
    4101        arg = expression.this
    4102        if not arg.type:
    4103            from sqlglot.optimizer.annotate_types import annotate_types
    4104
    4105            arg = annotate_types(arg, dialect=self.dialect)
    4106
    4107        if arg.is_type(exp.DataType.Type.ARRAY):
    4108            return self.sql(arg)
    4109
    4110        cond_for_null = arg.is_(exp.null())
    4111        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

    4113    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
    4114        this = expression.this
    4115        time_format = self.format_time(expression)
    4116
    4117        if time_format:
    4118            return self.sql(
    4119                exp.cast(
    4120                    exp.StrToTime(this=this, format=expression.args["format"]),
    4121                    exp.DataType.Type.TIME,
    4122                )
    4123            )
    4124
    4125        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
    4126            return self.sql(this)
    4127
    4128        return self.sql(exp.cast(this, exp.DataType.Type.TIME))

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

    4130    def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str:
    4131        this = expression.this
    4132        if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP):
    4133            return self.sql(this)
    4134
    4135        return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect))

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

    4137    def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str:
    4138        this = expression.this
    4139        if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME):
    4140            return self.sql(this)
    4141
    4142        return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect))

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

    4144    def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:
    4145        this = expression.this
    4146        time_format = self.format_time(expression)
    4147
    4148        if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT):
    4149            return self.sql(
    4150                exp.cast(
    4151                    exp.StrToTime(this=this, format=expression.args["format"]),
    4152                    exp.DataType.Type.DATE,
    4153                )
    4154            )
    4155
    4156        if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE):
    4157            return self.sql(this)
    4158
    4159        return self.sql(exp.cast(this, exp.DataType.Type.DATE))

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

    4161    def unixdate_sql(self, expression: exp.UnixDate) -> str:
    4162        return self.sql(
    4163            exp.func(
    4164                "DATEDIFF",
    4165                expression.this,
    4166                exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE),
    4167                "day",
    4168            )
    4169        )

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

    4171    def lastday_sql(self, expression: exp.LastDay) -> str:
    4172        if self.LAST_DAY_SUPPORTS_DATE_PART:
    4173            return self.function_fallback_sql(expression)
    4174
    4175        unit = expression.text("unit")
    4176        if unit and unit != "MONTH":
    4177            self.unsupported("Date parts are not supported in LAST_DAY.")
    4178
    4179        return self.func("LAST_DAY", expression.this)

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

    4181    def dateadd_sql(self, expression: exp.DateAdd) -> str:
    4182        from sqlglot.dialects.dialect import unit_to_str
    4183
    4184        return self.func(
    4185            "DATE_ADD", expression.this, expression.expression, unit_to_str(expression)
    4186        )

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

    4188    def arrayany_sql(self, expression: exp.ArrayAny) -> str:
    4189        if self.CAN_IMPLEMENT_ARRAY_ANY:
    4190            filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression)
    4191            filtered_not_empty = exp.ArraySize(this=filtered).neq(0)
    4192            original_is_empty = exp.ArraySize(this=expression.this).eq(0)
    4193            return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty)))
    4194
    4195        from sqlglot.dialects import Dialect
    4196
    4197        # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect
    4198        if self.dialect.__class__ != Dialect:
    4199            self.unsupported("ARRAY_ANY is unsupported")
    4200
    4201        return self.function_fallback_sql(expression)

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

    4203    def struct_sql(self, expression: exp.Struct) -> str:
    4204        expression.set(
    4205            "expressions",
    4206            [
    4207                exp.alias_(e.expression, e.name if e.this.is_string else e.this)
    4208                if isinstance(e, exp.PropertyEQ)
    4209                else e
    4210                for e in expression.expressions
    4211            ],
    4212        )
    4213
    4214        return self.function_fallback_sql(expression)

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

    4216    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
    4217        low = self.sql(expression, "this")
    4218        high = self.sql(expression, "expression")
    4219
    4220        return f"{low} TO {high}"

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

    4222    def truncatetable_sql(self, expression: exp.TruncateTable) -> str:
    4223        target = "DATABASE" if expression.args.get("is_database") else "TABLE"
    4224        tables = f" {self.expressions(expression)}"
    4225
    4226        exists = " IF EXISTS" if expression.args.get("exists") else ""
    4227
    4228        on_cluster = self.sql(expression, "cluster")
    4229        on_cluster = f" {on_cluster}" if on_cluster else ""
    4230
    4231        identity = self.sql(expression, "identity")
    4232        identity = f" {identity} IDENTITY" if identity else ""
    4233
    4234        option = self.sql(expression, "option")
    4235        option = f" {option}" if option else ""
    4236
    4237        partition = self.sql(expression, "partition")
    4238        partition = f" {partition}" if partition else ""
    4239
    4240        return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"

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

    4244    def convert_sql(self, expression: exp.Convert) -> str:
    4245        to = expression.this
    4246        value = expression.expression
    4247        style = expression.args.get("style")
    4248        safe = expression.args.get("safe")
    4249        strict = expression.args.get("strict")
    4250
    4251        if not to or not value:
    4252            return ""
    4253
    4254        # Retrieve length of datatype and override to default if not specified
    4255        if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    4256            to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
    4257
    4258        transformed: t.Optional[exp.Expression] = None
    4259        cast = exp.Cast if strict else exp.TryCast
    4260
    4261        # Check whether a conversion with format (T-SQL calls this 'style') is applicable
    4262        if isinstance(style, exp.Literal) and style.is_int:
    4263            from sqlglot.dialects.tsql import TSQL
    4264
    4265            style_value = style.name
    4266            converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value)
    4267            if not converted_style:
    4268                self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}")
    4269
    4270            fmt = exp.Literal.string(converted_style)
    4271
    4272            if to.this == exp.DataType.Type.DATE:
    4273                transformed = exp.StrToDate(this=value, format=fmt)
    4274            elif to.this in (exp.DataType.Type.DATETIME, exp.DataType.Type.DATETIME2):
    4275                transformed = exp.StrToTime(this=value, format=fmt)
    4276            elif to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    4277                transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe)
    4278            elif to.this == exp.DataType.Type.TEXT:
    4279                transformed = exp.TimeToStr(this=value, format=fmt)
    4280
    4281        if not transformed:
    4282            transformed = cast(this=value, to=to, safe=safe)
    4283
    4284        return self.sql(transformed)

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

    4352    def copyparameter_sql(self, expression: exp.CopyParameter) -> str:
    4353        option = self.sql(expression, "this")
    4354
    4355        if expression.expressions:
    4356            upper = option.upper()
    4357
    4358            # Snowflake FILE_FORMAT options are separated by whitespace
    4359            sep = " " if upper == "FILE_FORMAT" else ", "
    4360
    4361            # Databricks copy/format options do not set their list of values with EQ
    4362            op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = "
    4363            values = self.expressions(expression, flat=True, sep=sep)
    4364            return f"{option}{op}({values})"
    4365
    4366        value = self.sql(expression, "expression")
    4367
    4368        if not value:
    4369            return option
    4370
    4371        op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " "
    4372
    4373        return f"{option}{op}{value}"

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

    4375    def credentials_sql(self, expression: exp.Credentials) -> str:
    4376        cred_expr = expression.args.get("credentials")
    4377        if isinstance(cred_expr, exp.Literal):
    4378            # Redshift case: CREDENTIALS <string>
    4379            credentials = self.sql(expression, "credentials")
    4380            credentials = f"CREDENTIALS {credentials}" if credentials else ""
    4381        else:
    4382            # Snowflake case: CREDENTIALS = (...)
    4383            credentials = self.expressions(expression, key="credentials", flat=True, sep=" ")
    4384            credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else ""
    4385
    4386        storage = self.sql(expression, "storage")
    4387        storage = f"STORAGE_INTEGRATION = {storage}" if storage else ""
    4388
    4389        encryption = self.expressions(expression, key="encryption", flat=True, sep=" ")
    4390        encryption = f" ENCRYPTION = ({encryption})" if encryption else ""
    4391
    4392        iam_role = self.sql(expression, "iam_role")
    4393        iam_role = f"IAM_ROLE {iam_role}" if iam_role else ""
    4394
    4395        region = self.sql(expression, "region")
    4396        region = f" REGION {region}" if region else ""
    4397
    4398        return f"{credentials}{storage}{encryption}{iam_role}{region}"

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

    4400    def copy_sql(self, expression: exp.Copy) -> str:
    4401        this = self.sql(expression, "this")
    4402        this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}"
    4403
    4404        credentials = self.sql(expression, "credentials")
    4405        credentials = self.seg(credentials) if credentials else ""
    4406        kind = self.seg("FROM" if expression.args.get("kind") else "TO")
    4407        files = self.expressions(expression, key="files", flat=True)
    4408
    4409        sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " "
    4410        params = self.expressions(
    4411            expression,
    4412            key="params",
    4413            sep=sep,
    4414            new_line=True,
    4415            skip_last=True,
    4416            skip_first=True,
    4417            indent=self.COPY_PARAMS_ARE_WRAPPED,
    4418        )
    4419
    4420        if params:
    4421            if self.COPY_PARAMS_ARE_WRAPPED:
    4422                params = f" WITH ({params})"
    4423            elif not self.pretty:
    4424                params = f" {params}"
    4425
    4426        return f"COPY{this}{kind} {files}{credentials}{params}"

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

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

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

    4431    def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str:
    4432        on_sql = "ON" if expression.args.get("on") else "OFF"
    4433        filter_col: t.Optional[str] = self.sql(expression, "filter_column")
    4434        filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None
    4435        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    4436        retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None
    4437
    4438        if filter_col or retention_period:
    4439            on_sql = self.func("ON", filter_col, retention_period)
    4440
    4441        return f"DATA_DELETION={on_sql}"

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

    4443    def maskingpolicycolumnconstraint_sql(
    4444        self, expression: exp.MaskingPolicyColumnConstraint
    4445    ) -> str:
    4446        this = self.sql(expression, "this")
    4447        expressions = self.expressions(expression, flat=True)
    4448        expressions = f" USING ({expressions})" if expressions else ""
    4449        return f"MASKING POLICY {this}{expressions}"

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

    4451    def gapfill_sql(self, expression: exp.GapFill) -> str:
    4452        this = self.sql(expression, "this")
    4453        this = f"TABLE {this}"
    4454        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

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

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

    4459    def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str:
    4460        this = self.sql(expression, "this")
    4461        expr = expression.expression
    4462
    4463        if isinstance(expr, exp.Func):
    4464            # T-SQL's CLR functions are case sensitive
    4465            expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})"
    4466        else:
    4467            expr = self.sql(expression, "expression")
    4468
    4469        return self.scope_resolution(expr, this)

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

    4471    def parsejson_sql(self, expression: exp.ParseJSON) -> str:
    4472        if self.PARSE_JSON_NAME is None:
    4473            return self.sql(expression.this)
    4474
    4475        return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression)

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

    4477    def rand_sql(self, expression: exp.Rand) -> str:
    4478        lower = self.sql(expression, "lower")
    4479        upper = self.sql(expression, "upper")
    4480
    4481        if lower and upper:
    4482            return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}"
    4483        return self.func("RAND", expression.this)

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

    4485    def changes_sql(self, expression: exp.Changes) -> str:
    4486        information = self.sql(expression, "information")
    4487        information = f"INFORMATION => {information}"
    4488        at_before = self.sql(expression, "at_before")
    4489        at_before = f"{self.seg('')}{at_before}" if at_before else ""
    4490        end = self.sql(expression, "end")
    4491        end = f"{self.seg('')}{end}" if end else ""
    4492
    4493        return f"CHANGES ({information}){at_before}{end}"

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

    4495    def pad_sql(self, expression: exp.Pad) -> str:
    4496        prefix = "L" if expression.args.get("is_left") else "R"
    4497
    4498        fill_pattern = self.sql(expression, "fill_pattern") or None
    4499        if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED:
    4500            fill_pattern = "' '"
    4501
    4502        return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)

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

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

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

    4508    def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str:
    4509        generate_series = exp.GenerateSeries(**expression.args)
    4510
    4511        parent = expression.parent
    4512        if isinstance(parent, (exp.Alias, exp.TableAlias)):
    4513            parent = parent.parent
    4514
    4515        if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)):
    4516            return self.sql(exp.Unnest(expressions=[generate_series]))
    4517
    4518        if isinstance(parent, exp.Select):
    4519            self.unsupported("GenerateSeries projection unnesting is not supported.")
    4520
    4521        return self.sql(generate_series)

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

    4523    def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str:
    4524        exprs = expression.expressions
    4525        if not self.ARRAY_CONCAT_IS_VAR_LEN:
    4526            rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs)
    4527        else:
    4528            rhs = self.expressions(expression)
    4529
    4530        return self.func(name, expression.this, rhs or None)

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

    4532    def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str:
    4533        if self.SUPPORTS_CONVERT_TIMEZONE:
    4534            return self.function_fallback_sql(expression)
    4535
    4536        source_tz = expression.args.get("source_tz")
    4537        target_tz = expression.args.get("target_tz")
    4538        timestamp = expression.args.get("timestamp")
    4539
    4540        if source_tz and timestamp:
    4541            timestamp = exp.AtTimeZone(
    4542                this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz
    4543            )
    4544
    4545        expr = exp.AtTimeZone(this=timestamp, zone=target_tz)
    4546
    4547        return self.sql(expr)

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

    4549    def json_sql(self, expression: exp.JSON) -> str:
    4550        this = self.sql(expression, "this")
    4551        this = f" {this}" if this else ""
    4552
    4553        _with = expression.args.get("with")
    4554
    4555        if _with is None:
    4556            with_sql = ""
    4557        elif not _with:
    4558            with_sql = " WITHOUT"
    4559        else:
    4560            with_sql = " WITH"
    4561
    4562        unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else ""
    4563
    4564        return f"JSON{this}{with_sql}{unique_sql}"

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

    4566    def jsonvalue_sql(self, expression: exp.JSONValue) -> str:
    4567        def _generate_on_options(arg: t.Any) -> str:
    4568            return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}"
    4569
    4570        path = self.sql(expression, "path")
    4571        returning = self.sql(expression, "returning")
    4572        returning = f" RETURNING {returning}" if returning else ""
    4573
    4574        on_condition = self.sql(expression, "on_condition")
    4575        on_condition = f" {on_condition}" if on_condition else ""
    4576
    4577        return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}")

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

    4579    def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str:
    4580        else_ = "ELSE " if expression.args.get("else_") else ""
    4581        condition = self.sql(expression, "expression")
    4582        condition = f"WHEN {condition} THEN " if condition else else_
    4583        insert = self.sql(expression, "this")[len("INSERT") :].strip()
    4584        return f"{condition}{insert}"

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

    4586    def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str:
    4587        kind = self.sql(expression, "kind")
    4588        expressions = self.seg(self.expressions(expression, sep=" "))
    4589        res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}"
    4590        return res

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

    4592    def oncondition_sql(self, expression: exp.OnCondition) -> str:
    4593        # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR"
    4594        empty = expression.args.get("empty")
    4595        empty = (
    4596            f"DEFAULT {empty} ON EMPTY"
    4597            if isinstance(empty, exp.Expression)
    4598            else self.sql(expression, "empty")
    4599        )
    4600
    4601        error = expression.args.get("error")
    4602        error = (
    4603            f"DEFAULT {error} ON ERROR"
    4604            if isinstance(error, exp.Expression)
    4605            else self.sql(expression, "error")
    4606        )
    4607
    4608        if error and empty:
    4609            error = (
    4610                f"{empty} {error}"
    4611                if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR
    4612                else f"{error} {empty}"
    4613            )
    4614            empty = ""
    4615
    4616        null = self.sql(expression, "null")
    4617
    4618        return f"{empty}{error}{null}"

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

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

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

    4624    def jsonexists_sql(self, expression: exp.JSONExists) -> str:
    4625        this = self.sql(expression, "this")
    4626        path = self.sql(expression, "path")
    4627
    4628        passing = self.expressions(expression, "passing")
    4629        passing = f" PASSING {passing}" if passing else ""
    4630
    4631        on_condition = self.sql(expression, "on_condition")
    4632        on_condition = f" {on_condition}" if on_condition else ""
    4633
    4634        path = f"{path}{passing}{on_condition}"
    4635
    4636        return self.func("JSON_EXISTS", this, path)

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

    4638    def arrayagg_sql(self, expression: exp.ArrayAgg) -> str:
    4639        array_agg = self.function_fallback_sql(expression)
    4640
    4641        # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls
    4642        # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB)
    4643        if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"):
    4644            parent = expression.parent
    4645            if isinstance(parent, exp.Filter):
    4646                parent_cond = parent.expression.this
    4647                parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_()))
    4648            else:
    4649                this = expression.this
    4650                # Do not add the filter if the input is not a column (e.g. literal, struct etc)
    4651                if this.find(exp.Column):
    4652                    # DISTINCT is already present in the agg function, do not propagate it to FILTER as well
    4653                    this_sql = (
    4654                        self.expressions(this)
    4655                        if isinstance(this, exp.Distinct)
    4656                        else self.sql(expression, "this")
    4657                    )
    4658
    4659                    array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)"
    4660
    4661        return array_agg

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

    4663    def apply_sql(self, expression: exp.Apply) -> str:
    4664        this = self.sql(expression, "this")
    4665        expr = self.sql(expression, "expression")
    4666
    4667        return f"{this} APPLY({expr})"

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

    4669    def grant_sql(self, expression: exp.Grant) -> str:
    4670        privileges_sql = self.expressions(expression, key="privileges", flat=True)
    4671
    4672        kind = self.sql(expression, "kind")
    4673        kind = f" {kind}" if kind else ""
    4674
    4675        securable = self.sql(expression, "securable")
    4676        securable = f" {securable}" if securable else ""
    4677
    4678        principals = self.expressions(expression, key="principals", flat=True)
    4679
    4680        grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else ""
    4681
    4682        return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}"

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

    4684    def grantprivilege_sql(self, expression: exp.GrantPrivilege):
    4685        this = self.sql(expression, "this")
    4686        columns = self.expressions(expression, flat=True)
    4687        columns = f"({columns})" if columns else ""
    4688
    4689        return f"{this}{columns}"

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

    4691    def grantprincipal_sql(self, expression: exp.GrantPrincipal):
    4692        this = self.sql(expression, "this")
    4693
    4694        kind = self.sql(expression, "kind")
    4695        kind = f"{kind} " if kind else ""
    4696
    4697        return f"{kind}{this}"

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

    4699    def columns_sql(self, expression: exp.Columns):
    4700        func = self.function_fallback_sql(expression)
    4701        if expression.args.get("unpack"):
    4702            func = f"*{func}"
    4703
    4704        return func

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

    4706    def overlay_sql(self, expression: exp.Overlay):
    4707        this = self.sql(expression, "this")
    4708        expr = self.sql(expression, "expression")
    4709        from_sql = self.sql(expression, "from")
    4710        for_sql = self.sql(expression, "for")
    4711        for_sql = f" FOR {for_sql}" if for_sql else ""
    4712
    4713        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

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

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

    4719    def string_sql(self, expression: exp.String) -> str:
    4720        this = expression.this
    4721        zone = expression.args.get("zone")
    4722
    4723        if zone:
    4724            # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>)
    4725            # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC
    4726            # set for source_tz to transpile the time conversion before the STRING cast
    4727            this = exp.ConvertTimezone(
    4728                source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this
    4729            )
    4730
    4731        return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR))

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

    4733    def median_sql(self, expression: exp.Median):
    4734        if not self.SUPPORTS_MEDIAN:
    4735            return self.sql(
    4736                exp.PercentileCont(this=expression.this, expression=exp.Literal.number(0.5))
    4737            )
    4738
    4739        return self.function_fallback_sql(expression)

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

    4741    def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str:
    4742        filler = self.sql(expression, "this")
    4743        filler = f" {filler}" if filler else ""
    4744        with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT"
    4745        return f"TRUNCATE{filler} {with_count}"

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

    4747    def unixseconds_sql(self, expression: exp.UnixSeconds) -> str:
    4748        if self.SUPPORTS_UNIX_SECONDS:
    4749            return self.function_fallback_sql(expression)
    4750
    4751        start_ts = exp.cast(
    4752            exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ
    4753        )
    4754
    4755        return self.sql(
    4756            exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS"))
    4757        )

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

    4759    def arraysize_sql(self, expression: exp.ArraySize) -> str:
    4760        dim = expression.expression
    4761
    4762        # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension)
    4763        if dim and self.ARRAY_SIZE_DIM_REQUIRED is None:
    4764            if not (dim.is_int and dim.name == "1"):
    4765                self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH")
    4766            dim = None
    4767
    4768        # If dimension is required but not specified, default initialize it
    4769        if self.ARRAY_SIZE_DIM_REQUIRED and not dim:
    4770            dim = exp.Literal.number(1)
    4771
    4772        return self.func(self.ARRAY_SIZE_NAME, expression.this, dim)

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

    4774    def attach_sql(self, expression: exp.Attach) -> str:
    4775        this = self.sql(expression, "this")
    4776        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
    4777        expressions = self.expressions(expression)
    4778        expressions = f" ({expressions})" if expressions else ""
    4779
    4780        return f"ATTACH{exists_sql} {this}{expressions}"

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

    4782    def detach_sql(self, expression: exp.Detach) -> str:
    4783        this = self.sql(expression, "this")
    4784        # the DATABASE keyword is required if IF EXISTS is set
    4785        # without it, DuckDB throws an error: Parser Error: syntax error at or near "exists" (Line Number: 1)
    4786        # ref: https://duckdb.org/docs/stable/sql/statements/attach.html#detach-syntax
    4787        exists_sql = " DATABASE IF EXISTS" if expression.args.get("exists") else ""
    4788
    4789        return f"DETACH{exists_sql} {this}"

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

    4791    def attachoption_sql(self, expression: exp.AttachOption) -> str:
    4792        this = self.sql(expression, "this")
    4793        value = self.sql(expression, "expression")
    4794        value = f" {value}" if value else ""
    4795        return f"{this}{value}"

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

    4797    def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str:
    4798        this_sql = self.sql(expression, "this")
    4799        if isinstance(expression.this, exp.Table):
    4800            this_sql = f"TABLE {this_sql}"
    4801
    4802        return self.func(
    4803            "FEATURES_AT_TIME",
    4804            this_sql,
    4805            expression.args.get("time"),
    4806            expression.args.get("num_rows"),
    4807            expression.args.get("ignore_feature_nulls"),
    4808        )

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

    4810    def watermarkcolumnconstraint_sql(self, expression: exp.WatermarkColumnConstraint) -> str:
    4811        return (
    4812            f"WATERMARK FOR {self.sql(expression, 'this')} AS {self.sql(expression, 'expression')}"
    4813        )

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

    4815    def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str:
    4816        encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE"
    4817        encode = f"{encode} {self.sql(expression, 'this')}"
    4818
    4819        properties = expression.args.get("properties")
    4820        if properties:
    4821            encode = f"{encode} {self.properties(properties)}"
    4822
    4823        return encode

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

    4825    def includeproperty_sql(self, expression: exp.IncludeProperty) -> str:
    4826        this = self.sql(expression, "this")
    4827        include = f"INCLUDE {this}"
    4828
    4829        column_def = self.sql(expression, "column_def")
    4830        if column_def:
    4831            include = f"{include} {column_def}"
    4832
    4833        alias = self.sql(expression, "alias")
    4834        if alias:
    4835            include = f"{include} AS {alias}"
    4836
    4837        return include

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

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

def xmlkeyvalueoption_sql(self, expression: sqlglot.expressions.XMLKeyValueOption) -> str: View Source

    4843    def xmlkeyvalueoption_sql(self, expression: exp.XMLKeyValueOption) -> str:
    4844        this = self.sql(expression, "this")
    4845        expr = self.sql(expression, "expression")
    4846        expr = f"({expr})" if expr else ""
    4847        return f"{this}{expr}"

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

    4849    def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str:
    4850        partitions = self.expressions(expression, "partition_expressions")
    4851        create = self.expressions(expression, "create_expressions")
    4852        return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}"

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

    4854    def partitionbyrangepropertydynamic_sql(
    4855        self, expression: exp.PartitionByRangePropertyDynamic
    4856    ) -> str:
    4857        start = self.sql(expression, "start")
    4858        end = self.sql(expression, "end")
    4859
    4860        every = expression.args["every"]
    4861        if isinstance(every, exp.Interval) and every.this.is_string:
    4862            every.this.replace(exp.Literal.number(every.name))
    4863
    4864        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

    4866    def unpivotcolumns_sql(self, expression: exp.UnpivotColumns) -> str:
    4867        name = self.sql(expression, "this")
    4868        values = self.expressions(expression, flat=True)
    4869
    4870        return f"NAME {name} VALUE {values}"

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

    4872    def analyzesample_sql(self, expression: exp.AnalyzeSample) -> str:
    4873        kind = self.sql(expression, "kind")
    4874        sample = self.sql(expression, "sample")
    4875        return f"SAMPLE {sample} {kind}"

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

    4877    def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str:
    4878        kind = self.sql(expression, "kind")
    4879        option = self.sql(expression, "option")
    4880        option = f" {option}" if option else ""
    4881        this = self.sql(expression, "this")
    4882        this = f" {this}" if this else ""
    4883        columns = self.expressions(expression)
    4884        columns = f" {columns}" if columns else ""
    4885        return f"{kind}{option} STATISTICS{this}{columns}"

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

    4887    def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str:
    4888        this = self.sql(expression, "this")
    4889        columns = self.expressions(expression)
    4890        inner_expression = self.sql(expression, "expression")
    4891        inner_expression = f" {inner_expression}" if inner_expression else ""
    4892        update_options = self.sql(expression, "update_options")
    4893        update_options = f" {update_options} UPDATE" if update_options else ""
    4894        return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}"

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

    4896    def analyzedelete_sql(self, expression: exp.AnalyzeDelete) -> str:
    4897        kind = self.sql(expression, "kind")
    4898        kind = f" {kind}" if kind else ""
    4899        return f"DELETE{kind} STATISTICS"

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

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

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

    4905    def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str:
    4906        kind = self.sql(expression, "kind")
    4907        this = self.sql(expression, "this")
    4908        this = f" {this}" if this else ""
    4909        inner_expression = self.sql(expression, "expression")
    4910        return f"VALIDATE {kind}{this}{inner_expression}"

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

    4912    def analyze_sql(self, expression: exp.Analyze) -> str:
    4913        options = self.expressions(expression, key="options", sep=" ")
    4914        options = f" {options}" if options else ""
    4915        kind = self.sql(expression, "kind")
    4916        kind = f" {kind}" if kind else ""
    4917        this = self.sql(expression, "this")
    4918        this = f" {this}" if this else ""
    4919        mode = self.sql(expression, "mode")
    4920        mode = f" {mode}" if mode else ""
    4921        properties = self.sql(expression, "properties")
    4922        properties = f" {properties}" if properties else ""
    4923        partition = self.sql(expression, "partition")
    4924        partition = f" {partition}" if partition else ""
    4925        inner_expression = self.sql(expression, "expression")
    4926        inner_expression = f" {inner_expression}" if inner_expression else ""
    4927        return f"ANALYZE{options}{kind}{this}{partition}{mode}{inner_expression}{properties}"

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

    4929    def xmltable_sql(self, expression: exp.XMLTable) -> str:
    4930        this = self.sql(expression, "this")
    4931        namespaces = self.expressions(expression, key="namespaces")
    4932        namespaces = f"XMLNAMESPACES({namespaces}), " if namespaces else ""
    4933        passing = self.expressions(expression, key="passing")
    4934        passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else ""
    4935        columns = self.expressions(expression, key="columns")
    4936        columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else ""
    4937        by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else ""
    4938        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

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

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

    4944    def export_sql(self, expression: exp.Export) -> str:
    4945        this = self.sql(expression, "this")
    4946        connection = self.sql(expression, "connection")
    4947        connection = f"WITH CONNECTION {connection} " if connection else ""
    4948        options = self.sql(expression, "options")
    4949        return f"EXPORT DATA {connection}{options} AS {this}"

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

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

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

    4954    def declareitem_sql(self, expression: exp.DeclareItem) -> str:
    4955        variable = self.sql(expression, "this")
    4956        default = self.sql(expression, "default")
    4957        default = f" = {default}" if default else ""
    4958
    4959        kind = self.sql(expression, "kind")
    4960        if isinstance(expression.args.get("kind"), exp.Schema):
    4961            kind = f"TABLE {kind}"
    4962
    4963        return f"{variable} AS {kind}{default}"

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

    4965    def recursivewithsearch_sql(self, expression: exp.RecursiveWithSearch) -> str:
    4966        kind = self.sql(expression, "kind")
    4967        this = self.sql(expression, "this")
    4968        set = self.sql(expression, "expression")
    4969        using = self.sql(expression, "using")
    4970        using = f" USING {using}" if using else ""
    4971
    4972        kind_sql = kind if kind == "CYCLE" else f"SEARCH {kind} FIRST BY"
    4973
    4974        return f"{kind_sql} {this} SET {set}{using}"

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

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

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

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

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

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

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

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

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

    4989    def show_sql(self, expression: exp.Show) -> str:
    4990        self.unsupported("Unsupported SHOW statement")
    4991        return ""

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

    4993    def get_put_sql(self, expression: exp.Put | exp.Get) -> str:
    4994        # Snowflake GET/PUT statements:
    4995        #   PUT <file> <internalStage> <properties>
    4996        #   GET <internalStage> <file> <properties>
    4997        props = expression.args.get("properties")
    4998        props_sql = self.properties(props, prefix=" ", sep=" ", wrapped=False) if props else ""
    4999        this = self.sql(expression, "this")
    5000        target = self.sql(expression, "target")
    5001
    5002        if isinstance(expression, exp.Put):
    5003            return f"PUT {this} {target}{props_sql}"
    5004        else:
    5005            return f"GET {target} {this}{props_sql}"

def translatecharacters_sql(self, expression: sqlglot.expressions.TranslateCharacters): View Source

    5007    def translatecharacters_sql(self, expression: exp.TranslateCharacters):
    5008        this = self.sql(expression, "this")
    5009        expr = self.sql(expression, "expression")
    5010        with_error = " WITH ERROR" if expression.args.get("with_error") else ""
    5011        return f"TRANSLATE({this} USING {expr}{with_error})"