Edit on GitHub

# sqlglot.generator

View Source

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

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

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

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

class Generator: View Source

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

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.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None) View Source

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

TRANSFORMS: Dict[Type[sqlglot.expressions.Expression], Callable[..., str]] = {<class 'sqlglot.expressions.JSONPathFilter'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathKey'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathRecursive'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathRoot'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathScript'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSelector'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSlice'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSubscript'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathUnion'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathWildcard'>: <function <lambda>>, <class 'sqlglot.expressions.AllowedValuesProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AnalyzeColumns'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AnalyzeWith'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ArrayContainsAll'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ArrayOverlaps'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AutoRefreshProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.BackupProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CaseSpecificColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Ceil'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CommentColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ConnectByRoot'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DateFormatColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DefaultColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DynamicProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EmptyProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EncodeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EphemeralColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExcludeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Except'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExternalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Floor'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.GlobalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.HeapProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.IcebergProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InheritsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InlineLengthColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Intersect'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.IntervalSpan'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Int64'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LanguageProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LocationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.MaterializedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NonClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NotForReplicationColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnCommitProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnUpdateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Operator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OutputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PivotAny'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ProjectionPolicyColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ReturnsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SampleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SecureProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetConfigProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SharingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlReadWriteProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StabilityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Stream'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StreamingTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StrictProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SwapTable'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TemporaryProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Tags'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Union'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UnloggedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UsingData'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Uuid'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VarMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ViewAttributeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithProcedureOptions'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithSchemaBindingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithOperator'>: <function Generator.<lambda>>}
NULL_ORDERING_SUPPORTED: Optional[bool] = True
IGNORE_NULLS_IN_FUNC = False
LOCKING_READS_SUPPORTED = False
EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = True
WRAP_DERIVED_VALUES = True
CREATE_FUNCTION_RETURN_AS = True
MATCHED_BY_SOURCE = True
SINGLE_STRING_INTERVAL = False
INTERVAL_ALLOWS_PLURAL_FORM = True
LIMIT_FETCH = 'ALL'
LIMIT_ONLY_LITERALS = False
RENAME_TABLE_WITH_DB = True
GROUPINGS_SEP = ','
INDEX_ON = 'ON'
JOIN_HINTS = True
TABLE_HINTS = True
QUERY_HINTS = True
QUERY_HINT_SEP = ', '
IS_BOOL_ALLOWED = True
DUPLICATE_KEY_UPDATE_WITH_SET = True
LIMIT_IS_TOP = False
RETURNING_END = True
EXTRACT_ALLOWS_QUOTES = True
TZ_TO_WITH_TIME_ZONE = False
NVL2_SUPPORTED = True
SELECT_KINDS: Tuple[str, ...] = ('STRUCT', 'VALUE')
VALUES_AS_TABLE = True
ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = True
UNNEST_WITH_ORDINALITY = True
AGGREGATE_FILTER_SUPPORTED = True
SEMI_ANTI_JOIN_WITH_SIDE = True
COMPUTED_COLUMN_WITH_TYPE = True
SUPPORTS_TABLE_COPY = True
TABLESAMPLE_REQUIRES_PARENS = True
TABLESAMPLE_SIZE_IS_ROWS = True
TABLESAMPLE_KEYWORDS = 'TABLESAMPLE'
TABLESAMPLE_WITH_METHOD = True
TABLESAMPLE_SEED_KEYWORD = 'SEED'
COLLATE_IS_FUNC = False
DATA_TYPE_SPECIFIERS_ALLOWED = False
ENSURE_BOOLS = False
CTE_RECURSIVE_KEYWORD_REQUIRED = True
SUPPORTS_SINGLE_ARG_CONCAT = True
LAST_DAY_SUPPORTS_DATE_PART = True
SUPPORTS_TABLE_ALIAS_COLUMNS = True
UNPIVOT_ALIASES_ARE_IDENTIFIERS = True
JSON_KEY_VALUE_PAIR_SEP = ':'
INSERT_OVERWRITE = ' OVERWRITE TABLE'
SUPPORTS_SELECT_INTO = False
SUPPORTS_UNLOGGED_TABLES = False
SUPPORTS_CREATE_TABLE_LIKE = True
LIKE_PROPERTY_INSIDE_SCHEMA = False
MULTI_ARG_DISTINCT = True
JSON_TYPE_REQUIRED_FOR_EXTRACTION = False
JSON_PATH_BRACKETED_KEY_SUPPORTED = True
JSON_PATH_SINGLE_QUOTE_ESCAPE = False
SUPPORTED_JSON_PATH_PARTS = {<class 'sqlglot.expressions.JSONPathKey'>, <class 'sqlglot.expressions.JSONPathWildcard'>, <class 'sqlglot.expressions.JSONPathFilter'>, <class 'sqlglot.expressions.JSONPathUnion'>, <class 'sqlglot.expressions.JSONPathSubscript'>, <class 'sqlglot.expressions.JSONPathSelector'>, <class 'sqlglot.expressions.JSONPathSlice'>, <class 'sqlglot.expressions.JSONPathScript'>, <class 'sqlglot.expressions.JSONPathRoot'>, <class 'sqlglot.expressions.JSONPathRecursive'>}
CAN_IMPLEMENT_ARRAY_ANY = False
SUPPORTS_TO_NUMBER = True
SET_OP_MODIFIERS = True
COPY_PARAMS_ARE_WRAPPED = True
COPY_PARAMS_EQ_REQUIRED = False
COPY_HAS_INTO_KEYWORD = True
TRY_SUPPORTED = True
SUPPORTS_UESCAPE = True
STAR_EXCEPT = 'EXCEPT'
HEX_FUNC = 'HEX'
WITH_PROPERTIES_PREFIX = 'WITH'
QUOTE_JSON_PATH = True
PAD_FILL_PATTERN_IS_REQUIRED = False
SUPPORTS_EXPLODING_PROJECTIONS = True
ARRAY_CONCAT_IS_VAR_LEN = True
SUPPORTS_CONVERT_TIMEZONE = False
SUPPORTS_MEDIAN = True
SUPPORTS_UNIX_SECONDS = False
PARSE_JSON_NAME: Optional[str] = 'PARSE_JSON'
ARRAY_SIZE_NAME: str = 'ARRAY_LENGTH'
ARRAY_SIZE_DIM_REQUIRED: Optional[bool] = None
TYPE_MAPPING = {<Type.DATETIME2: 'DATETIME2'>: 'TIMESTAMP', <Type.NCHAR: 'NCHAR'>: 'CHAR', <Type.NVARCHAR: 'NVARCHAR'>: 'VARCHAR', <Type.MEDIUMTEXT: 'MEDIUMTEXT'>: 'TEXT', <Type.LONGTEXT: 'LONGTEXT'>: 'TEXT', <Type.TINYTEXT: 'TINYTEXT'>: 'TEXT', <Type.MEDIUMBLOB: 'MEDIUMBLOB'>: 'BLOB', <Type.LONGBLOB: 'LONGBLOB'>: 'BLOB', <Type.TINYBLOB: 'TINYBLOB'>: 'BLOB', <Type.INET: 'INET'>: 'INET', <Type.ROWVERSION: 'ROWVERSION'>: 'VARBINARY', <Type.SMALLDATETIME: 'SMALLDATETIME'>: 'TIMESTAMP'}
TIME_PART_SINGULARS = {'MICROSECONDS': 'MICROSECOND', 'SECONDS': 'SECOND', 'MINUTES': 'MINUTE', 'HOURS': 'HOUR', 'DAYS': 'DAY', 'WEEKS': 'WEEK', 'MONTHS': 'MONTH', 'QUARTERS': 'QUARTER', 'YEARS': 'YEAR'}
AFTER_HAVING_MODIFIER_TRANSFORMS = {'cluster': <function Generator.<lambda>>, 'distribute': <function Generator.<lambda>>, 'sort': <function Generator.<lambda>>, 'windows': <function Generator.<lambda>>, 'qualify': <function Generator.<lambda>>}
TOKEN_MAPPING: Dict[sqlglot.tokens.TokenType, str] = {}
STRUCT_DELIMITER = ('<', '>')
PARAMETER_TOKEN = '@'
NAMED_PLACEHOLDER_TOKEN = ':'
EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: Set[str] = set()
PROPERTIES_LOCATION = {<class 'sqlglot.expressions.AllowedValuesProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.AlgorithmProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.AutoIncrementProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.AutoRefreshProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.BackupProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.BlockCompressionProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CharacterSetProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ChecksumProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CollateProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Cluster'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ClusteredByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistributedByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DuplicateKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DataBlocksizeProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.DataDeletionProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DefinerProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.DictRange'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DictProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DynamicProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.DistKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistStyleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EmptyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EncodeProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.EngineProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExternalProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.FallbackProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.FileFormatProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.FreespaceProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.GlobalProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.HeapProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.InheritsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.IcebergProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.IncludeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.InputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.IsolatedLoadingProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.JournalProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.LanguageProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LikeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LocationProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LockProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LockingProperty'>: <Location.POST_ALIAS: 'POST_ALIAS'>, <class 'sqlglot.expressions.LogProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.MaterializedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.MergeBlockRatioProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.OnProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OnCommitProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.Order'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OutputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PartitionedByProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.PartitionedOfProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PrimaryKey'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Property'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ReturnsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatDelimitedProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatSerdeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SampleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SchemaCommentProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SecureProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.SecurityProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SerdeProperties'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Set'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SettingsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SetProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.SetConfigProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SharingProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.SequenceProperties'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.SortKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlReadWriteProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StabilityProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.StreamingTableProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StrictProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Tags'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.TemporaryProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.ToTableProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TransientProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.TransformModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.MergeTreeTTL'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.UnloggedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.ViewAttributeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.VolatileProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.WithDataProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.WithProcedureOptions'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.WithSchemaBindingProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.WithSystemVersioningProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>}
RESERVED_KEYWORDS: Set[str] = set()
WITH_SEPARATED_COMMENTS: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Command'>, <class 'sqlglot.expressions.Create'>, <class 'sqlglot.expressions.Describe'>, <class 'sqlglot.expressions.Delete'>, <class 'sqlglot.expressions.Drop'>, <class 'sqlglot.expressions.From'>, <class 'sqlglot.expressions.Insert'>, <class 'sqlglot.expressions.Join'>, <class 'sqlglot.expressions.MultitableInserts'>, <class 'sqlglot.expressions.Select'>, <class 'sqlglot.expressions.SetOperation'>, <class 'sqlglot.expressions.Update'>, <class 'sqlglot.expressions.Where'>, <class 'sqlglot.expressions.With'>)
EXCLUDE_COMMENTS: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Binary'>, <class 'sqlglot.expressions.SetOperation'>)
UNWRAPPED_INTERVAL_VALUES: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Column'>, <class 'sqlglot.expressions.Literal'>, <class 'sqlglot.expressions.Neg'>, <class 'sqlglot.expressions.Paren'>)
PARAMETERIZABLE_TEXT_TYPES = {<Type.NVARCHAR: 'NVARCHAR'>, <Type.CHAR: 'CHAR'>, <Type.VARCHAR: 'VARCHAR'>, <Type.NCHAR: 'NCHAR'>}
EXPRESSIONS_WITHOUT_NESTED_CTES: Set[Type[sqlglot.expressions.Expression]] = set()
SENTINEL_LINE_BREAK = '__SQLGLOT__LB__'
pretty
identify
normalize
pad
unsupported_level
max_unsupported
leading_comma
max_text_width
comments
dialect
normalize_functions
unsupported_messages: List[str]
def generate( self, expression: sqlglot.expressions.Expression, copy: bool = True) -> str: View Source

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

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

Apply generic preprocessing transformations to a given expression.

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

    776    def unsupported(self, message: str) -> None:
    777        if self.unsupported_level == ErrorLevel.IMMEDIATE:
    778            raise UnsupportedError(message)
    779        self.unsupported_messages.append(message)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    1042    def periodforsystemtimeconstraint_sql(
    1043        self, expression: exp.PeriodForSystemTimeConstraint
    1044    ) -> str:
    1045        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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    1271    def bitstring_sql(self, expression: exp.BitString) -> str:
    1272        this = self.sql(expression, "this")
    1273        if self.dialect.BIT_START:
    1274            return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}"
    1275        return f"{int(this, 2)}"

def hexstring_sql(self, expression: sqlglot.expressions.HexString) -> str: View Source

    1277    def hexstring_sql(self, expression: exp.HexString) -> str:
    1278        this = self.sql(expression, "this")
    1279        if self.dialect.HEX_START:
    1280            return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"
    1281        return f"{int(this, 16)}"

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

    1283    def bytestring_sql(self, expression: exp.ByteString) -> str:
    1284        this = self.sql(expression, "this")
    1285        if self.dialect.BYTE_START:
    1286            return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}"
    1287        return this

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

    1289    def unicodestring_sql(self, expression: exp.UnicodeString) -> str:
    1290        this = self.sql(expression, "this")
    1291        escape = expression.args.get("escape")
    1292
    1293        if self.dialect.UNICODE_START:
    1294            escape_substitute = r"\\\1"
    1295            left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END
    1296        else:
    1297            escape_substitute = r"\\u\1"
    1298            left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END
    1299
    1300        if escape:
    1301            escape_pattern = re.compile(rf"{escape.name}(\d+)")
    1302            escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else ""
    1303        else:
    1304            escape_pattern = ESCAPED_UNICODE_RE
    1305            escape_sql = ""
    1306
    1307        if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE):
    1308            this = escape_pattern.sub(escape_substitute, this)
    1309
    1310        return f"{left_quote}{this}{right_quote}{escape_sql}"

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

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

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

    1316    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
    1317        this = self.sql(expression, "this")
    1318        specifier = self.sql(expression, "expression")
    1319        specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else ""
    1320        return f"{this}{specifier}"

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

    1322    def datatype_sql(self, expression: exp.DataType) -> str:
    1323        nested = ""
    1324        values = ""
    1325        interior = self.expressions(expression, flat=True)
    1326
    1327        type_value = expression.this
    1328        if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"):
    1329            type_sql = self.sql(expression, "kind")
    1330        else:
    1331            type_sql = (
    1332                self.TYPE_MAPPING.get(type_value, type_value.value)
    1333                if isinstance(type_value, exp.DataType.Type)
    1334                else type_value
    1335            )
    1336
    1337        if interior:
    1338            if expression.args.get("nested"):
    1339                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
    1340                if expression.args.get("values") is not None:
    1341                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
    1342                    values = self.expressions(expression, key="values", flat=True)
    1343                    values = f"{delimiters[0]}{values}{delimiters[1]}"
    1344            elif type_value == exp.DataType.Type.INTERVAL:
    1345                nested = f" {interior}"
    1346            else:
    1347                nested = f"({interior})"
    1348
    1349        type_sql = f"{type_sql}{nested}{values}"
    1350        if self.TZ_TO_WITH_TIME_ZONE and type_value in (
    1351            exp.DataType.Type.TIMETZ,
    1352            exp.DataType.Type.TIMESTAMPTZ,
    1353        ):
    1354            type_sql = f"{type_sql} WITH TIME ZONE"
    1355
    1356        return type_sql

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

    1358    def directory_sql(self, expression: exp.Directory) -> str:
    1359        local = "LOCAL " if expression.args.get("local") else ""
    1360        row_format = self.sql(expression, "row_format")
    1361        row_format = f" {row_format}" if row_format else ""
    1362        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"

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

    1364    def delete_sql(self, expression: exp.Delete) -> str:
    1365        this = self.sql(expression, "this")
    1366        this = f" FROM {this}" if this else ""
    1367        using = self.sql(expression, "using")
    1368        using = f" USING {using}" if using else ""
    1369        cluster = self.sql(expression, "cluster")
    1370        cluster = f" {cluster}" if cluster else ""
    1371        where = self.sql(expression, "where")
    1372        returning = self.sql(expression, "returning")
    1373        limit = self.sql(expression, "limit")
    1374        tables = self.expressions(expression, key="tables")
    1375        tables = f" {tables}" if tables else ""
    1376        if self.RETURNING_END:
    1377            expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}"
    1378        else:
    1379            expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}"
    1380        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")

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

    1382    def drop_sql(self, expression: exp.Drop) -> str:
    1383        this = self.sql(expression, "this")
    1384        expressions = self.expressions(expression, flat=True)
    1385        expressions = f" ({expressions})" if expressions else ""
    1386        kind = expression.args["kind"]
    1387        kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind
    1388        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    1389        concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else ""
    1390        on_cluster = self.sql(expression, "cluster")
    1391        on_cluster = f" {on_cluster}" if on_cluster else ""
    1392        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    1393        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    1394        cascade = " CASCADE" if expression.args.get("cascade") else ""
    1395        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
    1396        purge = " PURGE" if expression.args.get("purge") else ""
    1397        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

    1399    def set_operation(self, expression: exp.SetOperation) -> str:
    1400        op_type = type(expression)
    1401        op_name = op_type.key.upper()
    1402
    1403        distinct = expression.args.get("distinct")
    1404        if (
    1405            distinct is False
    1406            and op_type in (exp.Except, exp.Intersect)
    1407            and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE
    1408        ):
    1409            self.unsupported(f"{op_name} ALL is not supported")
    1410
    1411        default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type]
    1412
    1413        if distinct is None:
    1414            distinct = default_distinct
    1415            if distinct is None:
    1416                self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified")
    1417
    1418        if distinct is default_distinct:
    1419            kind = ""
    1420        else:
    1421            kind = " DISTINCT" if distinct else " ALL"
    1422
    1423        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1424        return f"{op_name}{kind}{by_name}"

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

    1426    def set_operations(self, expression: exp.SetOperation) -> str:
    1427        if not self.SET_OP_MODIFIERS:
    1428            limit = expression.args.get("limit")
    1429            order = expression.args.get("order")
    1430
    1431            if limit or order:
    1432                select = self._move_ctes_to_top_level(
    1433                    exp.subquery(expression, "_l_0", copy=False).select("*", copy=False)
    1434                )
    1435
    1436                if limit:
    1437                    select = select.limit(limit.pop(), copy=False)
    1438                if order:
    1439                    select = select.order_by(order.pop(), copy=False)
    1440                return self.sql(select)
    1441
    1442        sqls: t.List[str] = []
    1443        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    1444
    1445        while stack:
    1446            node = stack.pop()
    1447
    1448            if isinstance(node, exp.SetOperation):
    1449                stack.append(node.expression)
    1450                stack.append(
    1451                    self.maybe_comment(
    1452                        self.set_operation(node), comments=node.comments, separated=True
    1453                    )
    1454                )
    1455                stack.append(node.this)
    1456            else:
    1457                sqls.append(self.sql(node))
    1458
    1459        this = self.sep().join(sqls)
    1460        this = self.query_modifiers(expression, this)
    1461        return self.prepend_ctes(expression, this)

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

    1463    def fetch_sql(self, expression: exp.Fetch) -> str:
    1464        direction = expression.args.get("direction")
    1465        direction = f" {direction}" if direction else ""
    1466        count = self.sql(expression, "count")
    1467        count = f" {count}" if count else ""
    1468        if expression.args.get("percent"):
    1469            count = f"{count} PERCENT"
    1470        with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY"
    1471        return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}"

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

    1473    def filter_sql(self, expression: exp.Filter) -> str:
    1474        if self.AGGREGATE_FILTER_SUPPORTED:
    1475            this = self.sql(expression, "this")
    1476            where = self.sql(expression, "expression").strip()
    1477            return f"{this} FILTER({where})"
    1478
    1479        agg = expression.this
    1480        agg_arg = agg.this
    1481        cond = expression.expression.this
    1482        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
    1483        return self.sql(agg)

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

    1485    def hint_sql(self, expression: exp.Hint) -> str:
    1486        if not self.QUERY_HINTS:
    1487            self.unsupported("Hints are not supported")
    1488            return ""
    1489
    1490        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"

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

    1492    def indexparameters_sql(self, expression: exp.IndexParameters) -> str:
    1493        using = self.sql(expression, "using")
    1494        using = f" USING {using}" if using else ""
    1495        columns = self.expressions(expression, key="columns", flat=True)
    1496        columns = f"({columns})" if columns else ""
    1497        partition_by = self.expressions(expression, key="partition_by", flat=True)
    1498        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
    1499        where = self.sql(expression, "where")
    1500        include = self.expressions(expression, key="include", flat=True)
    1501        if include:
    1502            include = f" INCLUDE ({include})"
    1503        with_storage = self.expressions(expression, key="with_storage", flat=True)
    1504        with_storage = f" WITH ({with_storage})" if with_storage else ""
    1505        tablespace = self.sql(expression, "tablespace")
    1506        tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else ""
    1507        on = self.sql(expression, "on")
    1508        on = f" ON {on}" if on else ""
    1509
    1510        return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"

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

    1512    def index_sql(self, expression: exp.Index) -> str:
    1513        unique = "UNIQUE " if expression.args.get("unique") else ""
    1514        primary = "PRIMARY " if expression.args.get("primary") else ""
    1515        amp = "AMP " if expression.args.get("amp") else ""
    1516        name = self.sql(expression, "this")
    1517        name = f"{name} " if name else ""
    1518        table = self.sql(expression, "table")
    1519        table = f"{self.INDEX_ON} {table}" if table else ""
    1520
    1521        index = "INDEX " if not table else ""
    1522
    1523        params = self.sql(expression, "params")
    1524        return f"{unique}{primary}{amp}{index}{name}{table}{params}"

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

    1526    def identifier_sql(self, expression: exp.Identifier) -> str:
    1527        text = expression.name
    1528        lower = text.lower()
    1529        text = lower if self.normalize and not expression.quoted else text
    1530        text = text.replace(self._identifier_end, self._escaped_identifier_end)
    1531        if (
    1532            expression.quoted
    1533            or self.dialect.can_identify(text, self.identify)
    1534            or lower in self.RESERVED_KEYWORDS
    1535            or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
    1536        ):
    1537            text = f"{self._identifier_start}{text}{self._identifier_end}"
    1538        return text

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

    1540    def hex_sql(self, expression: exp.Hex) -> str:
    1541        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1542        if self.dialect.HEX_LOWERCASE:
    1543            text = self.func("LOWER", text)
    1544
    1545        return text

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

    1547    def lowerhex_sql(self, expression: exp.LowerHex) -> str:
    1548        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1549        if not self.dialect.HEX_LOWERCASE:
    1550            text = self.func("LOWER", text)
    1551        return text

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

    1553    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    1554        input_format = self.sql(expression, "input_format")
    1555        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    1556        output_format = self.sql(expression, "output_format")
    1557        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    1558        return self.sep().join((input_format, output_format))

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

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

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

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

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

    1568    def properties_sql(self, expression: exp.Properties) -> str:
    1569        root_properties = []
    1570        with_properties = []
    1571
    1572        for p in expression.expressions:
    1573            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1574            if p_loc == exp.Properties.Location.POST_WITH:
    1575                with_properties.append(p)
    1576            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    1577                root_properties.append(p)
    1578
    1579        root_props = self.root_properties(exp.Properties(expressions=root_properties))
    1580        with_props = self.with_properties(exp.Properties(expressions=with_properties))
    1581
    1582        if root_props and with_props and not self.pretty:
    1583            with_props = " " + with_props
    1584
    1585        return root_props + with_props

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

    1587    def root_properties(self, properties: exp.Properties) -> str:
    1588        if properties.expressions:
    1589            return self.expressions(properties, indent=False, sep=" ")
    1590        return ""

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

    1592    def properties(
    1593        self,
    1594        properties: exp.Properties,
    1595        prefix: str = "",
    1596        sep: str = ", ",
    1597        suffix: str = "",
    1598        wrapped: bool = True,
    1599    ) -> str:
    1600        if properties.expressions:
    1601            expressions = self.expressions(properties, sep=sep, indent=False)
    1602            if expressions:
    1603                expressions = self.wrap(expressions) if wrapped else expressions
    1604                return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}"
    1605        return ""

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

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

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

    1610    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
    1611        properties_locs = defaultdict(list)
    1612        for p in properties.expressions:
    1613            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1614            if p_loc != exp.Properties.Location.UNSUPPORTED:
    1615                properties_locs[p_loc].append(p)
    1616            else:
    1617                self.unsupported(f"Unsupported property {p.key}")
    1618
    1619        return properties_locs

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

    1621    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
    1622        if isinstance(expression.this, exp.Dot):
    1623            return self.sql(expression, "this")
    1624        return f"'{expression.name}'" if string_key else expression.name

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

    1626    def property_sql(self, expression: exp.Property) -> str:
    1627        property_cls = expression.__class__
    1628        if property_cls == exp.Property:
    1629            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
    1630
    1631        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    1632        if not property_name:
    1633            self.unsupported(f"Unsupported property {expression.key}")
    1634
    1635        return f"{property_name}={self.sql(expression, 'this')}"

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

    1637    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
    1638        if self.SUPPORTS_CREATE_TABLE_LIKE:
    1639            options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
    1640            options = f" {options}" if options else ""
    1641
    1642            like = f"LIKE {self.sql(expression, 'this')}{options}"
    1643            if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema):
    1644                like = f"({like})"
    1645
    1646            return like
    1647
    1648        if expression.expressions:
    1649            self.unsupported("Transpilation of LIKE property options is unsupported")
    1650
    1651        select = exp.select("*").from_(expression.this).limit(0)
    1652        return f"AS {self.sql(select)}"

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

    1654    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1655        no = "NO " if expression.args.get("no") else ""
    1656        protection = " PROTECTION" if expression.args.get("protection") else ""
    1657        return f"{no}FALLBACK{protection}"

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

    1659    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1660        no = "NO " if expression.args.get("no") else ""
    1661        local = expression.args.get("local")
    1662        local = f"{local} " if local else ""
    1663        dual = "DUAL " if expression.args.get("dual") else ""
    1664        before = "BEFORE " if expression.args.get("before") else ""
    1665        after = "AFTER " if expression.args.get("after") else ""
    1666        return f"{no}{local}{dual}{before}{after}JOURNAL"

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

    1668    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1669        freespace = self.sql(expression, "this")
    1670        percent = " PERCENT" if expression.args.get("percent") else ""
    1671        return f"FREESPACE={freespace}{percent}"

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

    1673    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1674        if expression.args.get("default"):
    1675            property = "DEFAULT"
    1676        elif expression.args.get("on"):
    1677            property = "ON"
    1678        else:
    1679            property = "OFF"
    1680        return f"CHECKSUM={property}"

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

    1682    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1683        if expression.args.get("no"):
    1684            return "NO MERGEBLOCKRATIO"
    1685        if expression.args.get("default"):
    1686            return "DEFAULT MERGEBLOCKRATIO"
    1687
    1688        percent = " PERCENT" if expression.args.get("percent") else ""
    1689        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"

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

    1691    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1692        default = expression.args.get("default")
    1693        minimum = expression.args.get("minimum")
    1694        maximum = expression.args.get("maximum")
    1695        if default or minimum or maximum:
    1696            if default:
    1697                prop = "DEFAULT"
    1698            elif minimum:
    1699                prop = "MINIMUM"
    1700            else:
    1701                prop = "MAXIMUM"
    1702            return f"{prop} DATABLOCKSIZE"
    1703        units = expression.args.get("units")
    1704        units = f" {units}" if units else ""
    1705        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"

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

    1707    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1708        autotemp = expression.args.get("autotemp")
    1709        always = expression.args.get("always")
    1710        default = expression.args.get("default")
    1711        manual = expression.args.get("manual")
    1712        never = expression.args.get("never")
    1713
    1714        if autotemp is not None:
    1715            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1716        elif always:
    1717            prop = "ALWAYS"
    1718        elif default:
    1719            prop = "DEFAULT"
    1720        elif manual:
    1721            prop = "MANUAL"
    1722        elif never:
    1723            prop = "NEVER"
    1724        return f"BLOCKCOMPRESSION={prop}"

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

    1726    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1727        no = expression.args.get("no")
    1728        no = " NO" if no else ""
    1729        concurrent = expression.args.get("concurrent")
    1730        concurrent = " CONCURRENT" if concurrent else ""
    1731        target = self.sql(expression, "target")
    1732        target = f" {target}" if target else ""
    1733        return f"WITH{no}{concurrent} ISOLATED LOADING{target}"

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

    1735    def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str:
    1736        if isinstance(expression.this, list):
    1737            return f"IN ({self.expressions(expression, key='this', flat=True)})"
    1738        if expression.this:
    1739            modulus = self.sql(expression, "this")
    1740            remainder = self.sql(expression, "expression")
    1741            return f"WITH (MODULUS {modulus}, REMAINDER {remainder})"
    1742
    1743        from_expressions = self.expressions(expression, key="from_expressions", flat=True)
    1744        to_expressions = self.expressions(expression, key="to_expressions", flat=True)
    1745        return f"FROM ({from_expressions}) TO ({to_expressions})"

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

    1747    def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str:
    1748        this = self.sql(expression, "this")
    1749
    1750        for_values_or_default = expression.expression
    1751        if isinstance(for_values_or_default, exp.PartitionBoundSpec):
    1752            for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}"
    1753        else:
    1754            for_values_or_default = " DEFAULT"
    1755
    1756        return f"PARTITION OF {this}{for_values_or_default}"

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

    1758    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1759        kind = expression.args.get("kind")
    1760        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1761        for_or_in = expression.args.get("for_or_in")
    1762        for_or_in = f" {for_or_in}" if for_or_in else ""
    1763        lock_type = expression.args.get("lock_type")
    1764        override = " OVERRIDE" if expression.args.get("override") else ""
    1765        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"

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

    1767    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1768        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1769        statistics = expression.args.get("statistics")
    1770        statistics_sql = ""
    1771        if statistics is not None:
    1772            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1773        return f"{data_sql}{statistics_sql}"

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

    1775    def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str:
    1776        this = self.sql(expression, "this")
    1777        this = f"HISTORY_TABLE={this}" if this else ""
    1778        data_consistency: t.Optional[str] = self.sql(expression, "data_consistency")
    1779        data_consistency = (
    1780            f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None
    1781        )
    1782        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    1783        retention_period = (
    1784            f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None
    1785        )
    1786
    1787        if this:
    1788            on_sql = self.func("ON", this, data_consistency, retention_period)
    1789        else:
    1790            on_sql = "ON" if expression.args.get("on") else "OFF"
    1791
    1792        sql = f"SYSTEM_VERSIONING={on_sql}"
    1793
    1794        return f"WITH({sql})" if expression.args.get("with") else sql

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

    1796    def insert_sql(self, expression: exp.Insert) -> str:
    1797        hint = self.sql(expression, "hint")
    1798        overwrite = expression.args.get("overwrite")
    1799
    1800        if isinstance(expression.this, exp.Directory):
    1801            this = " OVERWRITE" if overwrite else " INTO"
    1802        else:
    1803            this = self.INSERT_OVERWRITE if overwrite else " INTO"
    1804
    1805        stored = self.sql(expression, "stored")
    1806        stored = f" {stored}" if stored else ""
    1807        alternative = expression.args.get("alternative")
    1808        alternative = f" OR {alternative}" if alternative else ""
    1809        ignore = " IGNORE" if expression.args.get("ignore") else ""
    1810        is_function = expression.args.get("is_function")
    1811        if is_function:
    1812            this = f"{this} FUNCTION"
    1813        this = f"{this} {self.sql(expression, 'this')}"
    1814
    1815        exists = " IF EXISTS" if expression.args.get("exists") else ""
    1816        where = self.sql(expression, "where")
    1817        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
    1818        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
    1819        on_conflict = self.sql(expression, "conflict")
    1820        on_conflict = f" {on_conflict}" if on_conflict else ""
    1821        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1822        returning = self.sql(expression, "returning")
    1823
    1824        if self.RETURNING_END:
    1825            expression_sql = f"{expression_sql}{on_conflict}{returning}"
    1826        else:
    1827            expression_sql = f"{returning}{expression_sql}{on_conflict}"
    1828
    1829        partition_by = self.sql(expression, "partition")
    1830        partition_by = f" {partition_by}" if partition_by else ""
    1831        settings = self.sql(expression, "settings")
    1832        settings = f" {settings}" if settings else ""
    1833
    1834        source = self.sql(expression, "source")
    1835        source = f"TABLE {source}" if source else ""
    1836
    1837        sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}"
    1838        return self.prepend_ctes(expression, sql)

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

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

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

    1843    def kill_sql(self, expression: exp.Kill) -> str:
    1844        kind = self.sql(expression, "kind")
    1845        kind = f" {kind}" if kind else ""
    1846        this = self.sql(expression, "this")
    1847        this = f" {this}" if this else ""
    1848        return f"KILL{kind}{this}"

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

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

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

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

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

    1856    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1857        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1858
    1859        constraint = self.sql(expression, "constraint")
    1860        constraint = f" ON CONSTRAINT {constraint}" if constraint else ""
    1861
    1862        conflict_keys = self.expressions(expression, key="conflict_keys", flat=True)
    1863        conflict_keys = f"({conflict_keys}) " if conflict_keys else " "
    1864        action = self.sql(expression, "action")
    1865
    1866        expressions = self.expressions(expression, flat=True)
    1867        if expressions:
    1868            set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
    1869            expressions = f" {set_keyword}{expressions}"
    1870
    1871        where = self.sql(expression, "where")
    1872        return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}"

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

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

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

    1877    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1878        fields = self.sql(expression, "fields")
    1879        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1880        escaped = self.sql(expression, "escaped")
    1881        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1882        items = self.sql(expression, "collection_items")
    1883        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1884        keys = self.sql(expression, "map_keys")
    1885        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1886        lines = self.sql(expression, "lines")
    1887        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1888        null = self.sql(expression, "null")
    1889        null = f" NULL DEFINED AS {null}" if null else ""
    1890        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"

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

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

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

    1895    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1896        this = f"{self.sql(expression, 'this')} INDEX"
    1897        target = self.sql(expression, "target")
    1898        target = f" FOR {target}" if target else ""
    1899        return f"{this}{target} ({self.expressions(expression, flat=True)})"

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

    1901    def historicaldata_sql(self, expression: exp.HistoricalData) -> str:
    1902        this = self.sql(expression, "this")
    1903        kind = self.sql(expression, "kind")
    1904        expr = self.sql(expression, "expression")
    1905        return f"{this} ({kind} => {expr})"

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

    1907    def table_parts(self, expression: exp.Table) -> str:
    1908        return ".".join(
    1909            self.sql(part)
    1910            for part in (
    1911                expression.args.get("catalog"),
    1912                expression.args.get("db"),
    1913                expression.args.get("this"),
    1914            )
    1915            if part is not None
    1916        )

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

    1918    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1919        table = self.table_parts(expression)
    1920        only = "ONLY " if expression.args.get("only") else ""
    1921        partition = self.sql(expression, "partition")
    1922        partition = f" {partition}" if partition else ""
    1923        version = self.sql(expression, "version")
    1924        version = f" {version}" if version else ""
    1925        alias = self.sql(expression, "alias")
    1926        alias = f"{sep}{alias}" if alias else ""
    1927
    1928        sample = self.sql(expression, "sample")
    1929        if self.dialect.ALIAS_POST_TABLESAMPLE:
    1930            sample_pre_alias = sample
    1931            sample_post_alias = ""
    1932        else:
    1933            sample_pre_alias = ""
    1934            sample_post_alias = sample
    1935
    1936        hints = self.expressions(expression, key="hints", sep=" ")
    1937        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
    1938        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    1939        joins = self.indent(
    1940            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
    1941        )
    1942        laterals = self.expressions(expression, key="laterals", sep="")
    1943
    1944        file_format = self.sql(expression, "format")
    1945        if file_format:
    1946            pattern = self.sql(expression, "pattern")
    1947            pattern = f", PATTERN => {pattern}" if pattern else ""
    1948            file_format = f" (FILE_FORMAT => {file_format}{pattern})"
    1949
    1950        ordinality = expression.args.get("ordinality") or ""
    1951        if ordinality:
    1952            ordinality = f" WITH ORDINALITY{alias}"
    1953            alias = ""
    1954
    1955        when = self.sql(expression, "when")
    1956        if when:
    1957            table = f"{table} {when}"
    1958
    1959        changes = self.sql(expression, "changes")
    1960        changes = f" {changes}" if changes else ""
    1961
    1962        rows_from = self.expressions(expression, key="rows_from")
    1963        if rows_from:
    1964            table = f"ROWS FROM {self.wrap(rows_from)}"
    1965
    1966        return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}"

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

    1968    def tablesample_sql(
    1969        self,
    1970        expression: exp.TableSample,
    1971        tablesample_keyword: t.Optional[str] = None,
    1972    ) -> str:
    1973        method = self.sql(expression, "method")
    1974        method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    1975        numerator = self.sql(expression, "bucket_numerator")
    1976        denominator = self.sql(expression, "bucket_denominator")
    1977        field = self.sql(expression, "bucket_field")
    1978        field = f" ON {field}" if field else ""
    1979        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    1980        seed = self.sql(expression, "seed")
    1981        seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else ""
    1982
    1983        size = self.sql(expression, "size")
    1984        if size and self.TABLESAMPLE_SIZE_IS_ROWS:
    1985            size = f"{size} ROWS"
    1986
    1987        percent = self.sql(expression, "percent")
    1988        if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT:
    1989            percent = f"{percent} PERCENT"
    1990
    1991        expr = f"{bucket}{percent}{size}"
    1992        if self.TABLESAMPLE_REQUIRES_PARENS:
    1993            expr = f"({expr})"
    1994
    1995        return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}"

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

    1997    def pivot_sql(self, expression: exp.Pivot) -> str:
    1998        expressions = self.expressions(expression, flat=True)
    1999        direction = "UNPIVOT" if expression.unpivot else "PIVOT"
    2000
    2001        if expression.this:
    2002            this = self.sql(expression, "this")
    2003            if not expressions:
    2004                return f"UNPIVOT {this}"
    2005
    2006            on = f"{self.seg('ON')} {expressions}"
    2007            into = self.sql(expression, "into")
    2008            into = f"{self.seg('INTO')} {into}" if into else ""
    2009            using = self.expressions(expression, key="using", flat=True)
    2010            using = f"{self.seg('USING')} {using}" if using else ""
    2011            group = self.sql(expression, "group")
    2012            return f"{direction} {this}{on}{into}{using}{group}"
    2013
    2014        alias = self.sql(expression, "alias")
    2015        alias = f" AS {alias}" if alias else ""
    2016
    2017        field = self.sql(expression, "field")
    2018
    2019        include_nulls = expression.args.get("include_nulls")
    2020        if include_nulls is not None:
    2021            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
    2022        else:
    2023            nulls = ""
    2024
    2025        default_on_null = self.sql(expression, "default_on_null")
    2026        default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else ""
    2027        return f"{self.seg(direction)}{nulls}({expressions} FOR {field}{default_on_null}){alias}"

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

    2029    def version_sql(self, expression: exp.Version) -> str:
    2030        this = f"FOR {expression.name}"
    2031        kind = expression.text("kind")
    2032        expr = self.sql(expression, "expression")
    2033        return f"{this} {kind} {expr}"

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

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

    2038    def update_sql(self, expression: exp.Update) -> str:
    2039        this = self.sql(expression, "this")
    2040        set_sql = self.expressions(expression, flat=True)
    2041        from_sql = self.sql(expression, "from")
    2042        where_sql = self.sql(expression, "where")
    2043        returning = self.sql(expression, "returning")
    2044        order = self.sql(expression, "order")
    2045        limit = self.sql(expression, "limit")
    2046        if self.RETURNING_END:
    2047            expression_sql = f"{from_sql}{where_sql}{returning}"
    2048        else:
    2049            expression_sql = f"{returning}{from_sql}{where_sql}"
    2050        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
    2051        return self.prepend_ctes(expression, sql)

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

    2053    def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str:
    2054        values_as_table = values_as_table and self.VALUES_AS_TABLE
    2055
    2056        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
    2057        if values_as_table or not expression.find_ancestor(exp.From, exp.Join):
    2058            args = self.expressions(expression)
    2059            alias = self.sql(expression, "alias")
    2060            values = f"VALUES{self.seg('')}{args}"
    2061            values = (
    2062                f"({values})"
    2063                if self.WRAP_DERIVED_VALUES
    2064                and (alias or isinstance(expression.parent, (exp.From, exp.Table)))
    2065                else values
    2066            )
    2067            return f"{values} AS {alias}" if alias else values
    2068
    2069        # Converts `VALUES...` expression into a series of select unions.
    2070        alias_node = expression.args.get("alias")
    2071        column_names = alias_node and alias_node.columns
    2072
    2073        selects: t.List[exp.Query] = []
    2074
    2075        for i, tup in enumerate(expression.expressions):
    2076            row = tup.expressions
    2077
    2078            if i == 0 and column_names:
    2079                row = [
    2080                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
    2081                ]
    2082
    2083            selects.append(exp.Select(expressions=row))
    2084
    2085        if self.pretty:
    2086            # This may result in poor performance for large-cardinality `VALUES` tables, due to
    2087            # the deep nesting of the resulting exp.Unions. If this is a problem, either increase
    2088            # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`.
    2089            query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects)
    2090            return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False))
    2091
    2092        alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else ""
    2093        unions = " UNION ALL ".join(self.sql(select) for select in selects)
    2094        return f"({unions}){alias}"

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

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

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

    2099    @unsupported_args("expressions")
    2100    def into_sql(self, expression: exp.Into) -> str:
    2101        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    2102        unlogged = " UNLOGGED" if expression.args.get("unlogged") else ""
    2103        return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"

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

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

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

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

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

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

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

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

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

    2120    def group_sql(self, expression: exp.Group) -> str:
    2121        group_by_all = expression.args.get("all")
    2122        if group_by_all is True:
    2123            modifier = " ALL"
    2124        elif group_by_all is False:
    2125            modifier = " DISTINCT"
    2126        else:
    2127            modifier = ""
    2128
    2129        group_by = self.op_expressions(f"GROUP BY{modifier}", expression)
    2130
    2131        grouping_sets = self.expressions(expression, key="grouping_sets")
    2132        cube = self.expressions(expression, key="cube")
    2133        rollup = self.expressions(expression, key="rollup")
    2134
    2135        groupings = csv(
    2136            self.seg(grouping_sets) if grouping_sets else "",
    2137            self.seg(cube) if cube else "",
    2138            self.seg(rollup) if rollup else "",
    2139            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    2140            sep=self.GROUPINGS_SEP,
    2141        )
    2142
    2143        if (
    2144            expression.expressions
    2145            and groupings
    2146            and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP")
    2147        ):
    2148            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    2149
    2150        return f"{group_by}{groupings}"

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

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

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

    2156    def connect_sql(self, expression: exp.Connect) -> str:
    2157        start = self.sql(expression, "start")
    2158        start = self.seg(f"START WITH {start}") if start else ""
    2159        nocycle = " NOCYCLE" if expression.args.get("nocycle") else ""
    2160        connect = self.sql(expression, "connect")
    2161        connect = self.seg(f"CONNECT BY{nocycle} {connect}")
    2162        return start + connect

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

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

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

    2167    def join_sql(self, expression: exp.Join) -> str:
    2168        if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"):
    2169            side = None
    2170        else:
    2171            side = expression.side
    2172
    2173        op_sql = " ".join(
    2174            op
    2175            for op in (
    2176                expression.method,
    2177                "GLOBAL" if expression.args.get("global") else None,
    2178                side,
    2179                expression.kind,
    2180                expression.hint if self.JOIN_HINTS else None,
    2181            )
    2182            if op
    2183        )
    2184        match_cond = self.sql(expression, "match_condition")
    2185        match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else ""
    2186        on_sql = self.sql(expression, "on")
    2187        using = expression.args.get("using")
    2188
    2189        if not on_sql and using:
    2190            on_sql = csv(*(self.sql(column) for column in using))
    2191
    2192        this = expression.this
    2193        this_sql = self.sql(this)
    2194
    2195        exprs = self.expressions(expression)
    2196        if exprs:
    2197            this_sql = f"{this_sql},{self.seg(exprs)}"
    2198
    2199        if on_sql:
    2200            on_sql = self.indent(on_sql, skip_first=True)
    2201            space = self.seg(" " * self.pad) if self.pretty else " "
    2202            if using:
    2203                on_sql = f"{space}USING ({on_sql})"
    2204            else:
    2205                on_sql = f"{space}ON {on_sql}"
    2206        elif not op_sql:
    2207            if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None:
    2208                return f" {this_sql}"
    2209
    2210            return f", {this_sql}"
    2211
    2212        if op_sql != "STRAIGHT_JOIN":
    2213            op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    2214
    2215        return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}"

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

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

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

    2222    def lateral_op(self, expression: exp.Lateral) -> str:
    2223        cross_apply = expression.args.get("cross_apply")
    2224
    2225        # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/
    2226        if cross_apply is True:
    2227            op = "INNER JOIN "
    2228        elif cross_apply is False:
    2229            op = "LEFT JOIN "
    2230        else:
    2231            op = ""
    2232
    2233        return f"{op}LATERAL"

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

    2235    def lateral_sql(self, expression: exp.Lateral) -> str:
    2236        this = self.sql(expression, "this")
    2237
    2238        if expression.args.get("view"):
    2239            alias = expression.args["alias"]
    2240            columns = self.expressions(alias, key="columns", flat=True)
    2241            table = f" {alias.name}" if alias.name else ""
    2242            columns = f" AS {columns}" if columns else ""
    2243            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    2244            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    2245
    2246        alias = self.sql(expression, "alias")
    2247        alias = f" AS {alias}" if alias else ""
    2248        return f"{self.lateral_op(expression)} {this}{alias}"

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

    2250    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    2251        this = self.sql(expression, "this")
    2252
    2253        args = [
    2254            self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e
    2255            for e in (expression.args.get(k) for k in ("offset", "expression"))
    2256            if e
    2257        ]
    2258
    2259        args_sql = ", ".join(self.sql(e) for e in args)
    2260        args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql
    2261        expressions = self.expressions(expression, flat=True)
    2262        expressions = f" BY {expressions}" if expressions else ""
    2263
    2264        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{expressions}"

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

    2266    def offset_sql(self, expression: exp.Offset) -> str:
    2267        this = self.sql(expression, "this")
    2268        value = expression.expression
    2269        value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value
    2270        expressions = self.expressions(expression, flat=True)
    2271        expressions = f" BY {expressions}" if expressions else ""
    2272        return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"

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

    2274    def setitem_sql(self, expression: exp.SetItem) -> str:
    2275        kind = self.sql(expression, "kind")
    2276        kind = f"{kind} " if kind else ""
    2277        this = self.sql(expression, "this")
    2278        expressions = self.expressions(expression)
    2279        collate = self.sql(expression, "collate")
    2280        collate = f" COLLATE {collate}" if collate else ""
    2281        global_ = "GLOBAL " if expression.args.get("global") else ""
    2282        return f"{global_}{kind}{this}{expressions}{collate}"

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

    2284    def set_sql(self, expression: exp.Set) -> str:
    2285        expressions = (
    2286            f" {self.expressions(expression, flat=True)}" if expression.expressions else ""
    2287        )
    2288        tag = " TAG" if expression.args.get("tag") else ""
    2289        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"

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

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

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

    2294    def lock_sql(self, expression: exp.Lock) -> str:
    2295        if not self.LOCKING_READS_SUPPORTED:
    2296            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    2297            return ""
    2298
    2299        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    2300        expressions = self.expressions(expression, flat=True)
    2301        expressions = f" OF {expressions}" if expressions else ""
    2302        wait = expression.args.get("wait")
    2303
    2304        if wait is not None:
    2305            if isinstance(wait, exp.Literal):
    2306                wait = f" WAIT {self.sql(wait)}"
    2307            else:
    2308                wait = " NOWAIT" if wait else " SKIP LOCKED"
    2309
    2310        return f"{lock_type}{expressions}{wait or ''}"

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

    2312    def literal_sql(self, expression: exp.Literal) -> str:
    2313        text = expression.this or ""
    2314        if expression.is_string:
    2315            text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}"
    2316        return text

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

    2318    def escape_str(self, text: str, escape_backslash: bool = True) -> str:
    2319        if self.dialect.ESCAPED_SEQUENCES:
    2320            to_escaped = self.dialect.ESCAPED_SEQUENCES
    2321            text = "".join(
    2322                to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text
    2323            )
    2324
    2325        return self._replace_line_breaks(text).replace(
    2326            self.dialect.QUOTE_END, self._escaped_quote_end
    2327        )

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

    2329    def loaddata_sql(self, expression: exp.LoadData) -> str:
    2330        local = " LOCAL" if expression.args.get("local") else ""
    2331        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    2332        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    2333        this = f" INTO TABLE {self.sql(expression, 'this')}"
    2334        partition = self.sql(expression, "partition")
    2335        partition = f" {partition}" if partition else ""
    2336        input_format = self.sql(expression, "input_format")
    2337        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    2338        serde = self.sql(expression, "serde")
    2339        serde = f" SERDE {serde}" if serde else ""
    2340        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"

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

    2342    def null_sql(self, *_) -> str:
    2343        return "NULL"

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

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

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

    2348    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    2349        this = self.sql(expression, "this")
    2350        this = f"{this} " if this else this
    2351        siblings = "SIBLINGS " if expression.args.get("siblings") else ""
    2352        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

    2354    def withfill_sql(self, expression: exp.WithFill) -> str:
    2355        from_sql = self.sql(expression, "from")
    2356        from_sql = f" FROM {from_sql}" if from_sql else ""
    2357        to_sql = self.sql(expression, "to")
    2358        to_sql = f" TO {to_sql}" if to_sql else ""
    2359        step_sql = self.sql(expression, "step")
    2360        step_sql = f" STEP {step_sql}" if step_sql else ""
    2361        interpolated_values = [
    2362            f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}"
    2363            if isinstance(e, exp.Alias)
    2364            else self.sql(e, "this")
    2365            for e in expression.args.get("interpolate") or []
    2366        ]
    2367        interpolate = (
    2368            f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else ""
    2369        )
    2370        return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}"

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

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

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

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

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

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

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

    2381    def ordered_sql(self, expression: exp.Ordered) -> str:
    2382        desc = expression.args.get("desc")
    2383        asc = not desc
    2384
    2385        nulls_first = expression.args.get("nulls_first")
    2386        nulls_last = not nulls_first
    2387        nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large"
    2388        nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small"
    2389        nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last"
    2390
    2391        this = self.sql(expression, "this")
    2392
    2393        sort_order = " DESC" if desc else (" ASC" if desc is False else "")
    2394        nulls_sort_change = ""
    2395        if nulls_first and (
    2396            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
    2397        ):
    2398            nulls_sort_change = " NULLS FIRST"
    2399        elif (
    2400            nulls_last
    2401            and ((asc and nulls_are_small) or (desc and nulls_are_large))
    2402            and not nulls_are_last
    2403        ):
    2404            nulls_sort_change = " NULLS LAST"
    2405
    2406        # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it
    2407        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
    2408            window = expression.find_ancestor(exp.Window, exp.Select)
    2409            if isinstance(window, exp.Window) and window.args.get("spec"):
    2410                self.unsupported(
    2411                    f"'{nulls_sort_change.strip()}' translation not supported in window functions"
    2412                )
    2413                nulls_sort_change = ""
    2414            elif self.NULL_ORDERING_SUPPORTED is False and (
    2415                (asc and nulls_sort_change == " NULLS LAST")
    2416                or (desc and nulls_sort_change == " NULLS FIRST")
    2417            ):
    2418                # BigQuery does not allow these ordering/nulls combinations when used under
    2419                # an aggregation func or under a window containing one
    2420                ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select)
    2421
    2422                if isinstance(ancestor, exp.Window):
    2423                    ancestor = ancestor.this
    2424                if isinstance(ancestor, exp.AggFunc):
    2425                    self.unsupported(
    2426                        f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order"
    2427                    )
    2428                    nulls_sort_change = ""
    2429            elif self.NULL_ORDERING_SUPPORTED is None:
    2430                if expression.this.is_int:
    2431                    self.unsupported(
    2432                        f"'{nulls_sort_change.strip()}' translation not supported with positional ordering"
    2433                    )
    2434                elif not isinstance(expression.this, exp.Rand):
    2435                    null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else ""
    2436                    this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}"
    2437                nulls_sort_change = ""
    2438
    2439        with_fill = self.sql(expression, "with_fill")
    2440        with_fill = f" {with_fill}" if with_fill else ""
    2441
    2442        return f"{this}{sort_order}{nulls_sort_change}{with_fill}"

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

    2444    def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str:
    2445        window_frame = self.sql(expression, "window_frame")
    2446        window_frame = f"{window_frame} " if window_frame else ""
    2447
    2448        this = self.sql(expression, "this")
    2449
    2450        return f"{window_frame}{this}"

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

    2452    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    2453        partition = self.partition_by_sql(expression)
    2454        order = self.sql(expression, "order")
    2455        measures = self.expressions(expression, key="measures")
    2456        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    2457        rows = self.sql(expression, "rows")
    2458        rows = self.seg(rows) if rows else ""
    2459        after = self.sql(expression, "after")
    2460        after = self.seg(after) if after else ""
    2461        pattern = self.sql(expression, "pattern")
    2462        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    2463        definition_sqls = [
    2464            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    2465            for definition in expression.args.get("define", [])
    2466        ]
    2467        definitions = self.expressions(sqls=definition_sqls)
    2468        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    2469        body = "".join(
    2470            (
    2471                partition,
    2472                order,
    2473                measures,
    2474                rows,
    2475                after,
    2476                pattern,
    2477                define,
    2478            )
    2479        )
    2480        alias = self.sql(expression, "alias")
    2481        alias = f" {alias}" if alias else ""
    2482        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"

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

    2484    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    2485        limit = expression.args.get("limit")
    2486
    2487        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    2488            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
    2489        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    2490            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
    2491
    2492        return csv(
    2493            *sqls,
    2494            *[self.sql(join) for join in expression.args.get("joins") or []],
    2495            self.sql(expression, "match"),
    2496            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    2497            self.sql(expression, "prewhere"),
    2498            self.sql(expression, "where"),
    2499            self.sql(expression, "connect"),
    2500            self.sql(expression, "group"),
    2501            self.sql(expression, "having"),
    2502            *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()],
    2503            self.sql(expression, "order"),
    2504            *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit),
    2505            *self.after_limit_modifiers(expression),
    2506            self.options_modifier(expression),
    2507            sep="",
    2508        )

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

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

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

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

    2517    def offset_limit_modifiers(
    2518        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    2519    ) -> t.List[str]:
    2520        return [
    2521            self.sql(expression, "offset") if fetch else self.sql(limit),
    2522            self.sql(limit) if fetch else self.sql(expression, "offset"),
    2523        ]

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

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

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

    2530    def select_sql(self, expression: exp.Select) -> str:
    2531        into = expression.args.get("into")
    2532        if not self.SUPPORTS_SELECT_INTO and into:
    2533            into.pop()
    2534
    2535        hint = self.sql(expression, "hint")
    2536        distinct = self.sql(expression, "distinct")
    2537        distinct = f" {distinct}" if distinct else ""
    2538        kind = self.sql(expression, "kind")
    2539
    2540        limit = expression.args.get("limit")
    2541        if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP:
    2542            top = self.limit_sql(limit, top=True)
    2543            limit.pop()
    2544        else:
    2545            top = ""
    2546
    2547        expressions = self.expressions(expression)
    2548
    2549        if kind:
    2550            if kind in self.SELECT_KINDS:
    2551                kind = f" AS {kind}"
    2552            else:
    2553                if kind == "STRUCT":
    2554                    expressions = self.expressions(
    2555                        sqls=[
    2556                            self.sql(
    2557                                exp.Struct(
    2558                                    expressions=[
    2559                                        exp.PropertyEQ(this=e.args.get("alias"), expression=e.this)
    2560                                        if isinstance(e, exp.Alias)
    2561                                        else e
    2562                                        for e in expression.expressions
    2563                                    ]
    2564                                )
    2565                            )
    2566                        ]
    2567                    )
    2568                kind = ""
    2569
    2570        operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ")
    2571        operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else ""
    2572
    2573        # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata
    2574        # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first.
    2575        top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}"
    2576        expressions = f"{self.sep()}{expressions}" if expressions else expressions
    2577        sql = self.query_modifiers(
    2578            expression,
    2579            f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}",
    2580            self.sql(expression, "into", comment=False),
    2581            self.sql(expression, "from", comment=False),
    2582        )
    2583
    2584        # If both the CTE and SELECT clauses have comments, generate the latter earlier
    2585        if expression.args.get("with"):
    2586            sql = self.maybe_comment(sql, expression)
    2587            expression.pop_comments()
    2588
    2589        sql = self.prepend_ctes(expression, sql)
    2590
    2591        if not self.SUPPORTS_SELECT_INTO and into:
    2592            if into.args.get("temporary"):
    2593                table_kind = " TEMPORARY"
    2594            elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"):
    2595                table_kind = " UNLOGGED"
    2596            else:
    2597                table_kind = ""
    2598            sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}"
    2599
    2600        return sql

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

    2602    def schema_sql(self, expression: exp.Schema) -> str:
    2603        this = self.sql(expression, "this")
    2604        sql = self.schema_columns_sql(expression)
    2605        return f"{this} {sql}" if this and sql else this or sql

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

    2607    def schema_columns_sql(self, expression: exp.Schema) -> str:
    2608        if expression.expressions:
    2609            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
    2610        return ""

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

    2612    def star_sql(self, expression: exp.Star) -> str:
    2613        except_ = self.expressions(expression, key="except", flat=True)
    2614        except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else ""
    2615        replace = self.expressions(expression, key="replace", flat=True)
    2616        replace = f"{self.seg('REPLACE')} ({replace})" if replace else ""
    2617        rename = self.expressions(expression, key="rename", flat=True)
    2618        rename = f"{self.seg('RENAME')} ({rename})" if rename else ""
    2619        return f"*{except_}{replace}{rename}"

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

    2621    def parameter_sql(self, expression: exp.Parameter) -> str:
    2622        this = self.sql(expression, "this")
    2623        return f"{self.PARAMETER_TOKEN}{this}"

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

    2625    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    2626        this = self.sql(expression, "this")
    2627        kind = expression.text("kind")
    2628        if kind:
    2629            kind = f"{kind}."
    2630        return f"@@{kind}{this}"

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

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

    2635    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    2636        alias = self.sql(expression, "alias")
    2637        alias = f"{sep}{alias}" if alias else ""
    2638        sample = self.sql(expression, "sample")
    2639        if self.dialect.ALIAS_POST_TABLESAMPLE and sample:
    2640            alias = f"{sample}{alias}"
    2641
    2642            # Set to None so it's not generated again by self.query_modifiers()
    2643            expression.set("sample", None)
    2644
    2645        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    2646        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    2647        return self.prepend_ctes(expression, sql)

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

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

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

    2653    def unnest_sql(self, expression: exp.Unnest) -> str:
    2654        args = self.expressions(expression, flat=True)
    2655
    2656        alias = expression.args.get("alias")
    2657        offset = expression.args.get("offset")
    2658
    2659        if self.UNNEST_WITH_ORDINALITY:
    2660            if alias and isinstance(offset, exp.Expression):
    2661                alias.append("columns", offset)
    2662
    2663        if alias and self.dialect.UNNEST_COLUMN_ONLY:
    2664            columns = alias.columns
    2665            alias = self.sql(columns[0]) if columns else ""
    2666        else:
    2667            alias = self.sql(alias)
    2668
    2669        alias = f" AS {alias}" if alias else alias
    2670        if self.UNNEST_WITH_ORDINALITY:
    2671            suffix = f" WITH ORDINALITY{alias}" if offset else alias
    2672        else:
    2673            if isinstance(offset, exp.Expression):
    2674                suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}"
    2675            elif offset:
    2676                suffix = f"{alias} WITH OFFSET"
    2677            else:
    2678                suffix = alias
    2679
    2680        return f"UNNEST({args}){suffix}"

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

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

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

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

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

    2689    def window_sql(self, expression: exp.Window) -> str:
    2690        this = self.sql(expression, "this")
    2691        partition = self.partition_by_sql(expression)
    2692        order = expression.args.get("order")
    2693        order = self.order_sql(order, flat=True) if order else ""
    2694        spec = self.sql(expression, "spec")
    2695        alias = self.sql(expression, "alias")
    2696        over = self.sql(expression, "over") or "OVER"
    2697
    2698        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    2699
    2700        first = expression.args.get("first")
    2701        if first is None:
    2702            first = ""
    2703        else:
    2704            first = "FIRST" if first else "LAST"
    2705
    2706        if not partition and not order and not spec and alias:
    2707            return f"{this} {alias}"
    2708
    2709        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
    2710        return f"{this} ({args})"

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

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

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

    2716    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    2717        kind = self.sql(expression, "kind")
    2718        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    2719        end = (
    2720            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    2721            or "CURRENT ROW"
    2722        )
    2723        return f"{kind} BETWEEN {start} AND {end}"

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

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

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

    2730    def between_sql(self, expression: exp.Between) -> str:
    2731        this = self.sql(expression, "this")
    2732        low = self.sql(expression, "low")
    2733        high = self.sql(expression, "high")
    2734        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

    2736    def bracket_offset_expressions(
    2737        self, expression: exp.Bracket, index_offset: t.Optional[int] = None
    2738    ) -> t.List[exp.Expression]:
    2739        return apply_index_offset(
    2740            expression.this,
    2741            expression.expressions,
    2742            (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0),
    2743        )

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

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

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

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

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

    2753    def any_sql(self, expression: exp.Any) -> str:
    2754        this = self.sql(expression, "this")
    2755        if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)):
    2756            if isinstance(expression.this, exp.UNWRAPPED_QUERIES):
    2757                this = self.wrap(this)
    2758            return f"ANY{this}"
    2759        return f"ANY {this}"

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

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

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

    2764    def case_sql(self, expression: exp.Case) -> str:
    2765        this = self.sql(expression, "this")
    2766        statements = [f"CASE {this}" if this else "CASE"]
    2767
    2768        for e in expression.args["ifs"]:
    2769            statements.append(f"WHEN {self.sql(e, 'this')}")
    2770            statements.append(f"THEN {self.sql(e, 'true')}")
    2771
    2772        default = self.sql(expression, "default")
    2773
    2774        if default:
    2775            statements.append(f"ELSE {default}")
    2776
    2777        statements.append("END")
    2778
    2779        if self.pretty and self.too_wide(statements):
    2780            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    2781
    2782        return " ".join(statements)

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

    2784    def constraint_sql(self, expression: exp.Constraint) -> str:
    2785        this = self.sql(expression, "this")
    2786        expressions = self.expressions(expression, flat=True)
    2787        return f"CONSTRAINT {this} {expressions}"

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

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

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

    2794    def extract_sql(self, expression: exp.Extract) -> str:
    2795        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
    2796        expression_sql = self.sql(expression, "expression")
    2797        return f"EXTRACT({this} FROM {expression_sql})"

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

    2799    def trim_sql(self, expression: exp.Trim) -> str:
    2800        trim_type = self.sql(expression, "position")
    2801
    2802        if trim_type == "LEADING":
    2803            func_name = "LTRIM"
    2804        elif trim_type == "TRAILING":
    2805            func_name = "RTRIM"
    2806        else:
    2807            func_name = "TRIM"
    2808
    2809        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

    2811    def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]:
    2812        args = expression.expressions
    2813        if isinstance(expression, exp.ConcatWs):
    2814            args = args[1:]  # Skip the delimiter
    2815
    2816        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    2817            args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args]
    2818
    2819        if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"):
    2820            args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args]
    2821
    2822        return args

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

    2824    def concat_sql(self, expression: exp.Concat) -> str:
    2825        expressions = self.convert_concat_args(expression)
    2826
    2827        # Some dialects don't allow a single-argument CONCAT call
    2828        if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1:
    2829            return self.sql(expressions[0])
    2830
    2831        return self.func("CONCAT", *expressions)

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

    2833    def concatws_sql(self, expression: exp.ConcatWs) -> str:
    2834        return self.func(
    2835            "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression)
    2836        )

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

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

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

    2842    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    2843        expressions = self.expressions(expression, flat=True)
    2844        expressions = f" ({expressions})" if expressions else ""
    2845        reference = self.sql(expression, "reference")
    2846        reference = f" {reference}" if reference else ""
    2847        delete = self.sql(expression, "delete")
    2848        delete = f" ON DELETE {delete}" if delete else ""
    2849        update = self.sql(expression, "update")
    2850        update = f" ON UPDATE {update}" if update else ""
    2851        return f"FOREIGN KEY{expressions}{reference}{delete}{update}"

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

    2853    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    2854        expressions = self.expressions(expression, flat=True)
    2855        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2856        options = f" {options}" if options else ""
    2857        return f"PRIMARY KEY ({expressions}){options}"

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

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

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

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

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

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

    2870    def jsonpath_sql(self, expression: exp.JSONPath) -> str:
    2871        path = self.expressions(expression, sep="", flat=True).lstrip(".")
    2872
    2873        if expression.args.get("escape"):
    2874            path = self.escape_str(path)
    2875
    2876        if self.QUOTE_JSON_PATH:
    2877            path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"
    2878
    2879        return path

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

    2881    def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str:
    2882        if isinstance(expression, exp.JSONPathPart):
    2883            transform = self.TRANSFORMS.get(expression.__class__)
    2884            if not callable(transform):
    2885                self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}")
    2886                return ""
    2887
    2888            return transform(self, expression)
    2889
    2890        if isinstance(expression, int):
    2891            return str(expression)
    2892
    2893        if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE:
    2894            escaped = expression.replace("'", "\\'")
    2895            escaped = f"\\'{expression}\\'"
    2896        else:
    2897            escaped = expression.replace('"', '\\"')
    2898            escaped = f'"{escaped}"'
    2899
    2900        return escaped

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

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

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

    2905    def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str:
    2906        null_handling = expression.args.get("null_handling")
    2907        null_handling = f" {null_handling}" if null_handling else ""
    2908
    2909        unique_keys = expression.args.get("unique_keys")
    2910        if unique_keys is not None:
    2911            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    2912        else:
    2913            unique_keys = ""
    2914
    2915        return_type = self.sql(expression, "return_type")
    2916        return_type = f" RETURNING {return_type}" if return_type else ""
    2917        encoding = self.sql(expression, "encoding")
    2918        encoding = f" ENCODING {encoding}" if encoding else ""
    2919
    2920        return self.func(
    2921            "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG",
    2922            *expression.expressions,
    2923            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
    2924        )

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

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

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

    2929    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
    2930        null_handling = expression.args.get("null_handling")
    2931        null_handling = f" {null_handling}" if null_handling else ""
    2932        return_type = self.sql(expression, "return_type")
    2933        return_type = f" RETURNING {return_type}" if return_type else ""
    2934        strict = " STRICT" if expression.args.get("strict") else ""
    2935        return self.func(
    2936            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
    2937        )

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

    2939    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
    2940        this = self.sql(expression, "this")
    2941        order = self.sql(expression, "order")
    2942        null_handling = expression.args.get("null_handling")
    2943        null_handling = f" {null_handling}" if null_handling else ""
    2944        return_type = self.sql(expression, "return_type")
    2945        return_type = f" RETURNING {return_type}" if return_type else ""
    2946        strict = " STRICT" if expression.args.get("strict") else ""
    2947        return self.func(
    2948            "JSON_ARRAYAGG",
    2949            this,
    2950            suffix=f"{order}{null_handling}{return_type}{strict})",
    2951        )

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

    2953    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
    2954        path = self.sql(expression, "path")
    2955        path = f" PATH {path}" if path else ""
    2956        nested_schema = self.sql(expression, "nested_schema")
    2957
    2958        if nested_schema:
    2959            return f"NESTED{path} {nested_schema}"
    2960
    2961        this = self.sql(expression, "this")
    2962        kind = self.sql(expression, "kind")
    2963        kind = f" {kind}" if kind else ""
    2964        return f"{this}{kind}{path}"

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

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

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

    2969    def jsontable_sql(self, expression: exp.JSONTable) -> str:
    2970        this = self.sql(expression, "this")
    2971        path = self.sql(expression, "path")
    2972        path = f", {path}" if path else ""
    2973        error_handling = expression.args.get("error_handling")
    2974        error_handling = f" {error_handling}" if error_handling else ""
    2975        empty_handling = expression.args.get("empty_handling")
    2976        empty_handling = f" {empty_handling}" if empty_handling else ""
    2977        schema = self.sql(expression, "schema")
    2978        return self.func(
    2979            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
    2980        )

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

    2982    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    2983        this = self.sql(expression, "this")
    2984        kind = self.sql(expression, "kind")
    2985        path = self.sql(expression, "path")
    2986        path = f" {path}" if path else ""
    2987        as_json = " AS JSON" if expression.args.get("as_json") else ""
    2988        return f"{this} {kind}{path}{as_json}"

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

    2990    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    2991        this = self.sql(expression, "this")
    2992        path = self.sql(expression, "path")
    2993        path = f", {path}" if path else ""
    2994        expressions = self.expressions(expression)
    2995        with_ = (
    2996            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    2997            if expressions
    2998            else ""
    2999        )
    3000        return f"OPENJSON({this}{path}){with_}"

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

    3002    def in_sql(self, expression: exp.In) -> str:
    3003        query = expression.args.get("query")
    3004        unnest = expression.args.get("unnest")
    3005        field = expression.args.get("field")
    3006        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    3007
    3008        if query:
    3009            in_sql = self.sql(query)
    3010        elif unnest:
    3011            in_sql = self.in_unnest_op(unnest)
    3012        elif field:
    3013            in_sql = self.sql(field)
    3014        else:
    3015            in_sql = f"({self.expressions(expression, flat=True)})"
    3016
    3017        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"

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

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

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

    3022    def interval_sql(self, expression: exp.Interval) -> str:
    3023        unit = self.sql(expression, "unit")
    3024        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    3025            unit = self.TIME_PART_SINGULARS.get(unit, unit)
    3026        unit = f" {unit}" if unit else ""
    3027
    3028        if self.SINGLE_STRING_INTERVAL:
    3029            this = expression.this.name if expression.this else ""
    3030            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    3031
    3032        this = self.sql(expression, "this")
    3033        if this:
    3034            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    3035            this = f" {this}" if unwrapped else f" ({this})"
    3036
    3037        return f"INTERVAL{this}{unit}"

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

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

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

    3042    def reference_sql(self, expression: exp.Reference) -> str:
    3043        this = self.sql(expression, "this")
    3044        expressions = self.expressions(expression, flat=True)
    3045        expressions = f"({expressions})" if expressions else ""
    3046        options = self.expressions(expression, key="options", flat=True, sep=" ")
    3047        options = f" {options}" if options else ""
    3048        return f"REFERENCES {this}{expressions}{options}"

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

    3050    def anonymous_sql(self, expression: exp.Anonymous) -> str:
    3051        # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive
    3052        parent = expression.parent
    3053        is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression
    3054        return self.func(
    3055            self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified
    3056        )

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

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

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

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

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

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

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

    3071    def alias_sql(self, expression: exp.Alias) -> str:
    3072        alias = self.sql(expression, "alias")
    3073        alias = f" AS {alias}" if alias else ""
    3074        return f"{self.sql(expression, 'this')}{alias}"

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

    3076    def pivotalias_sql(self, expression: exp.PivotAlias) -> str:
    3077        alias = expression.args["alias"]
    3078
    3079        identifier_alias = isinstance(alias, exp.Identifier)
    3080        literal_alias = isinstance(alias, exp.Literal)
    3081
    3082        if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    3083            alias.replace(exp.Literal.string(alias.output_name))
    3084        elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    3085            alias.replace(exp.to_identifier(alias.output_name))
    3086
    3087        return self.alias_sql(expression)

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

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

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

    3092    def atindex_sql(self, expression: exp.AtTimeZone) -> str:
    3093        this = self.sql(expression, "this")
    3094        index = self.sql(expression, "expression")
    3095        return f"{this} AT {index}"

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

    3097    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    3098        this = self.sql(expression, "this")
    3099        zone = self.sql(expression, "zone")
    3100        return f"{this} AT TIME ZONE {zone}"

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

    3102    def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str:
    3103        this = self.sql(expression, "this")
    3104        zone = self.sql(expression, "zone")
    3105        return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'"

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

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

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

    3110    def and_sql(
    3111        self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None
    3112    ) -> str:
    3113        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

    3115    def or_sql(
    3116        self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None
    3117    ) -> str:
    3118        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

    3120    def xor_sql(
    3121        self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None
    3122    ) -> str:
    3123        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

    3125    def connector_sql(
    3126        self,
    3127        expression: exp.Connector,
    3128        op: str,
    3129        stack: t.Optional[t.List[str | exp.Expression]] = None,
    3130    ) -> str:
    3131        if stack is not None:
    3132            if expression.expressions:
    3133                stack.append(self.expressions(expression, sep=f" {op} "))
    3134            else:
    3135                stack.append(expression.right)
    3136                if expression.comments and self.comments:
    3137                    for comment in expression.comments:
    3138                        if comment:
    3139                            op += f" /*{self.pad_comment(comment)}*/"
    3140                stack.extend((op, expression.left))
    3141            return op
    3142
    3143        stack = [expression]
    3144        sqls: t.List[str] = []
    3145        ops = set()
    3146
    3147        while stack:
    3148            node = stack.pop()
    3149            if isinstance(node, exp.Connector):
    3150                ops.add(getattr(self, f"{node.key}_sql")(node, stack))
    3151            else:
    3152                sql = self.sql(node)
    3153                if sqls and sqls[-1] in ops:
    3154                    sqls[-1] += f" {sql}"
    3155                else:
    3156                    sqls.append(sql)
    3157
    3158        sep = "\n" if self.pretty and self.too_wide(sqls) else " "
    3159        return sep.join(sqls)

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

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

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

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

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

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

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

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

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

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

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

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

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

    3179    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    3180        format_sql = self.sql(expression, "format")
    3181        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    3182        to_sql = self.sql(expression, "to")
    3183        to_sql = f" {to_sql}" if to_sql else ""
    3184        action = self.sql(expression, "action")
    3185        action = f" {action}" if action else ""
    3186        return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{format_sql}{action})"

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

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

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

    3192    def collate_sql(self, expression: exp.Collate) -> str:
    3193        if self.COLLATE_IS_FUNC:
    3194            return self.function_fallback_sql(expression)
    3195        return self.binary(expression, "COLLATE")

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

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

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

    3200    def comment_sql(self, expression: exp.Comment) -> str:
    3201        this = self.sql(expression, "this")
    3202        kind = expression.args["kind"]
    3203        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    3204        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    3205        expression_sql = self.sql(expression, "expression")
    3206        return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"

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

    3208    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    3209        this = self.sql(expression, "this")
    3210        delete = " DELETE" if expression.args.get("delete") else ""
    3211        recompress = self.sql(expression, "recompress")
    3212        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    3213        to_disk = self.sql(expression, "to_disk")
    3214        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    3215        to_volume = self.sql(expression, "to_volume")
    3216        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    3217        return f"{this}{delete}{recompress}{to_disk}{to_volume}"

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

    3219    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    3220        where = self.sql(expression, "where")
    3221        group = self.sql(expression, "group")
    3222        aggregates = self.expressions(expression, key="aggregates")
    3223        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    3224
    3225        if not (where or group or aggregates) and len(expression.expressions) == 1:
    3226            return f"TTL {self.expressions(expression, flat=True)}"
    3227
    3228        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"

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

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

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

    3233    def commit_sql(self, expression: exp.Commit) -> str:
    3234        chain = expression.args.get("chain")
    3235        if chain is not None:
    3236            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    3237
    3238        return f"COMMIT{chain or ''}"

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

    3240    def rollback_sql(self, expression: exp.Rollback) -> str:
    3241        savepoint = expression.args.get("savepoint")
    3242        savepoint = f" TO {savepoint}" if savepoint else ""
    3243        return f"ROLLBACK{savepoint}"

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

    3245    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    3246        this = self.sql(expression, "this")
    3247
    3248        dtype = self.sql(expression, "dtype")
    3249        if dtype:
    3250            collate = self.sql(expression, "collate")
    3251            collate = f" COLLATE {collate}" if collate else ""
    3252            using = self.sql(expression, "using")
    3253            using = f" USING {using}" if using else ""
    3254            return f"ALTER COLUMN {this} SET DATA TYPE {dtype}{collate}{using}"
    3255
    3256        default = self.sql(expression, "default")
    3257        if default:
    3258            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    3259
    3260        comment = self.sql(expression, "comment")
    3261        if comment:
    3262            return f"ALTER COLUMN {this} COMMENT {comment}"
    3263
    3264        allow_null = expression.args.get("allow_null")
    3265        drop = expression.args.get("drop")
    3266
    3267        if not drop and not allow_null:
    3268            self.unsupported("Unsupported ALTER COLUMN syntax")
    3269
    3270        if allow_null is not None:
    3271            keyword = "DROP" if drop else "SET"
    3272            return f"ALTER COLUMN {this} {keyword} NOT NULL"
    3273
    3274        return f"ALTER COLUMN {this} DROP DEFAULT"

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

    3276    def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str:
    3277        this = self.sql(expression, "this")
    3278        if not isinstance(expression.this, exp.Var):
    3279            this = f"KEY DISTKEY {this}"
    3280        return f"ALTER DISTSTYLE {this}"

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

    3282    def altersortkey_sql(self, expression: exp.AlterSortKey) -> str:
    3283        compound = " COMPOUND" if expression.args.get("compound") else ""
    3284        this = self.sql(expression, "this")
    3285        expressions = self.expressions(expression, flat=True)
    3286        expressions = f"({expressions})" if expressions else ""
    3287        return f"ALTER{compound} SORTKEY {this or expressions}"

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

    3289    def alterrename_sql(self, expression: exp.AlterRename) -> str:
    3290        if not self.RENAME_TABLE_WITH_DB:
    3291            # Remove db from tables
    3292            expression = expression.transform(
    3293                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    3294            ).assert_is(exp.AlterRename)
    3295        this = self.sql(expression, "this")
    3296        return f"RENAME TO {this}"

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

    3298    def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
    3299        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3300        old_column = self.sql(expression, "this")
    3301        new_column = self.sql(expression, "to")
    3302        return f"RENAME COLUMN{exists} {old_column} TO {new_column}"

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

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

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

    3308    def alter_sql(self, expression: exp.Alter) -> str:
    3309        actions = expression.args["actions"]
    3310
    3311        if isinstance(actions[0], exp.ColumnDef):
    3312            actions = self.add_column_sql(expression)
    3313        elif isinstance(actions[0], exp.Schema):
    3314            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    3315        elif isinstance(actions[0], exp.Delete):
    3316            actions = self.expressions(expression, key="actions", flat=True)
    3317        elif isinstance(actions[0], exp.Query):
    3318            actions = "AS " + self.expressions(expression, key="actions")
    3319        else:
    3320            actions = self.expressions(expression, key="actions", flat=True)
    3321
    3322        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3323        on_cluster = self.sql(expression, "cluster")
    3324        on_cluster = f" {on_cluster}" if on_cluster else ""
    3325        only = " ONLY" if expression.args.get("only") else ""
    3326        options = self.expressions(expression, key="options")
    3327        options = f", {options}" if options else ""
    3328        kind = self.sql(expression, "kind")
    3329        not_valid = " NOT VALID" if expression.args.get("not_valid") else ""
    3330
    3331        return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions}{not_valid}{options}"

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

    3333    def add_column_sql(self, expression: exp.Alter) -> str:
    3334        if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD:
    3335            return self.expressions(
    3336                expression,
    3337                key="actions",
    3338                prefix="ADD COLUMN ",
    3339                skip_first=True,
    3340            )
    3341        return f"ADD {self.expressions(expression, key='actions', flat=True)}"

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

    3343    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    3344        expressions = self.expressions(expression)
    3345        exists = " IF EXISTS " if expression.args.get("exists") else " "
    3346        return f"DROP{exists}{expressions}"

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

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

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

    3351    def distinct_sql(self, expression: exp.Distinct) -> str:
    3352        this = self.expressions(expression, flat=True)
    3353
    3354        if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1:
    3355            case = exp.case()
    3356            for arg in expression.expressions:
    3357                case = case.when(arg.is_(exp.null()), exp.null())
    3358            this = self.sql(case.else_(f"({this})"))
    3359
    3360        this = f" {this}" if this else ""
    3361
    3362        on = self.sql(expression, "on")
    3363        on = f" ON {on}" if on else ""
    3364        return f"DISTINCT{this}{on}"

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

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

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

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

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

    3372    def havingmax_sql(self, expression: exp.HavingMax) -> str:
    3373        this_sql = self.sql(expression, "this")
    3374        expression_sql = self.sql(expression, "expression")
    3375        kind = "MAX" if expression.args.get("max") else "MIN"
    3376        return f"{this_sql} HAVING {kind} {expression_sql}"

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

    3378    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    3379        return self.sql(
    3380            exp.Cast(
    3381                this=exp.Div(this=expression.this, expression=expression.expression),
    3382                to=exp.DataType(this=exp.DataType.Type.INT),
    3383            )
    3384        )

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

    3386    def dpipe_sql(self, expression: exp.DPipe) -> str:
    3387        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    3388            return self.func(
    3389                "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten())
    3390            )
    3391        return self.binary(expression, "||")

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

    3393    def div_sql(self, expression: exp.Div) -> str:
    3394        l, r = expression.left, expression.right
    3395
    3396        if not self.dialect.SAFE_DIVISION and expression.args.get("safe"):
    3397            r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0)))
    3398
    3399        if self.dialect.TYPED_DIVISION and not expression.args.get("typed"):
    3400            if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES):
    3401                l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE))
    3402
    3403        elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"):
    3404            if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES):
    3405                return self.sql(
    3406                    exp.cast(
    3407                        l / r,
    3408                        to=exp.DataType.Type.BIGINT,
    3409                    )
    3410                )
    3411
    3412        return self.binary(expression, "/")

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

    3414    def safedivide_sql(self, expression: exp.SafeDivide) -> str:
    3415        n = exp._wrap(expression.this, exp.Binary)
    3416        d = exp._wrap(expression.expression, exp.Binary)
    3417        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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3452    def is_sql(self, expression: exp.Is) -> str:
    3453        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    3454            return self.sql(
    3455                expression.this if expression.expression.this else exp.not_(expression.this)
    3456            )
    3457        return self.binary(expression, "IS")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3498    def try_sql(self, expression: exp.Try) -> str:
    3499        if not self.TRY_SUPPORTED:
    3500            self.unsupported("Unsupported TRY function")
    3501            return self.sql(expression, "this")
    3502
    3503        return self.func("TRY", expression.this)

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

    3505    def log_sql(self, expression: exp.Log) -> str:
    3506        this = expression.this
    3507        expr = expression.expression
    3508
    3509        if self.dialect.LOG_BASE_FIRST is False:
    3510            this, expr = expr, this
    3511        elif self.dialect.LOG_BASE_FIRST is None and expr:
    3512            if this.name in ("2", "10"):
    3513                return self.func(f"LOG{this.name}", expr)
    3514
    3515            self.unsupported(f"Unsupported logarithm with base {self.sql(this)}")
    3516
    3517        return self.func("LOG", this, expr)

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

    3519    def use_sql(self, expression: exp.Use) -> str:
    3520        kind = self.sql(expression, "kind")
    3521        kind = f" {kind}" if kind else ""
    3522        this = self.sql(expression, "this")
    3523        this = f" {this}" if this else ""
    3524        return f"USE{kind}{this}"

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

    3526    def binary(self, expression: exp.Binary, op: str) -> str:
    3527        sqls: t.List[str] = []
    3528        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    3529        binary_type = type(expression)
    3530
    3531        while stack:
    3532            node = stack.pop()
    3533
    3534            if type(node) is binary_type:
    3535                op_func = node.args.get("operator")
    3536                if op_func:
    3537                    op = f"OPERATOR({self.sql(op_func)})"
    3538
    3539                stack.append(node.right)
    3540                stack.append(f" {self.maybe_comment(op, comments=node.comments)} ")
    3541                stack.append(node.left)
    3542            else:
    3543                sqls.append(self.sql(node))
    3544
    3545        return "".join(sqls)

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

    3547    def ceil_floor(self, expression: exp.Ceil | exp.Floor) -> str:
    3548        to_clause = self.sql(expression, "to")
    3549        if to_clause:
    3550            return f"{expression.sql_name()}({self.sql(expression, 'this')} TO {to_clause})"
    3551
    3552        return self.function_fallback_sql(expression)

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

    3554    def function_fallback_sql(self, expression: exp.Func) -> str:
    3555        args = []
    3556
    3557        for key in expression.arg_types:
    3558            arg_value = expression.args.get(key)
    3559
    3560            if isinstance(arg_value, list):
    3561                for value in arg_value:
    3562                    args.append(value)
    3563            elif arg_value is not None:
    3564                args.append(arg_value)
    3565
    3566        if self.dialect.PRESERVE_ORIGINAL_NAMES:
    3567            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
    3568        else:
    3569            name = expression.sql_name()
    3570
    3571        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

    3573    def func(
    3574        self,
    3575        name: str,
    3576        *args: t.Optional[exp.Expression | str],
    3577        prefix: str = "(",
    3578        suffix: str = ")",
    3579        normalize: bool = True,
    3580    ) -> str:
    3581        name = self.normalize_func(name) if normalize else name
    3582        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

    3584    def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str:
    3585        arg_sqls = tuple(
    3586            self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool)
    3587        )
    3588        if self.pretty and self.too_wide(arg_sqls):
    3589            return self.indent(
    3590                "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True
    3591            )
    3592        return sep.join(arg_sqls)

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

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

    3597    def format_time(
    3598        self,
    3599        expression: exp.Expression,
    3600        inverse_time_mapping: t.Optional[t.Dict[str, str]] = None,
    3601        inverse_time_trie: t.Optional[t.Dict] = None,
    3602    ) -> t.Optional[str]:
    3603        return format_time(
    3604            self.sql(expression, "format"),
    3605            inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING,
    3606            inverse_time_trie or self.dialect.INVERSE_TIME_TRIE,
    3607        )

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

    3609    def expressions(
    3610        self,
    3611        expression: t.Optional[exp.Expression] = None,
    3612        key: t.Optional[str] = None,
    3613        sqls: t.Optional[t.Collection[str | exp.Expression]] = None,
    3614        flat: bool = False,
    3615        indent: bool = True,
    3616        skip_first: bool = False,
    3617        skip_last: bool = False,
    3618        sep: str = ", ",
    3619        prefix: str = "",
    3620        dynamic: bool = False,
    3621        new_line: bool = False,
    3622    ) -> str:
    3623        expressions = expression.args.get(key or "expressions") if expression else sqls
    3624
    3625        if not expressions:
    3626            return ""
    3627
    3628        if flat:
    3629            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
    3630
    3631        num_sqls = len(expressions)
    3632        result_sqls = []
    3633
    3634        for i, e in enumerate(expressions):
    3635            sql = self.sql(e, comment=False)
    3636            if not sql:
    3637                continue
    3638
    3639            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    3640
    3641            if self.pretty:
    3642                if self.leading_comma:
    3643                    result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}")
    3644                else:
    3645                    result_sqls.append(
    3646                        f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}"
    3647                    )
    3648            else:
    3649                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    3650
    3651        if self.pretty and (not dynamic or self.too_wide(result_sqls)):
    3652            if new_line:
    3653                result_sqls.insert(0, "")
    3654                result_sqls.append("")
    3655            result_sql = "\n".join(s.rstrip() for s in result_sqls)
    3656        else:
    3657            result_sql = "".join(result_sqls)
    3658
    3659        return (
    3660            self.indent(result_sql, skip_first=skip_first, skip_last=skip_last)
    3661            if indent
    3662            else result_sql
    3663        )

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

    3665    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    3666        flat = flat or isinstance(expression.parent, exp.Properties)
    3667        expressions_sql = self.expressions(expression, flat=flat)
    3668        if flat:
    3669            return f"{op} {expressions_sql}"
    3670        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"

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

    3672    def naked_property(self, expression: exp.Property) -> str:
    3673        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    3674        if not property_name:
    3675            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    3676        return f"{property_name} {self.sql(expression, 'this')}"

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

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

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

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

    3684    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    3685        this = self.sql(expression, "this")
    3686        expressions = self.no_identify(self.expressions, expression)
    3687        expressions = (
    3688            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    3689        )
    3690        return f"{this}{expressions}" if expressions.strip() != "" else this

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

    3692    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    3693        this = self.sql(expression, "this")
    3694        expressions = self.expressions(expression, flat=True)
    3695        return f"{this}({expressions})"

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

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

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

    3700    def when_sql(self, expression: exp.When) -> str:
    3701        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    3702        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    3703        condition = self.sql(expression, "condition")
    3704        condition = f" AND {condition}" if condition else ""
    3705
    3706        then_expression = expression.args.get("then")
    3707        if isinstance(then_expression, exp.Insert):
    3708            this = self.sql(then_expression, "this")
    3709            this = f"INSERT {this}" if this else "INSERT"
    3710            then = self.sql(then_expression, "expression")
    3711            then = f"{this} VALUES {then}" if then else this
    3712        elif isinstance(then_expression, exp.Update):
    3713            if isinstance(then_expression.args.get("expressions"), exp.Star):
    3714                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    3715            else:
    3716                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    3717        else:
    3718            then = self.sql(then_expression)
    3719        return f"WHEN {matched}{source}{condition} THEN {then}"

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

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

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

    3724    def merge_sql(self, expression: exp.Merge) -> str:
    3725        table = expression.this
    3726        table_alias = ""
    3727
    3728        hints = table.args.get("hints")
    3729        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
    3730            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
    3731            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
    3732
    3733        this = self.sql(table)
    3734        using = f"USING {self.sql(expression, 'using')}"
    3735        on = f"ON {self.sql(expression, 'on')}"
    3736        whens = self.sql(expression, "whens")
    3737
    3738        returning = self.sql(expression, "returning")
    3739        if returning:
    3740            whens = f"{whens}{returning}"
    3741
    3742        sep = self.sep()
    3743
    3744        return self.prepend_ctes(
    3745            expression,
    3746            f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}",
    3747        )

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

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

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

    3753    def tonumber_sql(self, expression: exp.ToNumber) -> str:
    3754        if not self.SUPPORTS_TO_NUMBER:
    3755            self.unsupported("Unsupported TO_NUMBER function")
    3756            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3757
    3758        fmt = expression.args.get("format")
    3759        if not fmt:
    3760            self.unsupported("Conversion format is required for TO_NUMBER")
    3761            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3762
    3763        return self.func("TO_NUMBER", expression.this, fmt)

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

    3765    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    3766        this = self.sql(expression, "this")
    3767        kind = self.sql(expression, "kind")
    3768        settings_sql = self.expressions(expression, key="settings", sep=" ")
    3769        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    3770        return f"{this}({kind}{args})"

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

    3772    def dictrange_sql(self, expression: exp.DictRange) -> str:
    3773        this = self.sql(expression, "this")
    3774        max = self.sql(expression, "max")
    3775        min = self.sql(expression, "min")
    3776        return f"{this}(MIN {min} MAX {max})"

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

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

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

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

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

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

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

    3789    def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str:
    3790        expressions = self.expressions(expression, flat=True)
    3791        expressions = f" {self.wrap(expressions)}" if expressions else ""
    3792        buckets = self.sql(expression, "buckets")
    3793        kind = self.sql(expression, "kind")
    3794        buckets = f" BUCKETS {buckets}" if buckets else ""
    3795        order = self.sql(expression, "order")
    3796        return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}"

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

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

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

    3801    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    3802        expressions = self.expressions(expression, key="expressions", flat=True)
    3803        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    3804        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    3805        buckets = self.sql(expression, "buckets")
    3806        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"

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

    3808    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    3809        this = self.sql(expression, "this")
    3810        having = self.sql(expression, "having")
    3811
    3812        if having:
    3813            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    3814
    3815        return self.func("ANY_VALUE", this)

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

    3817    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
    3818        transform = self.func("TRANSFORM", *expression.expressions)
    3819        row_format_before = self.sql(expression, "row_format_before")
    3820        row_format_before = f" {row_format_before}" if row_format_before else ""
    3821        record_writer = self.sql(expression, "record_writer")
    3822        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
    3823        using = f" USING {self.sql(expression, 'command_script')}"
    3824        schema = self.sql(expression, "schema")
    3825        schema = f" AS {schema}" if schema else ""
    3826        row_format_after = self.sql(expression, "row_format_after")
    3827        row_format_after = f" {row_format_after}" if row_format_after else ""
    3828        record_reader = self.sql(expression, "record_reader")
    3829        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
    3830        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

    3832    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
    3833        key_block_size = self.sql(expression, "key_block_size")
    3834        if key_block_size:
    3835            return f"KEY_BLOCK_SIZE = {key_block_size}"
    3836
    3837        using = self.sql(expression, "using")
    3838        if using:
    3839            return f"USING {using}"
    3840
    3841        parser = self.sql(expression, "parser")
    3842        if parser:
    3843            return f"WITH PARSER {parser}"
    3844
    3845        comment = self.sql(expression, "comment")
    3846        if comment:
    3847            return f"COMMENT {comment}"
    3848
    3849        visible = expression.args.get("visible")
    3850        if visible is not None:
    3851            return "VISIBLE" if visible else "INVISIBLE"
    3852
    3853        engine_attr = self.sql(expression, "engine_attr")
    3854        if engine_attr:
    3855            return f"ENGINE_ATTRIBUTE = {engine_attr}"
    3856
    3857        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
    3858        if secondary_engine_attr:
    3859            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
    3860
    3861        self.unsupported("Unsupported index constraint option.")
    3862        return ""

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

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

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

    3868    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
    3869        kind = self.sql(expression, "kind")
    3870        kind = f"{kind} INDEX" if kind else "INDEX"
    3871        this = self.sql(expression, "this")
    3872        this = f" {this}" if this else ""
    3873        index_type = self.sql(expression, "index_type")
    3874        index_type = f" USING {index_type}" if index_type else ""
    3875        expressions = self.expressions(expression, flat=True)
    3876        expressions = f" ({expressions})" if expressions else ""
    3877        options = self.expressions(expression, key="options", sep=" ")
    3878        options = f" {options}" if options else ""
    3879        return f"{kind}{this}{index_type}{expressions}{options}"

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

    3881    def nvl2_sql(self, expression: exp.Nvl2) -> str:
    3882        if self.NVL2_SUPPORTED:
    3883            return self.function_fallback_sql(expression)
    3884
    3885        case = exp.Case().when(
    3886            expression.this.is_(exp.null()).not_(copy=False),
    3887            expression.args["true"],
    3888            copy=False,
    3889        )
    3890        else_cond = expression.args.get("false")
    3891        if else_cond:
    3892            case.else_(else_cond, copy=False)
    3893
    3894        return self.sql(case)

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

    3896    def comprehension_sql(self, expression: exp.Comprehension) -> str:
    3897        this = self.sql(expression, "this")
    3898        expr = self.sql(expression, "expression")
    3899        iterator = self.sql(expression, "iterator")
    3900        condition = self.sql(expression, "condition")
    3901        condition = f" IF {condition}" if condition else ""
    3902        return f"{this} FOR {expr} IN {iterator}{condition}"

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

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

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

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

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

    3910    def predict_sql(self, expression: exp.Predict) -> str:
    3911        model = self.sql(expression, "this")
    3912        model = f"MODEL {model}"
    3913        table = self.sql(expression, "expression")
    3914        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
    3915        parameters = self.sql(expression, "params_struct")
    3916        return self.func("PREDICT", model, table, parameters or None)

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

    3918    def forin_sql(self, expression: exp.ForIn) -> str:
    3919        this = self.sql(expression, "this")
    3920        expression_sql = self.sql(expression, "expression")
    3921        return f"FOR {this} DO {expression_sql}"

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

    3923    def refresh_sql(self, expression: exp.Refresh) -> str:
    3924        this = self.sql(expression, "this")
    3925        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
    3926        return f"REFRESH {table}{this}"

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

    3928    def toarray_sql(self, expression: exp.ToArray) -> str:
    3929        arg = expression.this
    3930        if not arg.type:
    3931            from sqlglot.optimizer.annotate_types import annotate_types
    3932
    3933            arg = annotate_types(arg)
    3934
    3935        if arg.is_type(exp.DataType.Type.ARRAY):
    3936            return self.sql(arg)
    3937
    3938        cond_for_null = arg.is_(exp.null())
    3939        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

    3941    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
    3942        this = expression.this
    3943        time_format = self.format_time(expression)
    3944
    3945        if time_format:
    3946            return self.sql(
    3947                exp.cast(
    3948                    exp.StrToTime(this=this, format=expression.args["format"]),
    3949                    exp.DataType.Type.TIME,
    3950                )
    3951            )
    3952
    3953        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
    3954            return self.sql(this)
    3955
    3956        return self.sql(exp.cast(this, exp.DataType.Type.TIME))

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

    3958    def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str:
    3959        this = expression.this
    3960        if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP):
    3961            return self.sql(this)
    3962
    3963        return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect))

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

    3965    def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str:
    3966        this = expression.this
    3967        if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME):
    3968            return self.sql(this)
    3969
    3970        return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect))

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

    3972    def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:
    3973        this = expression.this
    3974        time_format = self.format_time(expression)
    3975
    3976        if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT):
    3977            return self.sql(
    3978                exp.cast(
    3979                    exp.StrToTime(this=this, format=expression.args["format"]),
    3980                    exp.DataType.Type.DATE,
    3981                )
    3982            )
    3983
    3984        if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE):
    3985            return self.sql(this)
    3986
    3987        return self.sql(exp.cast(this, exp.DataType.Type.DATE))

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

    3989    def unixdate_sql(self, expression: exp.UnixDate) -> str:
    3990        return self.sql(
    3991            exp.func(
    3992                "DATEDIFF",
    3993                expression.this,
    3994                exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE),
    3995                "day",
    3996            )
    3997        )

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

    3999    def lastday_sql(self, expression: exp.LastDay) -> str:
    4000        if self.LAST_DAY_SUPPORTS_DATE_PART:
    4001            return self.function_fallback_sql(expression)
    4002
    4003        unit = expression.text("unit")
    4004        if unit and unit != "MONTH":
    4005            self.unsupported("Date parts are not supported in LAST_DAY.")
    4006
    4007        return self.func("LAST_DAY", expression.this)

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

    4009    def dateadd_sql(self, expression: exp.DateAdd) -> str:
    4010        from sqlglot.dialects.dialect import unit_to_str
    4011
    4012        return self.func(
    4013            "DATE_ADD", expression.this, expression.expression, unit_to_str(expression)
    4014        )

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

    4016    def arrayany_sql(self, expression: exp.ArrayAny) -> str:
    4017        if self.CAN_IMPLEMENT_ARRAY_ANY:
    4018            filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression)
    4019            filtered_not_empty = exp.ArraySize(this=filtered).neq(0)
    4020            original_is_empty = exp.ArraySize(this=expression.this).eq(0)
    4021            return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty)))
    4022
    4023        from sqlglot.dialects import Dialect
    4024
    4025        # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect
    4026        if self.dialect.__class__ != Dialect:
    4027            self.unsupported("ARRAY_ANY is unsupported")
    4028
    4029        return self.function_fallback_sql(expression)

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

    4031    def struct_sql(self, expression: exp.Struct) -> str:
    4032        expression.set(
    4033            "expressions",
    4034            [
    4035                exp.alias_(e.expression, e.name if e.this.is_string else e.this)
    4036                if isinstance(e, exp.PropertyEQ)
    4037                else e
    4038                for e in expression.expressions
    4039            ],
    4040        )
    4041
    4042        return self.function_fallback_sql(expression)

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

    4044    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
    4045        low = self.sql(expression, "this")
    4046        high = self.sql(expression, "expression")
    4047
    4048        return f"{low} TO {high}"

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

    4050    def truncatetable_sql(self, expression: exp.TruncateTable) -> str:
    4051        target = "DATABASE" if expression.args.get("is_database") else "TABLE"
    4052        tables = f" {self.expressions(expression)}"
    4053
    4054        exists = " IF EXISTS" if expression.args.get("exists") else ""
    4055
    4056        on_cluster = self.sql(expression, "cluster")
    4057        on_cluster = f" {on_cluster}" if on_cluster else ""
    4058
    4059        identity = self.sql(expression, "identity")
    4060        identity = f" {identity} IDENTITY" if identity else ""
    4061
    4062        option = self.sql(expression, "option")
    4063        option = f" {option}" if option else ""
    4064
    4065        partition = self.sql(expression, "partition")
    4066        partition = f" {partition}" if partition else ""
    4067
    4068        return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"

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

    4072    def convert_sql(self, expression: exp.Convert) -> str:
    4073        to = expression.this
    4074        value = expression.expression
    4075        style = expression.args.get("style")
    4076        safe = expression.args.get("safe")
    4077        strict = expression.args.get("strict")
    4078
    4079        if not to or not value:
    4080            return ""
    4081
    4082        # Retrieve length of datatype and override to default if not specified
    4083        if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    4084            to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
    4085
    4086        transformed: t.Optional[exp.Expression] = None
    4087        cast = exp.Cast if strict else exp.TryCast
    4088
    4089        # Check whether a conversion with format (T-SQL calls this 'style') is applicable
    4090        if isinstance(style, exp.Literal) and style.is_int:
    4091            from sqlglot.dialects.tsql import TSQL
    4092
    4093            style_value = style.name
    4094            converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value)
    4095            if not converted_style:
    4096                self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}")
    4097
    4098            fmt = exp.Literal.string(converted_style)
    4099
    4100            if to.this == exp.DataType.Type.DATE:
    4101                transformed = exp.StrToDate(this=value, format=fmt)
    4102            elif to.this in (exp.DataType.Type.DATETIME, exp.DataType.Type.DATETIME2):
    4103                transformed = exp.StrToTime(this=value, format=fmt)
    4104            elif to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    4105                transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe)
    4106            elif to.this == exp.DataType.Type.TEXT:
    4107                transformed = exp.TimeToStr(this=value, format=fmt)
    4108
    4109        if not transformed:
    4110            transformed = cast(this=value, to=to, safe=safe)
    4111
    4112        return self.sql(transformed)

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

    4172    def copyparameter_sql(self, expression: exp.CopyParameter) -> str:
    4173        option = self.sql(expression, "this")
    4174
    4175        if expression.expressions:
    4176            upper = option.upper()
    4177
    4178            # Snowflake FILE_FORMAT options are separated by whitespace
    4179            sep = " " if upper == "FILE_FORMAT" else ", "
    4180
    4181            # Databricks copy/format options do not set their list of values with EQ
    4182            op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = "
    4183            values = self.expressions(expression, flat=True, sep=sep)
    4184            return f"{option}{op}({values})"
    4185
    4186        value = self.sql(expression, "expression")
    4187
    4188        if not value:
    4189            return option
    4190
    4191        op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " "
    4192
    4193        return f"{option}{op}{value}"

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

    4195    def credentials_sql(self, expression: exp.Credentials) -> str:
    4196        cred_expr = expression.args.get("credentials")
    4197        if isinstance(cred_expr, exp.Literal):
    4198            # Redshift case: CREDENTIALS <string>
    4199            credentials = self.sql(expression, "credentials")
    4200            credentials = f"CREDENTIALS {credentials}" if credentials else ""
    4201        else:
    4202            # Snowflake case: CREDENTIALS = (...)
    4203            credentials = self.expressions(expression, key="credentials", flat=True, sep=" ")
    4204            credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else ""
    4205
    4206        storage = self.sql(expression, "storage")
    4207        storage = f"STORAGE_INTEGRATION = {storage}" if storage else ""
    4208
    4209        encryption = self.expressions(expression, key="encryption", flat=True, sep=" ")
    4210        encryption = f" ENCRYPTION = ({encryption})" if encryption else ""
    4211
    4212        iam_role = self.sql(expression, "iam_role")
    4213        iam_role = f"IAM_ROLE {iam_role}" if iam_role else ""
    4214
    4215        region = self.sql(expression, "region")
    4216        region = f" REGION {region}" if region else ""
    4217
    4218        return f"{credentials}{storage}{encryption}{iam_role}{region}"

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

    4220    def copy_sql(self, expression: exp.Copy) -> str:
    4221        this = self.sql(expression, "this")
    4222        this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}"
    4223
    4224        credentials = self.sql(expression, "credentials")
    4225        credentials = self.seg(credentials) if credentials else ""
    4226        kind = self.seg("FROM" if expression.args.get("kind") else "TO")
    4227        files = self.expressions(expression, key="files", flat=True)
    4228
    4229        sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " "
    4230        params = self.expressions(
    4231            expression,
    4232            key="params",
    4233            sep=sep,
    4234            new_line=True,
    4235            skip_last=True,
    4236            skip_first=True,
    4237            indent=self.COPY_PARAMS_ARE_WRAPPED,
    4238        )
    4239
    4240        if params:
    4241            if self.COPY_PARAMS_ARE_WRAPPED:
    4242                params = f" WITH ({params})"
    4243            elif not self.pretty:
    4244                params = f" {params}"
    4245
    4246        return f"COPY{this}{kind} {files}{credentials}{params}"

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

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

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

    4251    def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str:
    4252        on_sql = "ON" if expression.args.get("on") else "OFF"
    4253        filter_col: t.Optional[str] = self.sql(expression, "filter_column")
    4254        filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None
    4255        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    4256        retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None
    4257
    4258        if filter_col or retention_period:
    4259            on_sql = self.func("ON", filter_col, retention_period)
    4260
    4261        return f"DATA_DELETION={on_sql}"

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

    4263    def maskingpolicycolumnconstraint_sql(
    4264        self, expression: exp.MaskingPolicyColumnConstraint
    4265    ) -> str:
    4266        this = self.sql(expression, "this")
    4267        expressions = self.expressions(expression, flat=True)
    4268        expressions = f" USING ({expressions})" if expressions else ""
    4269        return f"MASKING POLICY {this}{expressions}"

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

    4271    def gapfill_sql(self, expression: exp.GapFill) -> str:
    4272        this = self.sql(expression, "this")
    4273        this = f"TABLE {this}"
    4274        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

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

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

    4279    def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str:
    4280        this = self.sql(expression, "this")
    4281        expr = expression.expression
    4282
    4283        if isinstance(expr, exp.Func):
    4284            # T-SQL's CLR functions are case sensitive
    4285            expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})"
    4286        else:
    4287            expr = self.sql(expression, "expression")
    4288
    4289        return self.scope_resolution(expr, this)

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

    4291    def parsejson_sql(self, expression: exp.ParseJSON) -> str:
    4292        if self.PARSE_JSON_NAME is None:
    4293            return self.sql(expression.this)
    4294
    4295        return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression)

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

    4297    def rand_sql(self, expression: exp.Rand) -> str:
    4298        lower = self.sql(expression, "lower")
    4299        upper = self.sql(expression, "upper")
    4300
    4301        if lower and upper:
    4302            return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}"
    4303        return self.func("RAND", expression.this)

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

    4305    def changes_sql(self, expression: exp.Changes) -> str:
    4306        information = self.sql(expression, "information")
    4307        information = f"INFORMATION => {information}"
    4308        at_before = self.sql(expression, "at_before")
    4309        at_before = f"{self.seg('')}{at_before}" if at_before else ""
    4310        end = self.sql(expression, "end")
    4311        end = f"{self.seg('')}{end}" if end else ""
    4312
    4313        return f"CHANGES ({information}){at_before}{end}"

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

    4315    def pad_sql(self, expression: exp.Pad) -> str:
    4316        prefix = "L" if expression.args.get("is_left") else "R"
    4317
    4318        fill_pattern = self.sql(expression, "fill_pattern") or None
    4319        if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED:
    4320            fill_pattern = "' '"
    4321
    4322        return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)

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

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

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

    4328    def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str:
    4329        generate_series = exp.GenerateSeries(**expression.args)
    4330
    4331        parent = expression.parent
    4332        if isinstance(parent, (exp.Alias, exp.TableAlias)):
    4333            parent = parent.parent
    4334
    4335        if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)):
    4336            return self.sql(exp.Unnest(expressions=[generate_series]))
    4337
    4338        if isinstance(parent, exp.Select):
    4339            self.unsupported("GenerateSeries projection unnesting is not supported.")
    4340
    4341        return self.sql(generate_series)

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

    4343    def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str:
    4344        exprs = expression.expressions
    4345        if not self.ARRAY_CONCAT_IS_VAR_LEN:
    4346            rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs)
    4347        else:
    4348            rhs = self.expressions(expression)
    4349
    4350        return self.func(name, expression.this, rhs or None)

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

    4352    def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str:
    4353        if self.SUPPORTS_CONVERT_TIMEZONE:
    4354            return self.function_fallback_sql(expression)
    4355
    4356        source_tz = expression.args.get("source_tz")
    4357        target_tz = expression.args.get("target_tz")
    4358        timestamp = expression.args.get("timestamp")
    4359
    4360        if source_tz and timestamp:
    4361            timestamp = exp.AtTimeZone(
    4362                this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz
    4363            )
    4364
    4365        expr = exp.AtTimeZone(this=timestamp, zone=target_tz)
    4366
    4367        return self.sql(expr)

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

    4369    def json_sql(self, expression: exp.JSON) -> str:
    4370        this = self.sql(expression, "this")
    4371        this = f" {this}" if this else ""
    4372
    4373        _with = expression.args.get("with")
    4374
    4375        if _with is None:
    4376            with_sql = ""
    4377        elif not _with:
    4378            with_sql = " WITHOUT"
    4379        else:
    4380            with_sql = " WITH"
    4381
    4382        unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else ""
    4383
    4384        return f"JSON{this}{with_sql}{unique_sql}"

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

    4386    def jsonvalue_sql(self, expression: exp.JSONValue) -> str:
    4387        def _generate_on_options(arg: t.Any) -> str:
    4388            return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}"
    4389
    4390        path = self.sql(expression, "path")
    4391        returning = self.sql(expression, "returning")
    4392        returning = f" RETURNING {returning}" if returning else ""
    4393
    4394        on_condition = self.sql(expression, "on_condition")
    4395        on_condition = f" {on_condition}" if on_condition else ""
    4396
    4397        return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}")

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

    4399    def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str:
    4400        else_ = "ELSE " if expression.args.get("else_") else ""
    4401        condition = self.sql(expression, "expression")
    4402        condition = f"WHEN {condition} THEN " if condition else else_
    4403        insert = self.sql(expression, "this")[len("INSERT") :].strip()
    4404        return f"{condition}{insert}"

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

    4406    def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str:
    4407        kind = self.sql(expression, "kind")
    4408        expressions = self.seg(self.expressions(expression, sep=" "))
    4409        res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}"
    4410        return res

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

    4412    def oncondition_sql(self, expression: exp.OnCondition) -> str:
    4413        # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR"
    4414        empty = expression.args.get("empty")
    4415        empty = (
    4416            f"DEFAULT {empty} ON EMPTY"
    4417            if isinstance(empty, exp.Expression)
    4418            else self.sql(expression, "empty")
    4419        )
    4420
    4421        error = expression.args.get("error")
    4422        error = (
    4423            f"DEFAULT {error} ON ERROR"
    4424            if isinstance(error, exp.Expression)
    4425            else self.sql(expression, "error")
    4426        )
    4427
    4428        if error and empty:
    4429            error = (
    4430                f"{empty} {error}"
    4431                if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR
    4432                else f"{error} {empty}"
    4433            )
    4434            empty = ""
    4435
    4436        null = self.sql(expression, "null")
    4437
    4438        return f"{empty}{error}{null}"

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

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

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

    4444    def jsonexists_sql(self, expression: exp.JSONExists) -> str:
    4445        this = self.sql(expression, "this")
    4446        path = self.sql(expression, "path")
    4447
    4448        passing = self.expressions(expression, "passing")
    4449        passing = f" PASSING {passing}" if passing else ""
    4450
    4451        on_condition = self.sql(expression, "on_condition")
    4452        on_condition = f" {on_condition}" if on_condition else ""
    4453
    4454        path = f"{path}{passing}{on_condition}"
    4455
    4456        return self.func("JSON_EXISTS", this, path)

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

    4458    def arrayagg_sql(self, expression: exp.ArrayAgg) -> str:
    4459        array_agg = self.function_fallback_sql(expression)
    4460
    4461        # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls
    4462        # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB)
    4463        if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"):
    4464            parent = expression.parent
    4465            if isinstance(parent, exp.Filter):
    4466                parent_cond = parent.expression.this
    4467                parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_()))
    4468            else:
    4469                this = expression.this
    4470                # Do not add the filter if the input is not a column (e.g. literal, struct etc)
    4471                if this.find(exp.Column):
    4472                    # DISTINCT is already present in the agg function, do not propagate it to FILTER as well
    4473                    this_sql = (
    4474                        self.expressions(this)
    4475                        if isinstance(this, exp.Distinct)
    4476                        else self.sql(expression, "this")
    4477                    )
    4478
    4479                    array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)"
    4480
    4481        return array_agg

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

    4483    def apply_sql(self, expression: exp.Apply) -> str:
    4484        this = self.sql(expression, "this")
    4485        expr = self.sql(expression, "expression")
    4486
    4487        return f"{this} APPLY({expr})"

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

    4489    def grant_sql(self, expression: exp.Grant) -> str:
    4490        privileges_sql = self.expressions(expression, key="privileges", flat=True)
    4491
    4492        kind = self.sql(expression, "kind")
    4493        kind = f" {kind}" if kind else ""
    4494
    4495        securable = self.sql(expression, "securable")
    4496        securable = f" {securable}" if securable else ""
    4497
    4498        principals = self.expressions(expression, key="principals", flat=True)
    4499
    4500        grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else ""
    4501
    4502        return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}"

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

    4504    def grantprivilege_sql(self, expression: exp.GrantPrivilege):
    4505        this = self.sql(expression, "this")
    4506        columns = self.expressions(expression, flat=True)
    4507        columns = f"({columns})" if columns else ""
    4508
    4509        return f"{this}{columns}"

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

    4511    def grantprincipal_sql(self, expression: exp.GrantPrincipal):
    4512        this = self.sql(expression, "this")
    4513
    4514        kind = self.sql(expression, "kind")
    4515        kind = f"{kind} " if kind else ""
    4516
    4517        return f"{kind}{this}"

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

    4519    def columns_sql(self, expression: exp.Columns):
    4520        func = self.function_fallback_sql(expression)
    4521        if expression.args.get("unpack"):
    4522            func = f"*{func}"
    4523
    4524        return func

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

    4526    def overlay_sql(self, expression: exp.Overlay):
    4527        this = self.sql(expression, "this")
    4528        expr = self.sql(expression, "expression")
    4529        from_sql = self.sql(expression, "from")
    4530        for_sql = self.sql(expression, "for")
    4531        for_sql = f" FOR {for_sql}" if for_sql else ""
    4532
    4533        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

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

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

    4539    def string_sql(self, expression: exp.String) -> str:
    4540        this = expression.this
    4541        zone = expression.args.get("zone")
    4542
    4543        if zone:
    4544            # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>)
    4545            # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC
    4546            # set for source_tz to transpile the time conversion before the STRING cast
    4547            this = exp.ConvertTimezone(
    4548                source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this
    4549            )
    4550
    4551        return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR))

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

    4553    def median_sql(self, expression: exp.Median):
    4554        if not self.SUPPORTS_MEDIAN:
    4555            return self.sql(
    4556                exp.PercentileCont(this=expression.this, expression=exp.Literal.number(0.5))
    4557            )
    4558
    4559        return self.function_fallback_sql(expression)

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

    4561    def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str:
    4562        filler = self.sql(expression, "this")
    4563        filler = f" {filler}" if filler else ""
    4564        with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT"
    4565        return f"TRUNCATE{filler} {with_count}"

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

    4567    def unixseconds_sql(self, expression: exp.UnixSeconds) -> str:
    4568        if self.SUPPORTS_UNIX_SECONDS:
    4569            return self.function_fallback_sql(expression)
    4570
    4571        start_ts = exp.cast(
    4572            exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ
    4573        )
    4574
    4575        return self.sql(
    4576            exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS"))
    4577        )

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

    4579    def arraysize_sql(self, expression: exp.ArraySize) -> str:
    4580        dim = expression.expression
    4581
    4582        # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension)
    4583        if dim and self.ARRAY_SIZE_DIM_REQUIRED is None:
    4584            if not (dim.is_int and dim.name == "1"):
    4585                self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH")
    4586            dim = None
    4587
    4588        # If dimension is required but not specified, default initialize it
    4589        if self.ARRAY_SIZE_DIM_REQUIRED and not dim:
    4590            dim = exp.Literal.number(1)
    4591
    4592        return self.func(self.ARRAY_SIZE_NAME, expression.this, dim)

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

    4594    def attach_sql(self, expression: exp.Attach) -> str:
    4595        this = self.sql(expression, "this")
    4596        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
    4597        expressions = self.expressions(expression)
    4598        expressions = f" ({expressions})" if expressions else ""
    4599
    4600        return f"ATTACH{exists_sql} {this}{expressions}"

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

    4602    def detach_sql(self, expression: exp.Detach) -> str:
    4603        this = self.sql(expression, "this")
    4604        exists_sql = " IF EXISTS" if expression.args.get("exists") else ""
    4605
    4606        return f"DETACH{exists_sql} {this}"

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

    4608    def attachoption_sql(self, expression: exp.AttachOption) -> str:
    4609        this = self.sql(expression, "this")
    4610        value = self.sql(expression, "expression")
    4611        value = f" {value}" if value else ""
    4612        return f"{this}{value}"

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

    4614    def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str:
    4615        this_sql = self.sql(expression, "this")
    4616        if isinstance(expression.this, exp.Table):
    4617            this_sql = f"TABLE {this_sql}"
    4618
    4619        return self.func(
    4620            "FEATURES_AT_TIME",
    4621            this_sql,
    4622            expression.args.get("time"),
    4623            expression.args.get("num_rows"),
    4624            expression.args.get("ignore_feature_nulls"),
    4625        )

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

    4627    def watermarkcolumnconstraint_sql(self, expression: exp.WatermarkColumnConstraint) -> str:
    4628        return (
    4629            f"WATERMARK FOR {self.sql(expression, 'this')} AS {self.sql(expression, 'expression')}"
    4630        )

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

    4632    def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str:
    4633        encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE"
    4634        encode = f"{encode} {self.sql(expression, 'this')}"
    4635
    4636        properties = expression.args.get("properties")
    4637        if properties:
    4638            encode = f"{encode} {self.properties(properties)}"
    4639
    4640        return encode

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

    4642    def includeproperty_sql(self, expression: exp.IncludeProperty) -> str:
    4643        this = self.sql(expression, "this")
    4644        include = f"INCLUDE {this}"
    4645
    4646        column_def = self.sql(expression, "column_def")
    4647        if column_def:
    4648            include = f"{include} {column_def}"
    4649
    4650        alias = self.sql(expression, "alias")
    4651        if alias:
    4652            include = f"{include} AS {alias}"
    4653
    4654        return include

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

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

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

    4660    def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str:
    4661        partitions = self.expressions(expression, "partition_expressions")
    4662        create = self.expressions(expression, "create_expressions")
    4663        return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}"

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

    4665    def partitionbyrangepropertydynamic_sql(
    4666        self, expression: exp.PartitionByRangePropertyDynamic
    4667    ) -> str:
    4668        start = self.sql(expression, "start")
    4669        end = self.sql(expression, "end")
    4670
    4671        every = expression.args["every"]
    4672        if isinstance(every, exp.Interval) and every.this.is_string:
    4673            every.this.replace(exp.Literal.number(every.name))
    4674
    4675        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

    4677    def unpivotcolumns_sql(self, expression: exp.UnpivotColumns) -> str:
    4678        name = self.sql(expression, "this")
    4679        values = self.expressions(expression, flat=True)
    4680
    4681        return f"NAME {name} VALUE {values}"

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

    4683    def analyzesample_sql(self, expression: exp.AnalyzeSample) -> str:
    4684        kind = self.sql(expression, "kind")
    4685        sample = self.sql(expression, "sample")
    4686        return f"SAMPLE {sample} {kind}"

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

    4688    def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str:
    4689        kind = self.sql(expression, "kind")
    4690        option = self.sql(expression, "option")
    4691        option = f" {option}" if option else ""
    4692        this = self.sql(expression, "this")
    4693        this = f" {this}" if this else ""
    4694        columns = self.expressions(expression)
    4695        columns = f" {columns}" if columns else ""
    4696        return f"{kind}{option} STATISTICS{this}{columns}"

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

    4698    def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str:
    4699        this = self.sql(expression, "this")
    4700        columns = self.expressions(expression)
    4701        inner_expression = self.sql(expression, "expression")
    4702        inner_expression = f" {inner_expression}" if inner_expression else ""
    4703        update_options = self.sql(expression, "update_options")
    4704        update_options = f" {update_options} UPDATE" if update_options else ""
    4705        return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}"

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

    4707    def analyzedelete_sql(self, expression: exp.AnalyzeDelete) -> str:
    4708        kind = self.sql(expression, "kind")
    4709        kind = f" {kind}" if kind else ""
    4710        return f"DELETE{kind} STATISTICS"

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

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

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

    4716    def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str:
    4717        kind = self.sql(expression, "kind")
    4718        this = self.sql(expression, "this")
    4719        this = f" {this}" if this else ""
    4720        inner_expression = self.sql(expression, "expression")
    4721        return f"VALIDATE {kind}{this}{inner_expression}"

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

    4723    def analyze_sql(self, expression: exp.Analyze) -> str:
    4724        options = self.expressions(expression, key="options", sep=" ")
    4725        options = f" {options}" if options else ""
    4726        kind = self.sql(expression, "kind")
    4727        kind = f" {kind}" if kind else ""
    4728        this = self.sql(expression, "this")
    4729        this = f" {this}" if this else ""
    4730        mode = self.sql(expression, "mode")
    4731        mode = f" {mode}" if mode else ""
    4732        properties = self.sql(expression, "properties")
    4733        properties = f" {properties}" if properties else ""
    4734        partition = self.sql(expression, "partition")
    4735        partition = f" {partition}" if partition else ""
    4736        inner_expression = self.sql(expression, "expression")
    4737        inner_expression = f" {inner_expression}" if inner_expression else ""
    4738        return f"ANALYZE{options}{kind}{this}{partition}{mode}{inner_expression}{properties}"

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

    4740    def xmltable_sql(self, expression: exp.XMLTable) -> str:
    4741        this = self.sql(expression, "this")
    4742        namespaces = self.expressions(expression, key="namespaces")
    4743        namespaces = f"XMLNAMESPACES({namespaces}), " if namespaces else ""
    4744        passing = self.expressions(expression, key="passing")
    4745        passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else ""
    4746        columns = self.expressions(expression, key="columns")
    4747        columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else ""
    4748        by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else ""
    4749        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

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