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

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

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

    637    def __init__(
    638        self,
    639        pretty: t.Optional[bool] = None,
    640        identify: str | bool = False,
    641        normalize: bool = False,
    642        pad: int = 2,
    643        indent: int = 2,
    644        normalize_functions: t.Optional[str | bool] = None,
    645        unsupported_level: ErrorLevel = ErrorLevel.WARN,
    646        max_unsupported: int = 3,
    647        leading_comma: bool = False,
    648        max_text_width: int = 80,
    649        comments: bool = True,
    650        dialect: DialectType = None,
    651    ):
    652        import sqlglot
    653        from sqlglot.dialects import Dialect
    654
    655        self.pretty = pretty if pretty is not None else sqlglot.pretty
    656        self.identify = identify
    657        self.normalize = normalize
    658        self.pad = pad
    659        self._indent = indent
    660        self.unsupported_level = unsupported_level
    661        self.max_unsupported = max_unsupported
    662        self.leading_comma = leading_comma
    663        self.max_text_width = max_text_width
    664        self.comments = comments
    665        self.dialect = Dialect.get_or_raise(dialect)
    666
    667        # This is both a Dialect property and a Generator argument, so we prioritize the latter
    668        self.normalize_functions = (
    669            self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions
    670        )
    671
    672        self.unsupported_messages: t.List[str] = []
    673        self._escaped_quote_end: str = (
    674            self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END
    675        )
    676        self._escaped_identifier_end: str = (
    677            self.dialect.tokenizer_class.IDENTIFIER_ESCAPES[0] + self.dialect.IDENTIFIER_END
    678        )
    679
    680        self._next_name = name_sequence("_t")
    681
    682        self._identifier_start = self.dialect.IDENTIFIER_START
    683        self._identifier_end = self.dialect.IDENTIFIER_END

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.AutoRefreshProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.BackupProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CaseSpecificColumnConstraint'>: <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.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.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.TemporaryProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TagColumnConstraint'>: <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.UnpackColumns'>: <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.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.JSONPathRoot'>, <class 'sqlglot.expressions.JSONPathRecursive'>, <class 'sqlglot.expressions.JSONPathKey'>, <class 'sqlglot.expressions.JSONPathWildcard'>, <class 'sqlglot.expressions.JSONPathFilter'>, <class 'sqlglot.expressions.JSONPathUnion'>, <class 'sqlglot.expressions.JSONPathSubscript'>, <class 'sqlglot.expressions.JSONPathSelector'>, <class 'sqlglot.expressions.JSONPathSlice'>, <class 'sqlglot.expressions.JSONPathScript'>}
CAN_IMPLEMENT_ARRAY_ANY = False
SUPPORTS_TO_NUMBER = True
SET_OP_MODIFIERS = True
COPY_PARAMS_ARE_WRAPPED = True
COPY_PARAMS_EQ_REQUIRED = False
COPY_HAS_INTO_KEYWORD = True
TRY_SUPPORTED = True
SUPPORTS_UESCAPE = True
STAR_EXCEPT = 'EXCEPT'
HEX_FUNC = 'HEX'
WITH_PROPERTIES_PREFIX = 'WITH'
QUOTE_JSON_PATH = True
PAD_FILL_PATTERN_IS_REQUIRED = False
SUPPORTS_EXPLODING_PROJECTIONS = True
ARRAY_CONCAT_IS_VAR_LEN = True
SUPPORTS_CONVERT_TIMEZONE = False
PARSE_JSON_NAME: Optional[str] = 'PARSE_JSON'
TYPE_MAPPING = {<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'}
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 = ':'
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.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.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.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.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.Delete'>, <class 'sqlglot.expressions.Drop'>, <class 'sqlglot.expressions.From'>, <class 'sqlglot.expressions.Insert'>, <class 'sqlglot.expressions.Join'>, <class 'sqlglot.expressions.MultitableInserts'>, <class 'sqlglot.expressions.Select'>, <class 'sqlglot.expressions.SetOperation'>, <class 'sqlglot.expressions.Update'>, <class 'sqlglot.expressions.Where'>, <class 'sqlglot.expressions.With'>)
EXCLUDE_COMMENTS: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Binary'>, <class 'sqlglot.expressions.SetOperation'>)
UNWRAPPED_INTERVAL_VALUES: Tuple[Type[sqlglot.expressions.Expression], ...] = (<class 'sqlglot.expressions.Column'>, <class 'sqlglot.expressions.Literal'>, <class 'sqlglot.expressions.Neg'>, <class 'sqlglot.expressions.Paren'>)
PARAMETERIZABLE_TEXT_TYPES = {<Type.CHAR: 'CHAR'>, <Type.NVARCHAR: 'NVARCHAR'>, <Type.NCHAR: 'NCHAR'>, <Type.VARCHAR: 'VARCHAR'>}
EXPRESSIONS_WITHOUT_NESTED_CTES: Set[Type[sqlglot.expressions.Expression]] = set()
SENTINEL_LINE_BREAK = '__SQLGLOT__LB__'
pretty
identify
normalize
pad
unsupported_level
max_unsupported
leading_comma
max_text_width
comments
dialect
normalize_functions
unsupported_messages: List[str]
def generate( self, expression: sqlglot.expressions.Expression, copy: bool = True) -> str: View Source

    685    def generate(self, expression: exp.Expression, copy: bool = True) -> str:
    686        """
    687        Generates the SQL string corresponding to the given syntax tree.
    688
    689        Args:
    690            expression: The syntax tree.
    691            copy: Whether to copy the expression. The generator performs mutations so
    692                it is safer to copy.
    693
    694        Returns:
    695            The SQL string corresponding to `expression`.
    696        """
    697        if copy:
    698            expression = expression.copy()
    699
    700        expression = self.preprocess(expression)
    701
    702        self.unsupported_messages = []
    703        sql = self.sql(expression).strip()
    704
    705        if self.pretty:
    706            sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n")
    707
    708        if self.unsupported_level == ErrorLevel.IGNORE:
    709            return sql
    710
    711        if self.unsupported_level == ErrorLevel.WARN:
    712            for msg in self.unsupported_messages:
    713                logger.warning(msg)
    714        elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages:
    715            raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported))
    716
    717        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

    719    def preprocess(self, expression: exp.Expression) -> exp.Expression:
    720        """Apply generic preprocessing transformations to a given expression."""
    721        if (
    722            not expression.parent
    723            and type(expression) in self.EXPRESSIONS_WITHOUT_NESTED_CTES
    724            and any(node.parent is not expression for node in expression.find_all(exp.With))
    725        ):
    726            from sqlglot.transforms import move_ctes_to_top_level
    727
    728            expression = move_ctes_to_top_level(expression)
    729
    730        if self.ENSURE_BOOLS:
    731            from sqlglot.transforms import ensure_bools
    732
    733            expression = ensure_bools(expression)
    734
    735        return expression

Apply generic preprocessing transformations to a given expression.

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

    737    def unsupported(self, message: str) -> None:
    738        if self.unsupported_level == ErrorLevel.IMMEDIATE:
    739            raise UnsupportedError(message)
    740        self.unsupported_messages.append(message)

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

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

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

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

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

    748    def pad_comment(self, comment: str) -> str:
    749        comment = " " + comment if comment[0].strip() else comment
    750        comment = comment + " " if comment[-1].strip() else comment
    751        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

    753    def maybe_comment(
    754        self,
    755        sql: str,
    756        expression: t.Optional[exp.Expression] = None,
    757        comments: t.Optional[t.List[str]] = None,
    758        separated: bool = False,
    759    ) -> str:
    760        comments = (
    761            ((expression and expression.comments) if comments is None else comments)  # type: ignore
    762            if self.comments
    763            else None
    764        )
    765
    766        if not comments or isinstance(expression, self.EXCLUDE_COMMENTS):
    767            return sql
    768
    769        comments_sql = " ".join(
    770            f"/*{self.pad_comment(comment)}*/" for comment in comments if comment
    771        )
    772
    773        if not comments_sql:
    774            return sql
    775
    776        comments_sql = self._replace_line_breaks(comments_sql)
    777
    778        if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS):
    779            return (
    780                f"{self.sep()}{comments_sql}{sql}"
    781                if not sql or sql[0].isspace()
    782                else f"{comments_sql}{self.sep()}{sql}"
    783            )
    784
    785        return f"{sql} {comments_sql}"

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

    787    def wrap(self, expression: exp.Expression | str) -> str:
    788        this_sql = (
    789            self.sql(expression)
    790            if isinstance(expression, exp.UNWRAPPED_QUERIES)
    791            else self.sql(expression, "this")
    792        )
    793        if not this_sql:
    794            return "()"
    795
    796        this_sql = self.indent(this_sql, level=1, pad=0)
    797        return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"

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

    799    def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str:
    800        original = self.identify
    801        self.identify = False
    802        result = func(*args, **kwargs)
    803        self.identify = original
    804        return result

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

    806    def normalize_func(self, name: str) -> str:
    807        if self.normalize_functions == "upper" or self.normalize_functions is True:
    808            return name.upper()
    809        if self.normalize_functions == "lower":
    810            return name.lower()
    811        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

    813    def indent(
    814        self,
    815        sql: str,
    816        level: int = 0,
    817        pad: t.Optional[int] = None,
    818        skip_first: bool = False,
    819        skip_last: bool = False,
    820    ) -> str:
    821        if not self.pretty or not sql:
    822            return sql
    823
    824        pad = self.pad if pad is None else pad
    825        lines = sql.split("\n")
    826
    827        return "\n".join(
    828            (
    829                line
    830                if (skip_first and i == 0) or (skip_last and i == len(lines) - 1)
    831                else f"{' ' * (level * self._indent + pad)}{line}"
    832            )
    833            for i, line in enumerate(lines)
    834        )

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

    836    def sql(
    837        self,
    838        expression: t.Optional[str | exp.Expression],
    839        key: t.Optional[str] = None,
    840        comment: bool = True,
    841    ) -> str:
    842        if not expression:
    843            return ""
    844
    845        if isinstance(expression, str):
    846            return expression
    847
    848        if key:
    849            value = expression.args.get(key)
    850            if value:
    851                return self.sql(value)
    852            return ""
    853
    854        transform = self.TRANSFORMS.get(expression.__class__)
    855
    856        if callable(transform):
    857            sql = transform(self, expression)
    858        elif isinstance(expression, exp.Expression):
    859            exp_handler_name = f"{expression.key}_sql"
    860
    861            if hasattr(self, exp_handler_name):
    862                sql = getattr(self, exp_handler_name)(expression)
    863            elif isinstance(expression, exp.Func):
    864                sql = self.function_fallback_sql(expression)
    865            elif isinstance(expression, exp.Property):
    866                sql = self.property_sql(expression)
    867            else:
    868                raise ValueError(f"Unsupported expression type {expression.__class__.__name__}")
    869        else:
    870            raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}")
    871
    872        return self.maybe_comment(sql, expression) if self.comments and comment else sql

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

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

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

    879    def cache_sql(self, expression: exp.Cache) -> str:
    880        lazy = " LAZY" if expression.args.get("lazy") else ""
    881        table = self.sql(expression, "this")
    882        options = expression.args.get("options")
    883        options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else ""
    884        sql = self.sql(expression, "expression")
    885        sql = f" AS{self.sep()}{sql}" if sql else ""
    886        sql = f"CACHE{lazy} TABLE {table}{options}{sql}"
    887        return self.prepend_ctes(expression, sql)

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

    889    def characterset_sql(self, expression: exp.CharacterSet) -> str:
    890        if isinstance(expression.parent, exp.Cast):
    891            return f"CHAR CHARACTER SET {self.sql(expression, 'this')}"
    892        default = "DEFAULT " if expression.args.get("default") else ""
    893        return f"{default}CHARACTER SET={self.sql(expression, 'this')}"

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

    895    def column_parts(self, expression: exp.Column) -> str:
    896        return ".".join(
    897            self.sql(part)
    898            for part in (
    899                expression.args.get("catalog"),
    900                expression.args.get("db"),
    901                expression.args.get("table"),
    902                expression.args.get("this"),
    903            )
    904            if part
    905        )

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

    907    def column_sql(self, expression: exp.Column) -> str:
    908        join_mark = " (+)" if expression.args.get("join_mark") else ""
    909
    910        if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS:
    911            join_mark = ""
    912            self.unsupported("Outer join syntax using the (+) operator is not supported.")
    913
    914        return f"{self.column_parts(expression)}{join_mark}"

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

    916    def columnposition_sql(self, expression: exp.ColumnPosition) -> str:
    917        this = self.sql(expression, "this")
    918        this = f" {this}" if this else ""
    919        position = self.sql(expression, "position")
    920        return f"{position}{this}"

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

    922    def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str:
    923        column = self.sql(expression, "this")
    924        kind = self.sql(expression, "kind")
    925        constraints = self.expressions(expression, key="constraints", sep=" ", flat=True)
    926        exists = "IF NOT EXISTS " if expression.args.get("exists") else ""
    927        kind = f"{sep}{kind}" if kind else ""
    928        constraints = f" {constraints}" if constraints else ""
    929        position = self.sql(expression, "position")
    930        position = f" {position}" if position else ""
    931
    932        if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE:
    933            kind = ""
    934
    935        return f"{exists}{column}{kind}{constraints}{position}"

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

    937    def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str:
    938        this = self.sql(expression, "this")
    939        kind_sql = self.sql(expression, "kind").strip()
    940        return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql

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

    942    def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str:
    943        this = self.sql(expression, "this")
    944        if expression.args.get("not_null"):
    945            persisted = " PERSISTED NOT NULL"
    946        elif expression.args.get("persisted"):
    947            persisted = " PERSISTED"
    948        else:
    949            persisted = ""
    950        return f"AS {this}{persisted}"

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

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

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

    955    def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str:
    956        if isinstance(expression.this, list):
    957            this = self.wrap(self.expressions(expression, key="this", flat=True))
    958        else:
    959            this = self.sql(expression, "this")
    960
    961        return f"COMPRESS {this}"

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

    963    def generatedasidentitycolumnconstraint_sql(
    964        self, expression: exp.GeneratedAsIdentityColumnConstraint
    965    ) -> str:
    966        this = ""
    967        if expression.this is not None:
    968            on_null = " ON NULL" if expression.args.get("on_null") else ""
    969            this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}"
    970
    971        start = expression.args.get("start")
    972        start = f"START WITH {start}" if start else ""
    973        increment = expression.args.get("increment")
    974        increment = f" INCREMENT BY {increment}" if increment else ""
    975        minvalue = expression.args.get("minvalue")
    976        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    977        maxvalue = expression.args.get("maxvalue")
    978        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    979        cycle = expression.args.get("cycle")
    980        cycle_sql = ""
    981
    982        if cycle is not None:
    983            cycle_sql = f"{' NO' if not cycle else ''} CYCLE"
    984            cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql
    985
    986        sequence_opts = ""
    987        if start or increment or cycle_sql:
    988            sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}"
    989            sequence_opts = f" ({sequence_opts.strip()})"
    990
    991        expr = self.sql(expression, "expression")
    992        expr = f"({expr})" if expr else "IDENTITY"
    993
    994        return f"GENERATED{this} AS {expr}{sequence_opts}"

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

     996    def generatedasrowcolumnconstraint_sql(
     997        self, expression: exp.GeneratedAsRowColumnConstraint
     998    ) -> str:
     999        start = "START" if expression.args.get("start") else "END"
    1000        hidden = " HIDDEN" if expression.args.get("hidden") else ""
    1001        return f"GENERATED ALWAYS AS ROW {start}{hidden}"

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

    1003    def periodforsystemtimeconstraint_sql(
    1004        self, expression: exp.PeriodForSystemTimeConstraint
    1005    ) -> str:
    1006        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

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

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

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

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

    1014    def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str:
    1015        desc = expression.args.get("desc")
    1016        if desc is not None:
    1017            return f"PRIMARY KEY{' DESC' if desc else ' ASC'}"
    1018        return "PRIMARY KEY"

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

    1020    def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str:
    1021        this = self.sql(expression, "this")
    1022        this = f" {this}" if this else ""
    1023        index_type = expression.args.get("index_type")
    1024        index_type = f" USING {index_type}" if index_type else ""
    1025        on_conflict = self.sql(expression, "on_conflict")
    1026        on_conflict = f" {on_conflict}" if on_conflict else ""
    1027        nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else ""
    1028        return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}"

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

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

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

    1033    def create_sql(self, expression: exp.Create) -> str:
    1034        kind = self.sql(expression, "kind")
    1035        kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind
    1036        properties = expression.args.get("properties")
    1037        properties_locs = self.locate_properties(properties) if properties else defaultdict()
    1038
    1039        this = self.createable_sql(expression, properties_locs)
    1040
    1041        properties_sql = ""
    1042        if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get(
    1043            exp.Properties.Location.POST_WITH
    1044        ):
    1045            properties_sql = self.sql(
    1046                exp.Properties(
    1047                    expressions=[
    1048                        *properties_locs[exp.Properties.Location.POST_SCHEMA],
    1049                        *properties_locs[exp.Properties.Location.POST_WITH],
    1050                    ]
    1051                )
    1052            )
    1053
    1054            if properties_locs.get(exp.Properties.Location.POST_SCHEMA):
    1055                properties_sql = self.sep() + properties_sql
    1056            elif not self.pretty:
    1057                # Standalone POST_WITH properties need a leading whitespace in non-pretty mode
    1058                properties_sql = f" {properties_sql}"
    1059
    1060        begin = " BEGIN" if expression.args.get("begin") else ""
    1061        end = " END" if expression.args.get("end") else ""
    1062
    1063        expression_sql = self.sql(expression, "expression")
    1064        if expression_sql:
    1065            expression_sql = f"{begin}{self.sep()}{expression_sql}{end}"
    1066
    1067            if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return):
    1068                postalias_props_sql = ""
    1069                if properties_locs.get(exp.Properties.Location.POST_ALIAS):
    1070                    postalias_props_sql = self.properties(
    1071                        exp.Properties(
    1072                            expressions=properties_locs[exp.Properties.Location.POST_ALIAS]
    1073                        ),
    1074                        wrapped=False,
    1075                    )
    1076                postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else ""
    1077                expression_sql = f" AS{postalias_props_sql}{expression_sql}"
    1078
    1079        postindex_props_sql = ""
    1080        if properties_locs.get(exp.Properties.Location.POST_INDEX):
    1081            postindex_props_sql = self.properties(
    1082                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]),
    1083                wrapped=False,
    1084                prefix=" ",
    1085            )
    1086
    1087        indexes = self.expressions(expression, key="indexes", indent=False, sep=" ")
    1088        indexes = f" {indexes}" if indexes else ""
    1089        index_sql = indexes + postindex_props_sql
    1090
    1091        replace = " OR REPLACE" if expression.args.get("replace") else ""
    1092        refresh = " OR REFRESH" if expression.args.get("refresh") else ""
    1093        unique = " UNIQUE" if expression.args.get("unique") else ""
    1094
    1095        clustered = expression.args.get("clustered")
    1096        if clustered is None:
    1097            clustered_sql = ""
    1098        elif clustered:
    1099            clustered_sql = " CLUSTERED COLUMNSTORE"
    1100        else:
    1101            clustered_sql = " NONCLUSTERED COLUMNSTORE"
    1102
    1103        postcreate_props_sql = ""
    1104        if properties_locs.get(exp.Properties.Location.POST_CREATE):
    1105            postcreate_props_sql = self.properties(
    1106                exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]),
    1107                sep=" ",
    1108                prefix=" ",
    1109                wrapped=False,
    1110            )
    1111
    1112        modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql))
    1113
    1114        postexpression_props_sql = ""
    1115        if properties_locs.get(exp.Properties.Location.POST_EXPRESSION):
    1116            postexpression_props_sql = self.properties(
    1117                exp.Properties(
    1118                    expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION]
    1119                ),
    1120                sep=" ",
    1121                prefix=" ",
    1122                wrapped=False,
    1123            )
    1124
    1125        concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else ""
    1126        exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else ""
    1127        no_schema_binding = (
    1128            " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else ""
    1129        )
    1130
    1131        clone = self.sql(expression, "clone")
    1132        clone = f" {clone}" if clone else ""
    1133
    1134        expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_sql}{expression_sql}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}"
    1135        return self.prepend_ctes(expression, expression_sql)

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

    1137    def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str:
    1138        start = self.sql(expression, "start")
    1139        start = f"START WITH {start}" if start else ""
    1140        increment = self.sql(expression, "increment")
    1141        increment = f" INCREMENT BY {increment}" if increment else ""
    1142        minvalue = self.sql(expression, "minvalue")
    1143        minvalue = f" MINVALUE {minvalue}" if minvalue else ""
    1144        maxvalue = self.sql(expression, "maxvalue")
    1145        maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else ""
    1146        owned = self.sql(expression, "owned")
    1147        owned = f" OWNED BY {owned}" if owned else ""
    1148
    1149        cache = expression.args.get("cache")
    1150        if cache is None:
    1151            cache_str = ""
    1152        elif cache is True:
    1153            cache_str = " CACHE"
    1154        else:
    1155            cache_str = f" CACHE {cache}"
    1156
    1157        options = self.expressions(expression, key="options", flat=True, sep=" ")
    1158        options = f" {options}" if options else ""
    1159
    1160        return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip()

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

    1162    def clone_sql(self, expression: exp.Clone) -> str:
    1163        this = self.sql(expression, "this")
    1164        shallow = "SHALLOW " if expression.args.get("shallow") else ""
    1165        keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE"
    1166        return f"{shallow}{keyword} {this}"

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

    1168    def describe_sql(self, expression: exp.Describe) -> str:
    1169        style = expression.args.get("style")
    1170        style = f" {style}" if style else ""
    1171        partition = self.sql(expression, "partition")
    1172        partition = f" {partition}" if partition else ""
    1173        return f"DESCRIBE{style} {self.sql(expression, 'this')}{partition}"

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

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

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

    1179    def prepend_ctes(self, expression: exp.Expression, sql: str) -> str:
    1180        with_ = self.sql(expression, "with")
    1181        if with_:
    1182            sql = f"{with_}{self.sep()}{sql}"
    1183        return sql

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

    1185    def with_sql(self, expression: exp.With) -> str:
    1186        sql = self.expressions(expression, flat=True)
    1187        recursive = (
    1188            "RECURSIVE "
    1189            if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive")
    1190            else ""
    1191        )
    1192
    1193        return f"WITH {recursive}{sql}"

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

    1195    def cte_sql(self, expression: exp.CTE) -> str:
    1196        alias = self.sql(expression, "alias")
    1197
    1198        materialized = expression.args.get("materialized")
    1199        if materialized is False:
    1200            materialized = "NOT MATERIALIZED "
    1201        elif materialized:
    1202            materialized = "MATERIALIZED "
    1203
    1204        return f"{alias} AS {materialized or ''}{self.wrap(expression)}"

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

    1206    def tablealias_sql(self, expression: exp.TableAlias) -> str:
    1207        alias = self.sql(expression, "this")
    1208        columns = self.expressions(expression, key="columns", flat=True)
    1209        columns = f"({columns})" if columns else ""
    1210
    1211        if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS:
    1212            columns = ""
    1213            self.unsupported("Named columns are not supported in table alias.")
    1214
    1215        if not alias and not self.dialect.UNNEST_COLUMN_ONLY:
    1216            alias = self._next_name()
    1217
    1218        return f"{alias}{columns}"

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

    1220    def bitstring_sql(self, expression: exp.BitString) -> str:
    1221        this = self.sql(expression, "this")
    1222        if self.dialect.BIT_START:
    1223            return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}"
    1224        return f"{int(this, 2)}"

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

    1226    def hexstring_sql(self, expression: exp.HexString) -> str:
    1227        this = self.sql(expression, "this")
    1228        if self.dialect.HEX_START:
    1229            return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"
    1230        return f"{int(this, 16)}"

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

    1232    def bytestring_sql(self, expression: exp.ByteString) -> str:
    1233        this = self.sql(expression, "this")
    1234        if self.dialect.BYTE_START:
    1235            return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}"
    1236        return this

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

    1238    def unicodestring_sql(self, expression: exp.UnicodeString) -> str:
    1239        this = self.sql(expression, "this")
    1240        escape = expression.args.get("escape")
    1241
    1242        if self.dialect.UNICODE_START:
    1243            escape_substitute = r"\\\1"
    1244            left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END
    1245        else:
    1246            escape_substitute = r"\\u\1"
    1247            left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END
    1248
    1249        if escape:
    1250            escape_pattern = re.compile(rf"{escape.name}(\d+)")
    1251            escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else ""
    1252        else:
    1253            escape_pattern = ESCAPED_UNICODE_RE
    1254            escape_sql = ""
    1255
    1256        if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE):
    1257            this = escape_pattern.sub(escape_substitute, this)
    1258
    1259        return f"{left_quote}{this}{right_quote}{escape_sql}"

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

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

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

    1265    def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str:
    1266        this = self.sql(expression, "this")
    1267        specifier = self.sql(expression, "expression")
    1268        specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else ""
    1269        return f"{this}{specifier}"

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

    1271    def datatype_sql(self, expression: exp.DataType) -> str:
    1272        nested = ""
    1273        values = ""
    1274        interior = self.expressions(expression, flat=True)
    1275
    1276        type_value = expression.this
    1277        if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"):
    1278            type_sql = self.sql(expression, "kind")
    1279        else:
    1280            type_sql = (
    1281                self.TYPE_MAPPING.get(type_value, type_value.value)
    1282                if isinstance(type_value, exp.DataType.Type)
    1283                else type_value
    1284            )
    1285
    1286        if interior:
    1287            if expression.args.get("nested"):
    1288                nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}"
    1289                if expression.args.get("values") is not None:
    1290                    delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")")
    1291                    values = self.expressions(expression, key="values", flat=True)
    1292                    values = f"{delimiters[0]}{values}{delimiters[1]}"
    1293            elif type_value == exp.DataType.Type.INTERVAL:
    1294                nested = f" {interior}"
    1295            else:
    1296                nested = f"({interior})"
    1297
    1298        type_sql = f"{type_sql}{nested}{values}"
    1299        if self.TZ_TO_WITH_TIME_ZONE and type_value in (
    1300            exp.DataType.Type.TIMETZ,
    1301            exp.DataType.Type.TIMESTAMPTZ,
    1302        ):
    1303            type_sql = f"{type_sql} WITH TIME ZONE"
    1304
    1305        return type_sql

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

    1307    def directory_sql(self, expression: exp.Directory) -> str:
    1308        local = "LOCAL " if expression.args.get("local") else ""
    1309        row_format = self.sql(expression, "row_format")
    1310        row_format = f" {row_format}" if row_format else ""
    1311        return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"

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

    1313    def delete_sql(self, expression: exp.Delete) -> str:
    1314        this = self.sql(expression, "this")
    1315        this = f" FROM {this}" if this else ""
    1316        using = self.sql(expression, "using")
    1317        using = f" USING {using}" if using else ""
    1318        where = self.sql(expression, "where")
    1319        returning = self.sql(expression, "returning")
    1320        limit = self.sql(expression, "limit")
    1321        tables = self.expressions(expression, key="tables")
    1322        tables = f" {tables}" if tables else ""
    1323        if self.RETURNING_END:
    1324            expression_sql = f"{this}{using}{where}{returning}{limit}"
    1325        else:
    1326            expression_sql = f"{returning}{this}{using}{where}{limit}"
    1327        return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")

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

    1329    def drop_sql(self, expression: exp.Drop) -> str:
    1330        this = self.sql(expression, "this")
    1331        expressions = self.expressions(expression, flat=True)
    1332        expressions = f" ({expressions})" if expressions else ""
    1333        kind = expression.args["kind"]
    1334        kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind
    1335        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    1336        concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else ""
    1337        on_cluster = self.sql(expression, "cluster")
    1338        on_cluster = f" {on_cluster}" if on_cluster else ""
    1339        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    1340        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    1341        cascade = " CASCADE" if expression.args.get("cascade") else ""
    1342        constraints = " CONSTRAINTS" if expression.args.get("constraints") else ""
    1343        purge = " PURGE" if expression.args.get("purge") else ""
    1344        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

    1346    def set_operation(self, expression: exp.SetOperation) -> str:
    1347        op_type = type(expression)
    1348        op_name = op_type.key.upper()
    1349
    1350        distinct = expression.args.get("distinct")
    1351        if (
    1352            distinct is False
    1353            and op_type in (exp.Except, exp.Intersect)
    1354            and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE
    1355        ):
    1356            self.unsupported(f"{op_name} ALL is not supported")
    1357
    1358        default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type]
    1359
    1360        if distinct is None:
    1361            distinct = default_distinct
    1362            if distinct is None:
    1363                self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified")
    1364
    1365        if distinct is default_distinct:
    1366            kind = ""
    1367        else:
    1368            kind = " DISTINCT" if distinct else " ALL"
    1369
    1370        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1371        return f"{op_name}{kind}{by_name}"

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

    1373    def set_operations(self, expression: exp.SetOperation) -> str:
    1374        if not self.SET_OP_MODIFIERS:
    1375            limit = expression.args.get("limit")
    1376            order = expression.args.get("order")
    1377
    1378            if limit or order:
    1379                select = exp.subquery(expression, "_l_0", copy=False).select("*", copy=False)
    1380
    1381                if limit:
    1382                    select = select.limit(limit.pop(), copy=False)
    1383                if order:
    1384                    select = select.order_by(order.pop(), copy=False)
    1385                return self.sql(select)
    1386
    1387        sqls: t.List[str] = []
    1388        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    1389
    1390        while stack:
    1391            node = stack.pop()
    1392
    1393            if isinstance(node, exp.SetOperation):
    1394                stack.append(node.expression)
    1395                stack.append(
    1396                    self.maybe_comment(
    1397                        self.set_operation(node), comments=node.comments, separated=True
    1398                    )
    1399                )
    1400                stack.append(node.this)
    1401            else:
    1402                sqls.append(self.sql(node))
    1403
    1404        this = self.sep().join(sqls)
    1405        this = self.query_modifiers(expression, this)
    1406        return self.prepend_ctes(expression, this)

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

    1408    def fetch_sql(self, expression: exp.Fetch) -> str:
    1409        direction = expression.args.get("direction")
    1410        direction = f" {direction}" if direction else ""
    1411        count = self.sql(expression, "count")
    1412        count = f" {count}" if count else ""
    1413        if expression.args.get("percent"):
    1414            count = f"{count} PERCENT"
    1415        with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY"
    1416        return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}"

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

    1418    def filter_sql(self, expression: exp.Filter) -> str:
    1419        if self.AGGREGATE_FILTER_SUPPORTED:
    1420            this = self.sql(expression, "this")
    1421            where = self.sql(expression, "expression").strip()
    1422            return f"{this} FILTER({where})"
    1423
    1424        agg = expression.this
    1425        agg_arg = agg.this
    1426        cond = expression.expression.this
    1427        agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy()))
    1428        return self.sql(agg)

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

    1430    def hint_sql(self, expression: exp.Hint) -> str:
    1431        if not self.QUERY_HINTS:
    1432            self.unsupported("Hints are not supported")
    1433            return ""
    1434
    1435        return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */"

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

    1437    def indexparameters_sql(self, expression: exp.IndexParameters) -> str:
    1438        using = self.sql(expression, "using")
    1439        using = f" USING {using}" if using else ""
    1440        columns = self.expressions(expression, key="columns", flat=True)
    1441        columns = f"({columns})" if columns else ""
    1442        partition_by = self.expressions(expression, key="partition_by", flat=True)
    1443        partition_by = f" PARTITION BY {partition_by}" if partition_by else ""
    1444        where = self.sql(expression, "where")
    1445        include = self.expressions(expression, key="include", flat=True)
    1446        if include:
    1447            include = f" INCLUDE ({include})"
    1448        with_storage = self.expressions(expression, key="with_storage", flat=True)
    1449        with_storage = f" WITH ({with_storage})" if with_storage else ""
    1450        tablespace = self.sql(expression, "tablespace")
    1451        tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else ""
    1452        on = self.sql(expression, "on")
    1453        on = f" ON {on}" if on else ""
    1454
    1455        return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"

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

    1457    def index_sql(self, expression: exp.Index) -> str:
    1458        unique = "UNIQUE " if expression.args.get("unique") else ""
    1459        primary = "PRIMARY " if expression.args.get("primary") else ""
    1460        amp = "AMP " if expression.args.get("amp") else ""
    1461        name = self.sql(expression, "this")
    1462        name = f"{name} " if name else ""
    1463        table = self.sql(expression, "table")
    1464        table = f"{self.INDEX_ON} {table}" if table else ""
    1465
    1466        index = "INDEX " if not table else ""
    1467
    1468        params = self.sql(expression, "params")
    1469        return f"{unique}{primary}{amp}{index}{name}{table}{params}"

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

    1471    def identifier_sql(self, expression: exp.Identifier) -> str:
    1472        text = expression.name
    1473        lower = text.lower()
    1474        text = lower if self.normalize and not expression.quoted else text
    1475        text = text.replace(self._identifier_end, self._escaped_identifier_end)
    1476        if (
    1477            expression.quoted
    1478            or self.dialect.can_identify(text, self.identify)
    1479            or lower in self.RESERVED_KEYWORDS
    1480            or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit())
    1481        ):
    1482            text = f"{self._identifier_start}{text}{self._identifier_end}"
    1483        return text

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

    1485    def hex_sql(self, expression: exp.Hex) -> str:
    1486        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1487        if self.dialect.HEX_LOWERCASE:
    1488            text = self.func("LOWER", text)
    1489
    1490        return text

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

    1492    def lowerhex_sql(self, expression: exp.LowerHex) -> str:
    1493        text = self.func(self.HEX_FUNC, self.sql(expression, "this"))
    1494        if not self.dialect.HEX_LOWERCASE:
    1495            text = self.func("LOWER", text)
    1496        return text

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

    1498    def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str:
    1499        input_format = self.sql(expression, "input_format")
    1500        input_format = f"INPUTFORMAT {input_format}" if input_format else ""
    1501        output_format = self.sql(expression, "output_format")
    1502        output_format = f"OUTPUTFORMAT {output_format}" if output_format else ""
    1503        return self.sep().join((input_format, output_format))

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

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

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

    1509    def partition_sql(self, expression: exp.Partition) -> str:
    1510        return f"PARTITION({self.expressions(expression, flat=True)})"

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

    1512    def properties_sql(self, expression: exp.Properties) -> str:
    1513        root_properties = []
    1514        with_properties = []
    1515
    1516        for p in expression.expressions:
    1517            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1518            if p_loc == exp.Properties.Location.POST_WITH:
    1519                with_properties.append(p)
    1520            elif p_loc == exp.Properties.Location.POST_SCHEMA:
    1521                root_properties.append(p)
    1522
    1523        root_props = self.root_properties(exp.Properties(expressions=root_properties))
    1524        with_props = self.with_properties(exp.Properties(expressions=with_properties))
    1525
    1526        if root_props and with_props and not self.pretty:
    1527            with_props = " " + with_props
    1528
    1529        return root_props + with_props

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

    1531    def root_properties(self, properties: exp.Properties) -> str:
    1532        if properties.expressions:
    1533            return self.expressions(properties, indent=False, sep=" ")
    1534        return ""

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

    1536    def properties(
    1537        self,
    1538        properties: exp.Properties,
    1539        prefix: str = "",
    1540        sep: str = ", ",
    1541        suffix: str = "",
    1542        wrapped: bool = True,
    1543    ) -> str:
    1544        if properties.expressions:
    1545            expressions = self.expressions(properties, sep=sep, indent=False)
    1546            if expressions:
    1547                expressions = self.wrap(expressions) if wrapped else expressions
    1548                return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}"
    1549        return ""

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

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

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

    1554    def locate_properties(self, properties: exp.Properties) -> t.DefaultDict:
    1555        properties_locs = defaultdict(list)
    1556        for p in properties.expressions:
    1557            p_loc = self.PROPERTIES_LOCATION[p.__class__]
    1558            if p_loc != exp.Properties.Location.UNSUPPORTED:
    1559                properties_locs[p_loc].append(p)
    1560            else:
    1561                self.unsupported(f"Unsupported property {p.key}")
    1562
    1563        return properties_locs

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

    1565    def property_name(self, expression: exp.Property, string_key: bool = False) -> str:
    1566        if isinstance(expression.this, exp.Dot):
    1567            return self.sql(expression, "this")
    1568        return f"'{expression.name}'" if string_key else expression.name

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

    1570    def property_sql(self, expression: exp.Property) -> str:
    1571        property_cls = expression.__class__
    1572        if property_cls == exp.Property:
    1573            return f"{self.property_name(expression)}={self.sql(expression, 'value')}"
    1574
    1575        property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls)
    1576        if not property_name:
    1577            self.unsupported(f"Unsupported property {expression.key}")
    1578
    1579        return f"{property_name}={self.sql(expression, 'this')}"

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

    1581    def likeproperty_sql(self, expression: exp.LikeProperty) -> str:
    1582        if self.SUPPORTS_CREATE_TABLE_LIKE:
    1583            options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions)
    1584            options = f" {options}" if options else ""
    1585
    1586            like = f"LIKE {self.sql(expression, 'this')}{options}"
    1587            if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema):
    1588                like = f"({like})"
    1589
    1590            return like
    1591
    1592        if expression.expressions:
    1593            self.unsupported("Transpilation of LIKE property options is unsupported")
    1594
    1595        select = exp.select("*").from_(expression.this).limit(0)
    1596        return f"AS {self.sql(select)}"

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

    1598    def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str:
    1599        no = "NO " if expression.args.get("no") else ""
    1600        protection = " PROTECTION" if expression.args.get("protection") else ""
    1601        return f"{no}FALLBACK{protection}"

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

    1603    def journalproperty_sql(self, expression: exp.JournalProperty) -> str:
    1604        no = "NO " if expression.args.get("no") else ""
    1605        local = expression.args.get("local")
    1606        local = f"{local} " if local else ""
    1607        dual = "DUAL " if expression.args.get("dual") else ""
    1608        before = "BEFORE " if expression.args.get("before") else ""
    1609        after = "AFTER " if expression.args.get("after") else ""
    1610        return f"{no}{local}{dual}{before}{after}JOURNAL"

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

    1612    def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str:
    1613        freespace = self.sql(expression, "this")
    1614        percent = " PERCENT" if expression.args.get("percent") else ""
    1615        return f"FREESPACE={freespace}{percent}"

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

    1617    def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str:
    1618        if expression.args.get("default"):
    1619            property = "DEFAULT"
    1620        elif expression.args.get("on"):
    1621            property = "ON"
    1622        else:
    1623            property = "OFF"
    1624        return f"CHECKSUM={property}"

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

    1626    def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str:
    1627        if expression.args.get("no"):
    1628            return "NO MERGEBLOCKRATIO"
    1629        if expression.args.get("default"):
    1630            return "DEFAULT MERGEBLOCKRATIO"
    1631
    1632        percent = " PERCENT" if expression.args.get("percent") else ""
    1633        return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"

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

    1635    def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str:
    1636        default = expression.args.get("default")
    1637        minimum = expression.args.get("minimum")
    1638        maximum = expression.args.get("maximum")
    1639        if default or minimum or maximum:
    1640            if default:
    1641                prop = "DEFAULT"
    1642            elif minimum:
    1643                prop = "MINIMUM"
    1644            else:
    1645                prop = "MAXIMUM"
    1646            return f"{prop} DATABLOCKSIZE"
    1647        units = expression.args.get("units")
    1648        units = f" {units}" if units else ""
    1649        return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"

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

    1651    def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str:
    1652        autotemp = expression.args.get("autotemp")
    1653        always = expression.args.get("always")
    1654        default = expression.args.get("default")
    1655        manual = expression.args.get("manual")
    1656        never = expression.args.get("never")
    1657
    1658        if autotemp is not None:
    1659            prop = f"AUTOTEMP({self.expressions(autotemp)})"
    1660        elif always:
    1661            prop = "ALWAYS"
    1662        elif default:
    1663            prop = "DEFAULT"
    1664        elif manual:
    1665            prop = "MANUAL"
    1666        elif never:
    1667            prop = "NEVER"
    1668        return f"BLOCKCOMPRESSION={prop}"

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

    1670    def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str:
    1671        no = expression.args.get("no")
    1672        no = " NO" if no else ""
    1673        concurrent = expression.args.get("concurrent")
    1674        concurrent = " CONCURRENT" if concurrent else ""
    1675        target = self.sql(expression, "target")
    1676        target = f" {target}" if target else ""
    1677        return f"WITH{no}{concurrent} ISOLATED LOADING{target}"

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

    1679    def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str:
    1680        if isinstance(expression.this, list):
    1681            return f"IN ({self.expressions(expression, key='this', flat=True)})"
    1682        if expression.this:
    1683            modulus = self.sql(expression, "this")
    1684            remainder = self.sql(expression, "expression")
    1685            return f"WITH (MODULUS {modulus}, REMAINDER {remainder})"
    1686
    1687        from_expressions = self.expressions(expression, key="from_expressions", flat=True)
    1688        to_expressions = self.expressions(expression, key="to_expressions", flat=True)
    1689        return f"FROM ({from_expressions}) TO ({to_expressions})"

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

    1691    def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str:
    1692        this = self.sql(expression, "this")
    1693
    1694        for_values_or_default = expression.expression
    1695        if isinstance(for_values_or_default, exp.PartitionBoundSpec):
    1696            for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}"
    1697        else:
    1698            for_values_or_default = " DEFAULT"
    1699
    1700        return f"PARTITION OF {this}{for_values_or_default}"

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

    1702    def lockingproperty_sql(self, expression: exp.LockingProperty) -> str:
    1703        kind = expression.args.get("kind")
    1704        this = f" {self.sql(expression, 'this')}" if expression.this else ""
    1705        for_or_in = expression.args.get("for_or_in")
    1706        for_or_in = f" {for_or_in}" if for_or_in else ""
    1707        lock_type = expression.args.get("lock_type")
    1708        override = " OVERRIDE" if expression.args.get("override") else ""
    1709        return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"

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

    1711    def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str:
    1712        data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA"
    1713        statistics = expression.args.get("statistics")
    1714        statistics_sql = ""
    1715        if statistics is not None:
    1716            statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS"
    1717        return f"{data_sql}{statistics_sql}"

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

    1719    def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str:
    1720        this = self.sql(expression, "this")
    1721        this = f"HISTORY_TABLE={this}" if this else ""
    1722        data_consistency: t.Optional[str] = self.sql(expression, "data_consistency")
    1723        data_consistency = (
    1724            f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None
    1725        )
    1726        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    1727        retention_period = (
    1728            f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None
    1729        )
    1730
    1731        if this:
    1732            on_sql = self.func("ON", this, data_consistency, retention_period)
    1733        else:
    1734            on_sql = "ON" if expression.args.get("on") else "OFF"
    1735
    1736        sql = f"SYSTEM_VERSIONING={on_sql}"
    1737
    1738        return f"WITH({sql})" if expression.args.get("with") else sql

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

    1740    def insert_sql(self, expression: exp.Insert) -> str:
    1741        hint = self.sql(expression, "hint")
    1742        overwrite = expression.args.get("overwrite")
    1743
    1744        if isinstance(expression.this, exp.Directory):
    1745            this = " OVERWRITE" if overwrite else " INTO"
    1746        else:
    1747            this = self.INSERT_OVERWRITE if overwrite else " INTO"
    1748
    1749        stored = self.sql(expression, "stored")
    1750        stored = f" {stored}" if stored else ""
    1751        alternative = expression.args.get("alternative")
    1752        alternative = f" OR {alternative}" if alternative else ""
    1753        ignore = " IGNORE" if expression.args.get("ignore") else ""
    1754        is_function = expression.args.get("is_function")
    1755        if is_function:
    1756            this = f"{this} FUNCTION"
    1757        this = f"{this} {self.sql(expression, 'this')}"
    1758
    1759        exists = " IF EXISTS" if expression.args.get("exists") else ""
    1760        where = self.sql(expression, "where")
    1761        where = f"{self.sep()}REPLACE WHERE {where}" if where else ""
    1762        expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}"
    1763        on_conflict = self.sql(expression, "conflict")
    1764        on_conflict = f" {on_conflict}" if on_conflict else ""
    1765        by_name = " BY NAME" if expression.args.get("by_name") else ""
    1766        returning = self.sql(expression, "returning")
    1767
    1768        if self.RETURNING_END:
    1769            expression_sql = f"{expression_sql}{on_conflict}{returning}"
    1770        else:
    1771            expression_sql = f"{returning}{expression_sql}{on_conflict}"
    1772
    1773        partition_by = self.sql(expression, "partition")
    1774        partition_by = f" {partition_by}" if partition_by else ""
    1775        settings = self.sql(expression, "settings")
    1776        settings = f" {settings}" if settings else ""
    1777
    1778        source = self.sql(expression, "source")
    1779        source = f"TABLE {source}" if source else ""
    1780
    1781        sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}"
    1782        return self.prepend_ctes(expression, sql)

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

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

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

    1787    def kill_sql(self, expression: exp.Kill) -> str:
    1788        kind = self.sql(expression, "kind")
    1789        kind = f" {kind}" if kind else ""
    1790        this = self.sql(expression, "this")
    1791        this = f" {this}" if this else ""
    1792        return f"KILL{kind}{this}"

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

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

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

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

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

    1800    def onconflict_sql(self, expression: exp.OnConflict) -> str:
    1801        conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT"
    1802
    1803        constraint = self.sql(expression, "constraint")
    1804        constraint = f" ON CONSTRAINT {constraint}" if constraint else ""
    1805
    1806        conflict_keys = self.expressions(expression, key="conflict_keys", flat=True)
    1807        conflict_keys = f"({conflict_keys}) " if conflict_keys else " "
    1808        action = self.sql(expression, "action")
    1809
    1810        expressions = self.expressions(expression, flat=True)
    1811        if expressions:
    1812            set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else ""
    1813            expressions = f" {set_keyword}{expressions}"
    1814
    1815        return f"{conflict}{constraint}{conflict_keys}{action}{expressions}"

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

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

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

    1820    def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str:
    1821        fields = self.sql(expression, "fields")
    1822        fields = f" FIELDS TERMINATED BY {fields}" if fields else ""
    1823        escaped = self.sql(expression, "escaped")
    1824        escaped = f" ESCAPED BY {escaped}" if escaped else ""
    1825        items = self.sql(expression, "collection_items")
    1826        items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else ""
    1827        keys = self.sql(expression, "map_keys")
    1828        keys = f" MAP KEYS TERMINATED BY {keys}" if keys else ""
    1829        lines = self.sql(expression, "lines")
    1830        lines = f" LINES TERMINATED BY {lines}" if lines else ""
    1831        null = self.sql(expression, "null")
    1832        null = f" NULL DEFINED AS {null}" if null else ""
    1833        return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"

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

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

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

    1838    def indextablehint_sql(self, expression: exp.IndexTableHint) -> str:
    1839        this = f"{self.sql(expression, 'this')} INDEX"
    1840        target = self.sql(expression, "target")
    1841        target = f" FOR {target}" if target else ""
    1842        return f"{this}{target} ({self.expressions(expression, flat=True)})"

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

    1844    def historicaldata_sql(self, expression: exp.HistoricalData) -> str:
    1845        this = self.sql(expression, "this")
    1846        kind = self.sql(expression, "kind")
    1847        expr = self.sql(expression, "expression")
    1848        return f"{this} ({kind} => {expr})"

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

    1850    def table_parts(self, expression: exp.Table) -> str:
    1851        return ".".join(
    1852            self.sql(part)
    1853            for part in (
    1854                expression.args.get("catalog"),
    1855                expression.args.get("db"),
    1856                expression.args.get("this"),
    1857            )
    1858            if part is not None
    1859        )

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

    1861    def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str:
    1862        table = self.table_parts(expression)
    1863        only = "ONLY " if expression.args.get("only") else ""
    1864        partition = self.sql(expression, "partition")
    1865        partition = f" {partition}" if partition else ""
    1866        version = self.sql(expression, "version")
    1867        version = f" {version}" if version else ""
    1868        alias = self.sql(expression, "alias")
    1869        alias = f"{sep}{alias}" if alias else ""
    1870
    1871        sample = self.sql(expression, "sample")
    1872        if self.dialect.ALIAS_POST_TABLESAMPLE:
    1873            sample_pre_alias = sample
    1874            sample_post_alias = ""
    1875        else:
    1876            sample_pre_alias = ""
    1877            sample_post_alias = sample
    1878
    1879        hints = self.expressions(expression, key="hints", sep=" ")
    1880        hints = f" {hints}" if hints and self.TABLE_HINTS else ""
    1881        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    1882        joins = self.indent(
    1883            self.expressions(expression, key="joins", sep="", flat=True), skip_first=True
    1884        )
    1885        laterals = self.expressions(expression, key="laterals", sep="")
    1886
    1887        file_format = self.sql(expression, "format")
    1888        if file_format:
    1889            pattern = self.sql(expression, "pattern")
    1890            pattern = f", PATTERN => {pattern}" if pattern else ""
    1891            file_format = f" (FILE_FORMAT => {file_format}{pattern})"
    1892
    1893        ordinality = expression.args.get("ordinality") or ""
    1894        if ordinality:
    1895            ordinality = f" WITH ORDINALITY{alias}"
    1896            alias = ""
    1897
    1898        when = self.sql(expression, "when")
    1899        if when:
    1900            table = f"{table} {when}"
    1901
    1902        changes = self.sql(expression, "changes")
    1903        changes = f" {changes}" if changes else ""
    1904
    1905        rows_from = self.expressions(expression, key="rows_from")
    1906        if rows_from:
    1907            table = f"ROWS FROM {self.wrap(rows_from)}"
    1908
    1909        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

    1911    def tablesample_sql(
    1912        self,
    1913        expression: exp.TableSample,
    1914        tablesample_keyword: t.Optional[str] = None,
    1915    ) -> str:
    1916        method = self.sql(expression, "method")
    1917        method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else ""
    1918        numerator = self.sql(expression, "bucket_numerator")
    1919        denominator = self.sql(expression, "bucket_denominator")
    1920        field = self.sql(expression, "bucket_field")
    1921        field = f" ON {field}" if field else ""
    1922        bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else ""
    1923        seed = self.sql(expression, "seed")
    1924        seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else ""
    1925
    1926        size = self.sql(expression, "size")
    1927        if size and self.TABLESAMPLE_SIZE_IS_ROWS:
    1928            size = f"{size} ROWS"
    1929
    1930        percent = self.sql(expression, "percent")
    1931        if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT:
    1932            percent = f"{percent} PERCENT"
    1933
    1934        expr = f"{bucket}{percent}{size}"
    1935        if self.TABLESAMPLE_REQUIRES_PARENS:
    1936            expr = f"({expr})"
    1937
    1938        return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}"

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

    1940    def pivot_sql(self, expression: exp.Pivot) -> str:
    1941        expressions = self.expressions(expression, flat=True)
    1942
    1943        if expression.this:
    1944            this = self.sql(expression, "this")
    1945            if not expressions:
    1946                return f"UNPIVOT {this}"
    1947
    1948            on = f"{self.seg('ON')} {expressions}"
    1949            using = self.expressions(expression, key="using", flat=True)
    1950            using = f"{self.seg('USING')} {using}" if using else ""
    1951            group = self.sql(expression, "group")
    1952            return f"PIVOT {this}{on}{using}{group}"
    1953
    1954        alias = self.sql(expression, "alias")
    1955        alias = f" AS {alias}" if alias else ""
    1956        direction = self.seg("UNPIVOT" if expression.unpivot else "PIVOT")
    1957
    1958        field = self.sql(expression, "field")
    1959
    1960        include_nulls = expression.args.get("include_nulls")
    1961        if include_nulls is not None:
    1962            nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS "
    1963        else:
    1964            nulls = ""
    1965
    1966        default_on_null = self.sql(expression, "default_on_null")
    1967        default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else ""
    1968        return f"{direction}{nulls}({expressions} FOR {field}{default_on_null}){alias}"

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

    1970    def version_sql(self, expression: exp.Version) -> str:
    1971        this = f"FOR {expression.name}"
    1972        kind = expression.text("kind")
    1973        expr = self.sql(expression, "expression")
    1974        return f"{this} {kind} {expr}"

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

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

    1979    def update_sql(self, expression: exp.Update) -> str:
    1980        this = self.sql(expression, "this")
    1981        set_sql = self.expressions(expression, flat=True)
    1982        from_sql = self.sql(expression, "from")
    1983        where_sql = self.sql(expression, "where")
    1984        returning = self.sql(expression, "returning")
    1985        order = self.sql(expression, "order")
    1986        limit = self.sql(expression, "limit")
    1987        if self.RETURNING_END:
    1988            expression_sql = f"{from_sql}{where_sql}{returning}"
    1989        else:
    1990            expression_sql = f"{returning}{from_sql}{where_sql}"
    1991        sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}"
    1992        return self.prepend_ctes(expression, sql)

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

    1994    def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str:
    1995        values_as_table = values_as_table and self.VALUES_AS_TABLE
    1996
    1997        # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example
    1998        if values_as_table or not expression.find_ancestor(exp.From, exp.Join):
    1999            args = self.expressions(expression)
    2000            alias = self.sql(expression, "alias")
    2001            values = f"VALUES{self.seg('')}{args}"
    2002            values = (
    2003                f"({values})"
    2004                if self.WRAP_DERIVED_VALUES and (alias or isinstance(expression.parent, exp.From))
    2005                else values
    2006            )
    2007            return f"{values} AS {alias}" if alias else values
    2008
    2009        # Converts `VALUES...` expression into a series of select unions.
    2010        alias_node = expression.args.get("alias")
    2011        column_names = alias_node and alias_node.columns
    2012
    2013        selects: t.List[exp.Query] = []
    2014
    2015        for i, tup in enumerate(expression.expressions):
    2016            row = tup.expressions
    2017
    2018            if i == 0 and column_names:
    2019                row = [
    2020                    exp.alias_(value, column_name) for value, column_name in zip(row, column_names)
    2021                ]
    2022
    2023            selects.append(exp.Select(expressions=row))
    2024
    2025        if self.pretty:
    2026            # This may result in poor performance for large-cardinality `VALUES` tables, due to
    2027            # the deep nesting of the resulting exp.Unions. If this is a problem, either increase
    2028            # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`.
    2029            query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects)
    2030            return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False))
    2031
    2032        alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else ""
    2033        unions = " UNION ALL ".join(self.sql(select) for select in selects)
    2034        return f"({unions}){alias}"

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

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

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

    2039    def into_sql(self, expression: exp.Into) -> str:
    2040        temporary = " TEMPORARY" if expression.args.get("temporary") else ""
    2041        unlogged = " UNLOGGED" if expression.args.get("unlogged") else ""
    2042        return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"

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

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

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

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

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

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

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

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

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

    2059    def group_sql(self, expression: exp.Group) -> str:
    2060        group_by_all = expression.args.get("all")
    2061        if group_by_all is True:
    2062            modifier = " ALL"
    2063        elif group_by_all is False:
    2064            modifier = " DISTINCT"
    2065        else:
    2066            modifier = ""
    2067
    2068        group_by = self.op_expressions(f"GROUP BY{modifier}", expression)
    2069
    2070        grouping_sets = self.expressions(expression, key="grouping_sets")
    2071        cube = self.expressions(expression, key="cube")
    2072        rollup = self.expressions(expression, key="rollup")
    2073
    2074        groupings = csv(
    2075            self.seg(grouping_sets) if grouping_sets else "",
    2076            self.seg(cube) if cube else "",
    2077            self.seg(rollup) if rollup else "",
    2078            self.seg("WITH TOTALS") if expression.args.get("totals") else "",
    2079            sep=self.GROUPINGS_SEP,
    2080        )
    2081
    2082        if (
    2083            expression.expressions
    2084            and groupings
    2085            and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP")
    2086        ):
    2087            group_by = f"{group_by}{self.GROUPINGS_SEP}"
    2088
    2089        return f"{group_by}{groupings}"

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

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

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

    2095    def connect_sql(self, expression: exp.Connect) -> str:
    2096        start = self.sql(expression, "start")
    2097        start = self.seg(f"START WITH {start}") if start else ""
    2098        nocycle = " NOCYCLE" if expression.args.get("nocycle") else ""
    2099        connect = self.sql(expression, "connect")
    2100        connect = self.seg(f"CONNECT BY{nocycle} {connect}")
    2101        return start + connect

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

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

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

    2106    def join_sql(self, expression: exp.Join) -> str:
    2107        if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"):
    2108            side = None
    2109        else:
    2110            side = expression.side
    2111
    2112        op_sql = " ".join(
    2113            op
    2114            for op in (
    2115                expression.method,
    2116                "GLOBAL" if expression.args.get("global") else None,
    2117                side,
    2118                expression.kind,
    2119                expression.hint if self.JOIN_HINTS else None,
    2120            )
    2121            if op
    2122        )
    2123        match_cond = self.sql(expression, "match_condition")
    2124        match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else ""
    2125        on_sql = self.sql(expression, "on")
    2126        using = expression.args.get("using")
    2127
    2128        if not on_sql and using:
    2129            on_sql = csv(*(self.sql(column) for column in using))
    2130
    2131        this = expression.this
    2132        this_sql = self.sql(this)
    2133
    2134        if on_sql:
    2135            on_sql = self.indent(on_sql, skip_first=True)
    2136            space = self.seg(" " * self.pad) if self.pretty else " "
    2137            if using:
    2138                on_sql = f"{space}USING ({on_sql})"
    2139            else:
    2140                on_sql = f"{space}ON {on_sql}"
    2141        elif not op_sql:
    2142            if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None:
    2143                return f" {this_sql}"
    2144
    2145            return f", {this_sql}"
    2146
    2147        if op_sql != "STRAIGHT_JOIN":
    2148            op_sql = f"{op_sql} JOIN" if op_sql else "JOIN"
    2149
    2150        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

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

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

    2157    def lateral_op(self, expression: exp.Lateral) -> str:
    2158        cross_apply = expression.args.get("cross_apply")
    2159
    2160        # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/
    2161        if cross_apply is True:
    2162            op = "INNER JOIN "
    2163        elif cross_apply is False:
    2164            op = "LEFT JOIN "
    2165        else:
    2166            op = ""
    2167
    2168        return f"{op}LATERAL"

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

    2170    def lateral_sql(self, expression: exp.Lateral) -> str:
    2171        this = self.sql(expression, "this")
    2172
    2173        if expression.args.get("view"):
    2174            alias = expression.args["alias"]
    2175            columns = self.expressions(alias, key="columns", flat=True)
    2176            table = f" {alias.name}" if alias.name else ""
    2177            columns = f" AS {columns}" if columns else ""
    2178            op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}")
    2179            return f"{op_sql}{self.sep()}{this}{table}{columns}"
    2180
    2181        alias = self.sql(expression, "alias")
    2182        alias = f" AS {alias}" if alias else ""
    2183        return f"{self.lateral_op(expression)} {this}{alias}"

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

    2185    def limit_sql(self, expression: exp.Limit, top: bool = False) -> str:
    2186        this = self.sql(expression, "this")
    2187
    2188        args = [
    2189            self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e
    2190            for e in (expression.args.get(k) for k in ("offset", "expression"))
    2191            if e
    2192        ]
    2193
    2194        args_sql = ", ".join(self.sql(e) for e in args)
    2195        args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql
    2196        expressions = self.expressions(expression, flat=True)
    2197        expressions = f" BY {expressions}" if expressions else ""
    2198
    2199        return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{expressions}"

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

    2201    def offset_sql(self, expression: exp.Offset) -> str:
    2202        this = self.sql(expression, "this")
    2203        value = expression.expression
    2204        value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value
    2205        expressions = self.expressions(expression, flat=True)
    2206        expressions = f" BY {expressions}" if expressions else ""
    2207        return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"

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

    2209    def setitem_sql(self, expression: exp.SetItem) -> str:
    2210        kind = self.sql(expression, "kind")
    2211        kind = f"{kind} " if kind else ""
    2212        this = self.sql(expression, "this")
    2213        expressions = self.expressions(expression)
    2214        collate = self.sql(expression, "collate")
    2215        collate = f" COLLATE {collate}" if collate else ""
    2216        global_ = "GLOBAL " if expression.args.get("global") else ""
    2217        return f"{global_}{kind}{this}{expressions}{collate}"

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

    2219    def set_sql(self, expression: exp.Set) -> str:
    2220        expressions = (
    2221            f" {self.expressions(expression, flat=True)}" if expression.expressions else ""
    2222        )
    2223        tag = " TAG" if expression.args.get("tag") else ""
    2224        return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"

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

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

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

    2229    def lock_sql(self, expression: exp.Lock) -> str:
    2230        if not self.LOCKING_READS_SUPPORTED:
    2231            self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported")
    2232            return ""
    2233
    2234        lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE"
    2235        expressions = self.expressions(expression, flat=True)
    2236        expressions = f" OF {expressions}" if expressions else ""
    2237        wait = expression.args.get("wait")
    2238
    2239        if wait is not None:
    2240            if isinstance(wait, exp.Literal):
    2241                wait = f" WAIT {self.sql(wait)}"
    2242            else:
    2243                wait = " NOWAIT" if wait else " SKIP LOCKED"
    2244
    2245        return f"{lock_type}{expressions}{wait or ''}"

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

    2247    def literal_sql(self, expression: exp.Literal) -> str:
    2248        text = expression.this or ""
    2249        if expression.is_string:
    2250            text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}"
    2251        return text

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

    2253    def escape_str(self, text: str, escape_backslash: bool = True) -> str:
    2254        if self.dialect.ESCAPED_SEQUENCES:
    2255            to_escaped = self.dialect.ESCAPED_SEQUENCES
    2256            text = "".join(
    2257                to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text
    2258            )
    2259
    2260        return self._replace_line_breaks(text).replace(
    2261            self.dialect.QUOTE_END, self._escaped_quote_end
    2262        )

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

    2264    def loaddata_sql(self, expression: exp.LoadData) -> str:
    2265        local = " LOCAL" if expression.args.get("local") else ""
    2266        inpath = f" INPATH {self.sql(expression, 'inpath')}"
    2267        overwrite = " OVERWRITE" if expression.args.get("overwrite") else ""
    2268        this = f" INTO TABLE {self.sql(expression, 'this')}"
    2269        partition = self.sql(expression, "partition")
    2270        partition = f" {partition}" if partition else ""
    2271        input_format = self.sql(expression, "input_format")
    2272        input_format = f" INPUTFORMAT {input_format}" if input_format else ""
    2273        serde = self.sql(expression, "serde")
    2274        serde = f" SERDE {serde}" if serde else ""
    2275        return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"

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

    2277    def null_sql(self, *_) -> str:
    2278        return "NULL"

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

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

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

    2283    def order_sql(self, expression: exp.Order, flat: bool = False) -> str:
    2284        this = self.sql(expression, "this")
    2285        this = f"{this} " if this else this
    2286        siblings = "SIBLINGS " if expression.args.get("siblings") else ""
    2287        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

    2289    def withfill_sql(self, expression: exp.WithFill) -> str:
    2290        from_sql = self.sql(expression, "from")
    2291        from_sql = f" FROM {from_sql}" if from_sql else ""
    2292        to_sql = self.sql(expression, "to")
    2293        to_sql = f" TO {to_sql}" if to_sql else ""
    2294        step_sql = self.sql(expression, "step")
    2295        step_sql = f" STEP {step_sql}" if step_sql else ""
    2296        interpolated_values = [
    2297            f"{self.sql(named_expression, 'alias')} AS {self.sql(named_expression, 'this')}"
    2298            for named_expression in expression.args.get("interpolate") or []
    2299        ]
    2300        interpolate = (
    2301            f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else ""
    2302        )
    2303        return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}"

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

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

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

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

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

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

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

    2314    def ordered_sql(self, expression: exp.Ordered) -> str:
    2315        desc = expression.args.get("desc")
    2316        asc = not desc
    2317
    2318        nulls_first = expression.args.get("nulls_first")
    2319        nulls_last = not nulls_first
    2320        nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large"
    2321        nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small"
    2322        nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last"
    2323
    2324        this = self.sql(expression, "this")
    2325
    2326        sort_order = " DESC" if desc else (" ASC" if desc is False else "")
    2327        nulls_sort_change = ""
    2328        if nulls_first and (
    2329            (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last
    2330        ):
    2331            nulls_sort_change = " NULLS FIRST"
    2332        elif (
    2333            nulls_last
    2334            and ((asc and nulls_are_small) or (desc and nulls_are_large))
    2335            and not nulls_are_last
    2336        ):
    2337            nulls_sort_change = " NULLS LAST"
    2338
    2339        # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it
    2340        if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED:
    2341            window = expression.find_ancestor(exp.Window, exp.Select)
    2342            if isinstance(window, exp.Window) and window.args.get("spec"):
    2343                self.unsupported(
    2344                    f"'{nulls_sort_change.strip()}' translation not supported in window functions"
    2345                )
    2346                nulls_sort_change = ""
    2347            elif self.NULL_ORDERING_SUPPORTED is None:
    2348                if expression.this.is_int:
    2349                    self.unsupported(
    2350                        f"'{nulls_sort_change.strip()}' translation not supported with positional ordering"
    2351                    )
    2352                elif not isinstance(expression.this, exp.Rand):
    2353                    null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else ""
    2354                    this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}"
    2355                nulls_sort_change = ""
    2356
    2357        with_fill = self.sql(expression, "with_fill")
    2358        with_fill = f" {with_fill}" if with_fill else ""
    2359
    2360        return f"{this}{sort_order}{nulls_sort_change}{with_fill}"

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

    2362    def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str:
    2363        window_frame = self.sql(expression, "window_frame")
    2364        window_frame = f"{window_frame} " if window_frame else ""
    2365
    2366        this = self.sql(expression, "this")
    2367
    2368        return f"{window_frame}{this}"

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

    2370    def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str:
    2371        partition = self.partition_by_sql(expression)
    2372        order = self.sql(expression, "order")
    2373        measures = self.expressions(expression, key="measures")
    2374        measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else ""
    2375        rows = self.sql(expression, "rows")
    2376        rows = self.seg(rows) if rows else ""
    2377        after = self.sql(expression, "after")
    2378        after = self.seg(after) if after else ""
    2379        pattern = self.sql(expression, "pattern")
    2380        pattern = self.seg(f"PATTERN ({pattern})") if pattern else ""
    2381        definition_sqls = [
    2382            f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}"
    2383            for definition in expression.args.get("define", [])
    2384        ]
    2385        definitions = self.expressions(sqls=definition_sqls)
    2386        define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else ""
    2387        body = "".join(
    2388            (
    2389                partition,
    2390                order,
    2391                measures,
    2392                rows,
    2393                after,
    2394                pattern,
    2395                define,
    2396            )
    2397        )
    2398        alias = self.sql(expression, "alias")
    2399        alias = f" {alias}" if alias else ""
    2400        return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"

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

    2402    def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str:
    2403        limit = expression.args.get("limit")
    2404
    2405        if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch):
    2406            limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count")))
    2407        elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit):
    2408            limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression))
    2409
    2410        return csv(
    2411            *sqls,
    2412            *[self.sql(join) for join in expression.args.get("joins") or []],
    2413            self.sql(expression, "connect"),
    2414            self.sql(expression, "match"),
    2415            *[self.sql(lateral) for lateral in expression.args.get("laterals") or []],
    2416            self.sql(expression, "prewhere"),
    2417            self.sql(expression, "where"),
    2418            self.sql(expression, "group"),
    2419            self.sql(expression, "having"),
    2420            *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()],
    2421            self.sql(expression, "order"),
    2422            *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit),
    2423            *self.after_limit_modifiers(expression),
    2424            self.options_modifier(expression),
    2425            sep="",
    2426        )

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

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

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

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

    2435    def offset_limit_modifiers(
    2436        self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit]
    2437    ) -> t.List[str]:
    2438        return [
    2439            self.sql(expression, "offset") if fetch else self.sql(limit),
    2440            self.sql(limit) if fetch else self.sql(expression, "offset"),
    2441        ]

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

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

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

    2448    def select_sql(self, expression: exp.Select) -> str:
    2449        into = expression.args.get("into")
    2450        if not self.SUPPORTS_SELECT_INTO and into:
    2451            into.pop()
    2452
    2453        hint = self.sql(expression, "hint")
    2454        distinct = self.sql(expression, "distinct")
    2455        distinct = f" {distinct}" if distinct else ""
    2456        kind = self.sql(expression, "kind")
    2457
    2458        limit = expression.args.get("limit")
    2459        if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP:
    2460            top = self.limit_sql(limit, top=True)
    2461            limit.pop()
    2462        else:
    2463            top = ""
    2464
    2465        expressions = self.expressions(expression)
    2466
    2467        if kind:
    2468            if kind in self.SELECT_KINDS:
    2469                kind = f" AS {kind}"
    2470            else:
    2471                if kind == "STRUCT":
    2472                    expressions = self.expressions(
    2473                        sqls=[
    2474                            self.sql(
    2475                                exp.Struct(
    2476                                    expressions=[
    2477                                        exp.PropertyEQ(this=e.args.get("alias"), expression=e.this)
    2478                                        if isinstance(e, exp.Alias)
    2479                                        else e
    2480                                        for e in expression.expressions
    2481                                    ]
    2482                                )
    2483                            )
    2484                        ]
    2485                    )
    2486                kind = ""
    2487
    2488        # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata
    2489        # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first.
    2490        top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}"
    2491        expressions = f"{self.sep()}{expressions}" if expressions else expressions
    2492        sql = self.query_modifiers(
    2493            expression,
    2494            f"SELECT{top_distinct}{kind}{expressions}",
    2495            self.sql(expression, "into", comment=False),
    2496            self.sql(expression, "from", comment=False),
    2497        )
    2498
    2499        sql = self.prepend_ctes(expression, sql)
    2500
    2501        if not self.SUPPORTS_SELECT_INTO and into:
    2502            if into.args.get("temporary"):
    2503                table_kind = " TEMPORARY"
    2504            elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"):
    2505                table_kind = " UNLOGGED"
    2506            else:
    2507                table_kind = ""
    2508            sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}"
    2509
    2510        return sql

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

    2512    def schema_sql(self, expression: exp.Schema) -> str:
    2513        this = self.sql(expression, "this")
    2514        sql = self.schema_columns_sql(expression)
    2515        return f"{this} {sql}" if this and sql else this or sql

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

    2517    def schema_columns_sql(self, expression: exp.Schema) -> str:
    2518        if expression.expressions:
    2519            return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}"
    2520        return ""

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

    2522    def star_sql(self, expression: exp.Star) -> str:
    2523        except_ = self.expressions(expression, key="except", flat=True)
    2524        except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else ""
    2525        replace = self.expressions(expression, key="replace", flat=True)
    2526        replace = f"{self.seg('REPLACE')} ({replace})" if replace else ""
    2527        rename = self.expressions(expression, key="rename", flat=True)
    2528        rename = f"{self.seg('RENAME')} ({rename})" if rename else ""
    2529        return f"*{except_}{replace}{rename}"

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

    2531    def parameter_sql(self, expression: exp.Parameter) -> str:
    2532        this = self.sql(expression, "this")
    2533        return f"{self.PARAMETER_TOKEN}{this}"

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

    2535    def sessionparameter_sql(self, expression: exp.SessionParameter) -> str:
    2536        this = self.sql(expression, "this")
    2537        kind = expression.text("kind")
    2538        if kind:
    2539            kind = f"{kind}."
    2540        return f"@@{kind}{this}"

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

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

    2545    def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str:
    2546        alias = self.sql(expression, "alias")
    2547        alias = f"{sep}{alias}" if alias else ""
    2548        sample = self.sql(expression, "sample")
    2549        if self.dialect.ALIAS_POST_TABLESAMPLE and sample:
    2550            alias = f"{sample}{alias}"
    2551
    2552            # Set to None so it's not generated again by self.query_modifiers()
    2553            expression.set("sample", None)
    2554
    2555        pivots = self.expressions(expression, key="pivots", sep="", flat=True)
    2556        sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots)
    2557        return self.prepend_ctes(expression, sql)

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

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

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

    2563    def unnest_sql(self, expression: exp.Unnest) -> str:
    2564        args = self.expressions(expression, flat=True)
    2565
    2566        alias = expression.args.get("alias")
    2567        offset = expression.args.get("offset")
    2568
    2569        if self.UNNEST_WITH_ORDINALITY:
    2570            if alias and isinstance(offset, exp.Expression):
    2571                alias.append("columns", offset)
    2572
    2573        if alias and self.dialect.UNNEST_COLUMN_ONLY:
    2574            columns = alias.columns
    2575            alias = self.sql(columns[0]) if columns else ""
    2576        else:
    2577            alias = self.sql(alias)
    2578
    2579        alias = f" AS {alias}" if alias else alias
    2580        if self.UNNEST_WITH_ORDINALITY:
    2581            suffix = f" WITH ORDINALITY{alias}" if offset else alias
    2582        else:
    2583            if isinstance(offset, exp.Expression):
    2584                suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}"
    2585            elif offset:
    2586                suffix = f"{alias} WITH OFFSET"
    2587            else:
    2588                suffix = alias
    2589
    2590        return f"UNNEST({args}){suffix}"

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

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

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

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

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

    2599    def window_sql(self, expression: exp.Window) -> str:
    2600        this = self.sql(expression, "this")
    2601        partition = self.partition_by_sql(expression)
    2602        order = expression.args.get("order")
    2603        order = self.order_sql(order, flat=True) if order else ""
    2604        spec = self.sql(expression, "spec")
    2605        alias = self.sql(expression, "alias")
    2606        over = self.sql(expression, "over") or "OVER"
    2607
    2608        this = f"{this} {'AS' if expression.arg_key == 'windows' else over}"
    2609
    2610        first = expression.args.get("first")
    2611        if first is None:
    2612            first = ""
    2613        else:
    2614            first = "FIRST" if first else "LAST"
    2615
    2616        if not partition and not order and not spec and alias:
    2617            return f"{this} {alias}"
    2618
    2619        args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg)
    2620        return f"{this} ({args})"

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

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

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

    2626    def windowspec_sql(self, expression: exp.WindowSpec) -> str:
    2627        kind = self.sql(expression, "kind")
    2628        start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ")
    2629        end = (
    2630            csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ")
    2631            or "CURRENT ROW"
    2632        )
    2633        return f"{kind} BETWEEN {start} AND {end}"

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

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

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

    2640    def between_sql(self, expression: exp.Between) -> str:
    2641        this = self.sql(expression, "this")
    2642        low = self.sql(expression, "low")
    2643        high = self.sql(expression, "high")
    2644        return f"{this} BETWEEN {low} AND {high}"

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

    2646    def bracket_offset_expressions(self, expression: exp.Bracket) -> t.List[exp.Expression]:
    2647        return apply_index_offset(
    2648            expression.this,
    2649            expression.expressions,
    2650            self.dialect.INDEX_OFFSET - expression.args.get("offset", 0),
    2651        )

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

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

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

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

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

    2661    def any_sql(self, expression: exp.Any) -> str:
    2662        this = self.sql(expression, "this")
    2663        if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)):
    2664            if isinstance(expression.this, exp.UNWRAPPED_QUERIES):
    2665                this = self.wrap(this)
    2666            return f"ANY{this}"
    2667        return f"ANY {this}"

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

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

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

    2672    def case_sql(self, expression: exp.Case) -> str:
    2673        this = self.sql(expression, "this")
    2674        statements = [f"CASE {this}" if this else "CASE"]
    2675
    2676        for e in expression.args["ifs"]:
    2677            statements.append(f"WHEN {self.sql(e, 'this')}")
    2678            statements.append(f"THEN {self.sql(e, 'true')}")
    2679
    2680        default = self.sql(expression, "default")
    2681
    2682        if default:
    2683            statements.append(f"ELSE {default}")
    2684
    2685        statements.append("END")
    2686
    2687        if self.pretty and self.too_wide(statements):
    2688            return self.indent("\n".join(statements), skip_first=True, skip_last=True)
    2689
    2690        return " ".join(statements)

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

    2692    def constraint_sql(self, expression: exp.Constraint) -> str:
    2693        this = self.sql(expression, "this")
    2694        expressions = self.expressions(expression, flat=True)
    2695        return f"CONSTRAINT {this} {expressions}"

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

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

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

    2702    def extract_sql(self, expression: exp.Extract) -> str:
    2703        this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name
    2704        expression_sql = self.sql(expression, "expression")
    2705        return f"EXTRACT({this} FROM {expression_sql})"

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

    2707    def trim_sql(self, expression: exp.Trim) -> str:
    2708        trim_type = self.sql(expression, "position")
    2709
    2710        if trim_type == "LEADING":
    2711            func_name = "LTRIM"
    2712        elif trim_type == "TRAILING":
    2713            func_name = "RTRIM"
    2714        else:
    2715            func_name = "TRIM"
    2716
    2717        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

    2719    def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]:
    2720        args = expression.expressions
    2721        if isinstance(expression, exp.ConcatWs):
    2722            args = args[1:]  # Skip the delimiter
    2723
    2724        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    2725            args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args]
    2726
    2727        if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"):
    2728            args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args]
    2729
    2730        return args

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

    2732    def concat_sql(self, expression: exp.Concat) -> str:
    2733        expressions = self.convert_concat_args(expression)
    2734
    2735        # Some dialects don't allow a single-argument CONCAT call
    2736        if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1:
    2737            return self.sql(expressions[0])
    2738
    2739        return self.func("CONCAT", *expressions)

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

    2741    def concatws_sql(self, expression: exp.ConcatWs) -> str:
    2742        return self.func(
    2743            "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression)
    2744        )

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

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

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

    2750    def foreignkey_sql(self, expression: exp.ForeignKey) -> str:
    2751        expressions = self.expressions(expression, flat=True)
    2752        reference = self.sql(expression, "reference")
    2753        reference = f" {reference}" if reference else ""
    2754        delete = self.sql(expression, "delete")
    2755        delete = f" ON DELETE {delete}" if delete else ""
    2756        update = self.sql(expression, "update")
    2757        update = f" ON UPDATE {update}" if update else ""
    2758        return f"FOREIGN KEY ({expressions}){reference}{delete}{update}"

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

    2760    def primarykey_sql(self, expression: exp.ForeignKey) -> str:
    2761        expressions = self.expressions(expression, flat=True)
    2762        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2763        options = f" {options}" if options else ""
    2764        return f"PRIMARY KEY ({expressions}){options}"

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

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

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

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

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

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

    2777    def jsonpath_sql(self, expression: exp.JSONPath) -> str:
    2778        path = self.expressions(expression, sep="", flat=True).lstrip(".")
    2779
    2780        if expression.args.get("escape"):
    2781            path = self.escape_str(path)
    2782
    2783        if self.QUOTE_JSON_PATH:
    2784            path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}"
    2785
    2786        return path

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

    2788    def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str:
    2789        if isinstance(expression, exp.JSONPathPart):
    2790            transform = self.TRANSFORMS.get(expression.__class__)
    2791            if not callable(transform):
    2792                self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}")
    2793                return ""
    2794
    2795            return transform(self, expression)
    2796
    2797        if isinstance(expression, int):
    2798            return str(expression)
    2799
    2800        if self.JSON_PATH_SINGLE_QUOTE_ESCAPE:
    2801            escaped = expression.replace("'", "\\'")
    2802            escaped = f"\\'{expression}\\'"
    2803        else:
    2804            escaped = expression.replace('"', '\\"')
    2805            escaped = f'"{escaped}"'
    2806
    2807        return escaped

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

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

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

    2812    def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str:
    2813        null_handling = expression.args.get("null_handling")
    2814        null_handling = f" {null_handling}" if null_handling else ""
    2815
    2816        unique_keys = expression.args.get("unique_keys")
    2817        if unique_keys is not None:
    2818            unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS"
    2819        else:
    2820            unique_keys = ""
    2821
    2822        return_type = self.sql(expression, "return_type")
    2823        return_type = f" RETURNING {return_type}" if return_type else ""
    2824        encoding = self.sql(expression, "encoding")
    2825        encoding = f" ENCODING {encoding}" if encoding else ""
    2826
    2827        return self.func(
    2828            "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG",
    2829            *expression.expressions,
    2830            suffix=f"{null_handling}{unique_keys}{return_type}{encoding})",
    2831        )

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

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

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

    2836    def jsonarray_sql(self, expression: exp.JSONArray) -> str:
    2837        null_handling = expression.args.get("null_handling")
    2838        null_handling = f" {null_handling}" if null_handling else ""
    2839        return_type = self.sql(expression, "return_type")
    2840        return_type = f" RETURNING {return_type}" if return_type else ""
    2841        strict = " STRICT" if expression.args.get("strict") else ""
    2842        return self.func(
    2843            "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})"
    2844        )

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

    2846    def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str:
    2847        this = self.sql(expression, "this")
    2848        order = self.sql(expression, "order")
    2849        null_handling = expression.args.get("null_handling")
    2850        null_handling = f" {null_handling}" if null_handling else ""
    2851        return_type = self.sql(expression, "return_type")
    2852        return_type = f" RETURNING {return_type}" if return_type else ""
    2853        strict = " STRICT" if expression.args.get("strict") else ""
    2854        return self.func(
    2855            "JSON_ARRAYAGG",
    2856            this,
    2857            suffix=f"{order}{null_handling}{return_type}{strict})",
    2858        )

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

    2860    def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str:
    2861        path = self.sql(expression, "path")
    2862        path = f" PATH {path}" if path else ""
    2863        nested_schema = self.sql(expression, "nested_schema")
    2864
    2865        if nested_schema:
    2866            return f"NESTED{path} {nested_schema}"
    2867
    2868        this = self.sql(expression, "this")
    2869        kind = self.sql(expression, "kind")
    2870        kind = f" {kind}" if kind else ""
    2871        return f"{this}{kind}{path}"

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

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

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

    2876    def jsontable_sql(self, expression: exp.JSONTable) -> str:
    2877        this = self.sql(expression, "this")
    2878        path = self.sql(expression, "path")
    2879        path = f", {path}" if path else ""
    2880        error_handling = expression.args.get("error_handling")
    2881        error_handling = f" {error_handling}" if error_handling else ""
    2882        empty_handling = expression.args.get("empty_handling")
    2883        empty_handling = f" {empty_handling}" if empty_handling else ""
    2884        schema = self.sql(expression, "schema")
    2885        return self.func(
    2886            "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})"
    2887        )

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

    2889    def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str:
    2890        this = self.sql(expression, "this")
    2891        kind = self.sql(expression, "kind")
    2892        path = self.sql(expression, "path")
    2893        path = f" {path}" if path else ""
    2894        as_json = " AS JSON" if expression.args.get("as_json") else ""
    2895        return f"{this} {kind}{path}{as_json}"

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

    2897    def openjson_sql(self, expression: exp.OpenJSON) -> str:
    2898        this = self.sql(expression, "this")
    2899        path = self.sql(expression, "path")
    2900        path = f", {path}" if path else ""
    2901        expressions = self.expressions(expression)
    2902        with_ = (
    2903            f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}"
    2904            if expressions
    2905            else ""
    2906        )
    2907        return f"OPENJSON({this}{path}){with_}"

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

    2909    def in_sql(self, expression: exp.In) -> str:
    2910        query = expression.args.get("query")
    2911        unnest = expression.args.get("unnest")
    2912        field = expression.args.get("field")
    2913        is_global = " GLOBAL" if expression.args.get("is_global") else ""
    2914
    2915        if query:
    2916            in_sql = self.sql(query)
    2917        elif unnest:
    2918            in_sql = self.in_unnest_op(unnest)
    2919        elif field:
    2920            in_sql = self.sql(field)
    2921        else:
    2922            in_sql = f"({self.expressions(expression, flat=True)})"
    2923
    2924        return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"

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

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

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

    2929    def interval_sql(self, expression: exp.Interval) -> str:
    2930        unit = self.sql(expression, "unit")
    2931        if not self.INTERVAL_ALLOWS_PLURAL_FORM:
    2932            unit = self.TIME_PART_SINGULARS.get(unit, unit)
    2933        unit = f" {unit}" if unit else ""
    2934
    2935        if self.SINGLE_STRING_INTERVAL:
    2936            this = expression.this.name if expression.this else ""
    2937            return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}"
    2938
    2939        this = self.sql(expression, "this")
    2940        if this:
    2941            unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES)
    2942            this = f" {this}" if unwrapped else f" ({this})"
    2943
    2944        return f"INTERVAL{this}{unit}"

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

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

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

    2949    def reference_sql(self, expression: exp.Reference) -> str:
    2950        this = self.sql(expression, "this")
    2951        expressions = self.expressions(expression, flat=True)
    2952        expressions = f"({expressions})" if expressions else ""
    2953        options = self.expressions(expression, key="options", flat=True, sep=" ")
    2954        options = f" {options}" if options else ""
    2955        return f"REFERENCES {this}{expressions}{options}"

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

    2957    def anonymous_sql(self, expression: exp.Anonymous) -> str:
    2958        # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive
    2959        parent = expression.parent
    2960        is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression
    2961        return self.func(
    2962            self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified
    2963        )

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

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

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

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

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

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

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

    2978    def alias_sql(self, expression: exp.Alias) -> str:
    2979        alias = self.sql(expression, "alias")
    2980        alias = f" AS {alias}" if alias else ""
    2981        return f"{self.sql(expression, 'this')}{alias}"

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

    2983    def pivotalias_sql(self, expression: exp.PivotAlias) -> str:
    2984        alias = expression.args["alias"]
    2985
    2986        identifier_alias = isinstance(alias, exp.Identifier)
    2987        literal_alias = isinstance(alias, exp.Literal)
    2988
    2989        if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    2990            alias.replace(exp.Literal.string(alias.output_name))
    2991        elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS:
    2992            alias.replace(exp.to_identifier(alias.output_name))
    2993
    2994        return self.alias_sql(expression)

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

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

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

    2999    def atindex_sql(self, expression: exp.AtTimeZone) -> str:
    3000        this = self.sql(expression, "this")
    3001        index = self.sql(expression, "expression")
    3002        return f"{this} AT {index}"

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

    3004    def attimezone_sql(self, expression: exp.AtTimeZone) -> str:
    3005        this = self.sql(expression, "this")
    3006        zone = self.sql(expression, "zone")
    3007        return f"{this} AT TIME ZONE {zone}"

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

    3009    def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str:
    3010        this = self.sql(expression, "this")
    3011        zone = self.sql(expression, "zone")
    3012        return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'"

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

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

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

    3017    def and_sql(
    3018        self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None
    3019    ) -> str:
    3020        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

    3022    def or_sql(
    3023        self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None
    3024    ) -> str:
    3025        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

    3027    def xor_sql(
    3028        self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None
    3029    ) -> str:
    3030        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

    3032    def connector_sql(
    3033        self,
    3034        expression: exp.Connector,
    3035        op: str,
    3036        stack: t.Optional[t.List[str | exp.Expression]] = None,
    3037    ) -> str:
    3038        if stack is not None:
    3039            if expression.expressions:
    3040                stack.append(self.expressions(expression, sep=f" {op} "))
    3041            else:
    3042                stack.append(expression.right)
    3043                if expression.comments and self.comments:
    3044                    for comment in expression.comments:
    3045                        if comment:
    3046                            op += f" /*{self.pad_comment(comment)}*/"
    3047                stack.extend((op, expression.left))
    3048            return op
    3049
    3050        stack = [expression]
    3051        sqls: t.List[str] = []
    3052        ops = set()
    3053
    3054        while stack:
    3055            node = stack.pop()
    3056            if isinstance(node, exp.Connector):
    3057                ops.add(getattr(self, f"{node.key}_sql")(node, stack))
    3058            else:
    3059                sql = self.sql(node)
    3060                if sqls and sqls[-1] in ops:
    3061                    sqls[-1] += f" {sql}"
    3062                else:
    3063                    sqls.append(sql)
    3064
    3065        sep = "\n" if self.pretty and self.too_wide(sqls) else " "
    3066        return sep.join(sqls)

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

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

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

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

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

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

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

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

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

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

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

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

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

    3086    def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:
    3087        format_sql = self.sql(expression, "format")
    3088        format_sql = f" FORMAT {format_sql}" if format_sql else ""
    3089        to_sql = self.sql(expression, "to")
    3090        to_sql = f" {to_sql}" if to_sql else ""
    3091        action = self.sql(expression, "action")
    3092        action = f" {action}" if action else ""
    3093        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

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

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

    3099    def collate_sql(self, expression: exp.Collate) -> str:
    3100        if self.COLLATE_IS_FUNC:
    3101            return self.function_fallback_sql(expression)
    3102        return self.binary(expression, "COLLATE")

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

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

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

    3107    def comment_sql(self, expression: exp.Comment) -> str:
    3108        this = self.sql(expression, "this")
    3109        kind = expression.args["kind"]
    3110        materialized = " MATERIALIZED" if expression.args.get("materialized") else ""
    3111        exists_sql = " IF EXISTS " if expression.args.get("exists") else " "
    3112        expression_sql = self.sql(expression, "expression")
    3113        return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"

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

    3115    def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str:
    3116        this = self.sql(expression, "this")
    3117        delete = " DELETE" if expression.args.get("delete") else ""
    3118        recompress = self.sql(expression, "recompress")
    3119        recompress = f" RECOMPRESS {recompress}" if recompress else ""
    3120        to_disk = self.sql(expression, "to_disk")
    3121        to_disk = f" TO DISK {to_disk}" if to_disk else ""
    3122        to_volume = self.sql(expression, "to_volume")
    3123        to_volume = f" TO VOLUME {to_volume}" if to_volume else ""
    3124        return f"{this}{delete}{recompress}{to_disk}{to_volume}"

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

    3126    def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str:
    3127        where = self.sql(expression, "where")
    3128        group = self.sql(expression, "group")
    3129        aggregates = self.expressions(expression, key="aggregates")
    3130        aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else ""
    3131
    3132        if not (where or group or aggregates) and len(expression.expressions) == 1:
    3133            return f"TTL {self.expressions(expression, flat=True)}"
    3134
    3135        return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"

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

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

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

    3140    def commit_sql(self, expression: exp.Commit) -> str:
    3141        chain = expression.args.get("chain")
    3142        if chain is not None:
    3143            chain = " AND CHAIN" if chain else " AND NO CHAIN"
    3144
    3145        return f"COMMIT{chain or ''}"

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

    3147    def rollback_sql(self, expression: exp.Rollback) -> str:
    3148        savepoint = expression.args.get("savepoint")
    3149        savepoint = f" TO {savepoint}" if savepoint else ""
    3150        return f"ROLLBACK{savepoint}"

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

    3152    def altercolumn_sql(self, expression: exp.AlterColumn) -> str:
    3153        this = self.sql(expression, "this")
    3154
    3155        dtype = self.sql(expression, "dtype")
    3156        if dtype:
    3157            collate = self.sql(expression, "collate")
    3158            collate = f" COLLATE {collate}" if collate else ""
    3159            using = self.sql(expression, "using")
    3160            using = f" USING {using}" if using else ""
    3161            return f"ALTER COLUMN {this} SET DATA TYPE {dtype}{collate}{using}"
    3162
    3163        default = self.sql(expression, "default")
    3164        if default:
    3165            return f"ALTER COLUMN {this} SET DEFAULT {default}"
    3166
    3167        comment = self.sql(expression, "comment")
    3168        if comment:
    3169            return f"ALTER COLUMN {this} COMMENT {comment}"
    3170
    3171        allow_null = expression.args.get("allow_null")
    3172        drop = expression.args.get("drop")
    3173
    3174        if not drop and not allow_null:
    3175            self.unsupported("Unsupported ALTER COLUMN syntax")
    3176
    3177        if allow_null is not None:
    3178            keyword = "DROP" if drop else "SET"
    3179            return f"ALTER COLUMN {this} {keyword} NOT NULL"
    3180
    3181        return f"ALTER COLUMN {this} DROP DEFAULT"

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

    3183    def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str:
    3184        this = self.sql(expression, "this")
    3185        if not isinstance(expression.this, exp.Var):
    3186            this = f"KEY DISTKEY {this}"
    3187        return f"ALTER DISTSTYLE {this}"

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

    3189    def altersortkey_sql(self, expression: exp.AlterSortKey) -> str:
    3190        compound = " COMPOUND" if expression.args.get("compound") else ""
    3191        this = self.sql(expression, "this")
    3192        expressions = self.expressions(expression, flat=True)
    3193        expressions = f"({expressions})" if expressions else ""
    3194        return f"ALTER{compound} SORTKEY {this or expressions}"

def renametable_sql(self, expression: sqlglot.expressions.RenameTable) -> str: View Source

    3196    def renametable_sql(self, expression: exp.RenameTable) -> str:
    3197        if not self.RENAME_TABLE_WITH_DB:
    3198            # Remove db from tables
    3199            expression = expression.transform(
    3200                lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n
    3201            ).assert_is(exp.RenameTable)
    3202        this = self.sql(expression, "this")
    3203        return f"RENAME TO {this}"

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

    3205    def renamecolumn_sql(self, expression: exp.RenameColumn) -> str:
    3206        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3207        old_column = self.sql(expression, "this")
    3208        new_column = self.sql(expression, "to")
    3209        return f"RENAME COLUMN{exists} {old_column} TO {new_column}"

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

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

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

    3215    def alter_sql(self, expression: exp.Alter) -> str:
    3216        actions = expression.args["actions"]
    3217
    3218        if isinstance(actions[0], exp.ColumnDef):
    3219            actions = self.add_column_sql(expression)
    3220        elif isinstance(actions[0], exp.Schema):
    3221            actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ")
    3222        elif isinstance(actions[0], exp.Delete):
    3223            actions = self.expressions(expression, key="actions", flat=True)
    3224        elif isinstance(actions[0], exp.Query):
    3225            actions = "AS " + self.expressions(expression, key="actions")
    3226        else:
    3227            actions = self.expressions(expression, key="actions", flat=True)
    3228
    3229        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3230        on_cluster = self.sql(expression, "cluster")
    3231        on_cluster = f" {on_cluster}" if on_cluster else ""
    3232        only = " ONLY" if expression.args.get("only") else ""
    3233        options = self.expressions(expression, key="options")
    3234        options = f", {options}" if options else ""
    3235        kind = self.sql(expression, "kind")
    3236        not_valid = " NOT VALID" if expression.args.get("not_valid") else ""
    3237
    3238        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

    3240    def add_column_sql(self, expression: exp.Alter) -> str:
    3241        if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD:
    3242            return self.expressions(
    3243                expression,
    3244                key="actions",
    3245                prefix="ADD COLUMN ",
    3246                skip_first=True,
    3247            )
    3248        return f"ADD {self.expressions(expression, key='actions', flat=True)}"

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

    3250    def droppartition_sql(self, expression: exp.DropPartition) -> str:
    3251        expressions = self.expressions(expression)
    3252        exists = " IF EXISTS " if expression.args.get("exists") else " "
    3253        return f"DROP{exists}{expressions}"

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

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

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

    3258    def distinct_sql(self, expression: exp.Distinct) -> str:
    3259        this = self.expressions(expression, flat=True)
    3260
    3261        if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1:
    3262            case = exp.case()
    3263            for arg in expression.expressions:
    3264                case = case.when(arg.is_(exp.null()), exp.null())
    3265            this = self.sql(case.else_(f"({this})"))
    3266
    3267        this = f" {this}" if this else ""
    3268
    3269        on = self.sql(expression, "on")
    3270        on = f" ON {on}" if on else ""
    3271        return f"DISTINCT{this}{on}"

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

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

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

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

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

    3279    def havingmax_sql(self, expression: exp.HavingMax) -> str:
    3280        this_sql = self.sql(expression, "this")
    3281        expression_sql = self.sql(expression, "expression")
    3282        kind = "MAX" if expression.args.get("max") else "MIN"
    3283        return f"{this_sql} HAVING {kind} {expression_sql}"

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

    3285    def intdiv_sql(self, expression: exp.IntDiv) -> str:
    3286        return self.sql(
    3287            exp.Cast(
    3288                this=exp.Div(this=expression.this, expression=expression.expression),
    3289                to=exp.DataType(this=exp.DataType.Type.INT),
    3290            )
    3291        )

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

    3293    def dpipe_sql(self, expression: exp.DPipe) -> str:
    3294        if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"):
    3295            return self.func(
    3296                "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten())
    3297            )
    3298        return self.binary(expression, "||")

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

    3300    def div_sql(self, expression: exp.Div) -> str:
    3301        l, r = expression.left, expression.right
    3302
    3303        if not self.dialect.SAFE_DIVISION and expression.args.get("safe"):
    3304            r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0)))
    3305
    3306        if self.dialect.TYPED_DIVISION and not expression.args.get("typed"):
    3307            if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES):
    3308                l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE))
    3309
    3310        elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"):
    3311            if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES):
    3312                return self.sql(
    3313                    exp.cast(
    3314                        l / r,
    3315                        to=exp.DataType.Type.BIGINT,
    3316                    )
    3317                )
    3318
    3319        return self.binary(expression, "/")

def overlaps_sql(self, expression: sqlglot.expressions.Overlaps) -> str: View Source

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3354    def is_sql(self, expression: exp.Is) -> str:
    3355        if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean):
    3356            return self.sql(
    3357                expression.this if expression.expression.this else exp.not_(expression.this)
    3358            )
    3359        return self.binary(expression, "IS")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    3400    def try_sql(self, expression: exp.Try) -> str:
    3401        if not self.TRY_SUPPORTED:
    3402            self.unsupported("Unsupported TRY function")
    3403            return self.sql(expression, "this")
    3404
    3405        return self.func("TRY", expression.this)

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

    3407    def log_sql(self, expression: exp.Log) -> str:
    3408        this = expression.this
    3409        expr = expression.expression
    3410
    3411        if self.dialect.LOG_BASE_FIRST is False:
    3412            this, expr = expr, this
    3413        elif self.dialect.LOG_BASE_FIRST is None and expr:
    3414            if this.name in ("2", "10"):
    3415                return self.func(f"LOG{this.name}", expr)
    3416
    3417            self.unsupported(f"Unsupported logarithm with base {self.sql(this)}")
    3418
    3419        return self.func("LOG", this, expr)

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

    3421    def use_sql(self, expression: exp.Use) -> str:
    3422        kind = self.sql(expression, "kind")
    3423        kind = f" {kind}" if kind else ""
    3424        this = self.sql(expression, "this")
    3425        this = f" {this}" if this else ""
    3426        return f"USE{kind}{this}"

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

    3428    def binary(self, expression: exp.Binary, op: str) -> str:
    3429        sqls: t.List[str] = []
    3430        stack: t.List[t.Union[str, exp.Expression]] = [expression]
    3431        binary_type = type(expression)
    3432
    3433        while stack:
    3434            node = stack.pop()
    3435
    3436            if type(node) is binary_type:
    3437                op_func = node.args.get("operator")
    3438                if op_func:
    3439                    op = f"OPERATOR({self.sql(op_func)})"
    3440
    3441                stack.append(node.right)
    3442                stack.append(f" {self.maybe_comment(op, comments=node.comments)} ")
    3443                stack.append(node.left)
    3444            else:
    3445                sqls.append(self.sql(node))
    3446
    3447        return "".join(sqls)

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

    3449    def function_fallback_sql(self, expression: exp.Func) -> str:
    3450        args = []
    3451
    3452        for key in expression.arg_types:
    3453            arg_value = expression.args.get(key)
    3454
    3455            if isinstance(arg_value, list):
    3456                for value in arg_value:
    3457                    args.append(value)
    3458            elif arg_value is not None:
    3459                args.append(arg_value)
    3460
    3461        if self.normalize_functions:
    3462            name = expression.sql_name()
    3463        else:
    3464            name = (expression._meta and expression.meta.get("name")) or expression.sql_name()
    3465
    3466        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

    3468    def func(
    3469        self,
    3470        name: str,
    3471        *args: t.Optional[exp.Expression | str],
    3472        prefix: str = "(",
    3473        suffix: str = ")",
    3474        normalize: bool = True,
    3475    ) -> str:
    3476        name = self.normalize_func(name) if normalize else name
    3477        return f"{name}{prefix}{self.format_args(*args)}{suffix}"

def format_args(self, *args: Union[str, sqlglot.expressions.Expression, NoneType]) -> str: View Source

    3479    def format_args(self, *args: t.Optional[str | exp.Expression]) -> str:
    3480        arg_sqls = tuple(
    3481            self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool)
    3482        )
    3483        if self.pretty and self.too_wide(arg_sqls):
    3484            return self.indent("\n" + ",\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True)
    3485        return ", ".join(arg_sqls)

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

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

    3490    def format_time(
    3491        self,
    3492        expression: exp.Expression,
    3493        inverse_time_mapping: t.Optional[t.Dict[str, str]] = None,
    3494        inverse_time_trie: t.Optional[t.Dict] = None,
    3495    ) -> t.Optional[str]:
    3496        return format_time(
    3497            self.sql(expression, "format"),
    3498            inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING,
    3499            inverse_time_trie or self.dialect.INVERSE_TIME_TRIE,
    3500        )

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

    3502    def expressions(
    3503        self,
    3504        expression: t.Optional[exp.Expression] = None,
    3505        key: t.Optional[str] = None,
    3506        sqls: t.Optional[t.Collection[str | exp.Expression]] = None,
    3507        flat: bool = False,
    3508        indent: bool = True,
    3509        skip_first: bool = False,
    3510        skip_last: bool = False,
    3511        sep: str = ", ",
    3512        prefix: str = "",
    3513        dynamic: bool = False,
    3514        new_line: bool = False,
    3515    ) -> str:
    3516        expressions = expression.args.get(key or "expressions") if expression else sqls
    3517
    3518        if not expressions:
    3519            return ""
    3520
    3521        if flat:
    3522            return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql)
    3523
    3524        num_sqls = len(expressions)
    3525        result_sqls = []
    3526
    3527        for i, e in enumerate(expressions):
    3528            sql = self.sql(e, comment=False)
    3529            if not sql:
    3530                continue
    3531
    3532            comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else ""
    3533
    3534            if self.pretty:
    3535                if self.leading_comma:
    3536                    result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}")
    3537                else:
    3538                    result_sqls.append(
    3539                        f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}"
    3540                    )
    3541            else:
    3542                result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}")
    3543
    3544        if self.pretty and (not dynamic or self.too_wide(result_sqls)):
    3545            if new_line:
    3546                result_sqls.insert(0, "")
    3547                result_sqls.append("")
    3548            result_sql = "\n".join(s.rstrip() for s in result_sqls)
    3549        else:
    3550            result_sql = "".join(result_sqls)
    3551
    3552        return (
    3553            self.indent(result_sql, skip_first=skip_first, skip_last=skip_last)
    3554            if indent
    3555            else result_sql
    3556        )

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

    3558    def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str:
    3559        flat = flat or isinstance(expression.parent, exp.Properties)
    3560        expressions_sql = self.expressions(expression, flat=flat)
    3561        if flat:
    3562            return f"{op} {expressions_sql}"
    3563        return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"

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

    3565    def naked_property(self, expression: exp.Property) -> str:
    3566        property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__)
    3567        if not property_name:
    3568            self.unsupported(f"Unsupported property {expression.__class__.__name__}")
    3569        return f"{property_name} {self.sql(expression, 'this')}"

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

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

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

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

    3577    def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str:
    3578        this = self.sql(expression, "this")
    3579        expressions = self.no_identify(self.expressions, expression)
    3580        expressions = (
    3581            self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}"
    3582        )
    3583        return f"{this}{expressions}"

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

    3585    def joinhint_sql(self, expression: exp.JoinHint) -> str:
    3586        this = self.sql(expression, "this")
    3587        expressions = self.expressions(expression, flat=True)
    3588        return f"{this}({expressions})"

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

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

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

    3593    def when_sql(self, expression: exp.When) -> str:
    3594        matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED"
    3595        source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else ""
    3596        condition = self.sql(expression, "condition")
    3597        condition = f" AND {condition}" if condition else ""
    3598
    3599        then_expression = expression.args.get("then")
    3600        if isinstance(then_expression, exp.Insert):
    3601            this = self.sql(then_expression, "this")
    3602            this = f"INSERT {this}" if this else "INSERT"
    3603            then = self.sql(then_expression, "expression")
    3604            then = f"{this} VALUES {then}" if then else this
    3605        elif isinstance(then_expression, exp.Update):
    3606            if isinstance(then_expression.args.get("expressions"), exp.Star):
    3607                then = f"UPDATE {self.sql(then_expression, 'expressions')}"
    3608            else:
    3609                then = f"UPDATE SET {self.expressions(then_expression, flat=True)}"
    3610        else:
    3611            then = self.sql(then_expression)
    3612        return f"WHEN {matched}{source}{condition} THEN {then}"

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

    3614    def merge_sql(self, expression: exp.Merge) -> str:
    3615        table = expression.this
    3616        table_alias = ""
    3617
    3618        hints = table.args.get("hints")
    3619        if hints and table.alias and isinstance(hints[0], exp.WithTableHint):
    3620            # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias]
    3621            table_alias = f" AS {self.sql(table.args['alias'].pop())}"
    3622
    3623        this = self.sql(table)
    3624        using = f"USING {self.sql(expression, 'using')}"
    3625        on = f"ON {self.sql(expression, 'on')}"
    3626        expressions = self.expressions(expression, sep=" ", indent=False)
    3627        sep = self.sep()
    3628        returning = self.expressions(expression, key="returning", indent=False)
    3629        returning = f"RETURNING {returning}" if returning else ""
    3630
    3631        return self.prepend_ctes(
    3632            expression,
    3633            f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{expressions}{sep}{returning}",
    3634        )

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

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

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

    3640    def tonumber_sql(self, expression: exp.ToNumber) -> str:
    3641        if not self.SUPPORTS_TO_NUMBER:
    3642            self.unsupported("Unsupported TO_NUMBER function")
    3643            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3644
    3645        fmt = expression.args.get("format")
    3646        if not fmt:
    3647            self.unsupported("Conversion format is required for TO_NUMBER")
    3648            return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE))
    3649
    3650        return self.func("TO_NUMBER", expression.this, fmt)

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

    3652    def dictproperty_sql(self, expression: exp.DictProperty) -> str:
    3653        this = self.sql(expression, "this")
    3654        kind = self.sql(expression, "kind")
    3655        settings_sql = self.expressions(expression, key="settings", sep=" ")
    3656        args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()"
    3657        return f"{this}({kind}{args})"

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

    3659    def dictrange_sql(self, expression: exp.DictRange) -> str:
    3660        this = self.sql(expression, "this")
    3661        max = self.sql(expression, "max")
    3662        min = self.sql(expression, "min")
    3663        return f"{this}(MIN {min} MAX {max})"

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

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

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

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

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

    3672    def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str:
    3673        expressions = self.expressions(expression, flat=True)
    3674        expressions = f" {self.wrap(expressions)}" if expressions else ""
    3675        buckets = self.sql(expression, "buckets")
    3676        kind = self.sql(expression, "kind")
    3677        buckets = f" BUCKETS {buckets}" if buckets else ""
    3678        order = self.sql(expression, "order")
    3679        return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}"

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

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

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

    3684    def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str:
    3685        expressions = self.expressions(expression, key="expressions", flat=True)
    3686        sorted_by = self.expressions(expression, key="sorted_by", flat=True)
    3687        sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else ""
    3688        buckets = self.sql(expression, "buckets")
    3689        return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"

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

    3691    def anyvalue_sql(self, expression: exp.AnyValue) -> str:
    3692        this = self.sql(expression, "this")
    3693        having = self.sql(expression, "having")
    3694
    3695        if having:
    3696            this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}"
    3697
    3698        return self.func("ANY_VALUE", this)

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

    3700    def querytransform_sql(self, expression: exp.QueryTransform) -> str:
    3701        transform = self.func("TRANSFORM", *expression.expressions)
    3702        row_format_before = self.sql(expression, "row_format_before")
    3703        row_format_before = f" {row_format_before}" if row_format_before else ""
    3704        record_writer = self.sql(expression, "record_writer")
    3705        record_writer = f" RECORDWRITER {record_writer}" if record_writer else ""
    3706        using = f" USING {self.sql(expression, 'command_script')}"
    3707        schema = self.sql(expression, "schema")
    3708        schema = f" AS {schema}" if schema else ""
    3709        row_format_after = self.sql(expression, "row_format_after")
    3710        row_format_after = f" {row_format_after}" if row_format_after else ""
    3711        record_reader = self.sql(expression, "record_reader")
    3712        record_reader = f" RECORDREADER {record_reader}" if record_reader else ""
    3713        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

    3715    def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str:
    3716        key_block_size = self.sql(expression, "key_block_size")
    3717        if key_block_size:
    3718            return f"KEY_BLOCK_SIZE = {key_block_size}"
    3719
    3720        using = self.sql(expression, "using")
    3721        if using:
    3722            return f"USING {using}"
    3723
    3724        parser = self.sql(expression, "parser")
    3725        if parser:
    3726            return f"WITH PARSER {parser}"
    3727
    3728        comment = self.sql(expression, "comment")
    3729        if comment:
    3730            return f"COMMENT {comment}"
    3731
    3732        visible = expression.args.get("visible")
    3733        if visible is not None:
    3734            return "VISIBLE" if visible else "INVISIBLE"
    3735
    3736        engine_attr = self.sql(expression, "engine_attr")
    3737        if engine_attr:
    3738            return f"ENGINE_ATTRIBUTE = {engine_attr}"
    3739
    3740        secondary_engine_attr = self.sql(expression, "secondary_engine_attr")
    3741        if secondary_engine_attr:
    3742            return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}"
    3743
    3744        self.unsupported("Unsupported index constraint option.")
    3745        return ""

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

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

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

    3751    def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str:
    3752        kind = self.sql(expression, "kind")
    3753        kind = f"{kind} INDEX" if kind else "INDEX"
    3754        this = self.sql(expression, "this")
    3755        this = f" {this}" if this else ""
    3756        index_type = self.sql(expression, "index_type")
    3757        index_type = f" USING {index_type}" if index_type else ""
    3758        expressions = self.expressions(expression, flat=True)
    3759        expressions = f" ({expressions})" if expressions else ""
    3760        options = self.expressions(expression, key="options", sep=" ")
    3761        options = f" {options}" if options else ""
    3762        return f"{kind}{this}{index_type}{expressions}{options}"

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

    3764    def nvl2_sql(self, expression: exp.Nvl2) -> str:
    3765        if self.NVL2_SUPPORTED:
    3766            return self.function_fallback_sql(expression)
    3767
    3768        case = exp.Case().when(
    3769            expression.this.is_(exp.null()).not_(copy=False),
    3770            expression.args["true"],
    3771            copy=False,
    3772        )
    3773        else_cond = expression.args.get("false")
    3774        if else_cond:
    3775            case.else_(else_cond, copy=False)
    3776
    3777        return self.sql(case)

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

    3779    def comprehension_sql(self, expression: exp.Comprehension) -> str:
    3780        this = self.sql(expression, "this")
    3781        expr = self.sql(expression, "expression")
    3782        iterator = self.sql(expression, "iterator")
    3783        condition = self.sql(expression, "condition")
    3784        condition = f" IF {condition}" if condition else ""
    3785        return f"{this} FOR {expr} IN {iterator}{condition}"

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

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

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

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

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

    3793    def predict_sql(self, expression: exp.Predict) -> str:
    3794        model = self.sql(expression, "this")
    3795        model = f"MODEL {model}"
    3796        table = self.sql(expression, "expression")
    3797        table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table
    3798        parameters = self.sql(expression, "params_struct")
    3799        return self.func("PREDICT", model, table, parameters or None)

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

    3801    def forin_sql(self, expression: exp.ForIn) -> str:
    3802        this = self.sql(expression, "this")
    3803        expression_sql = self.sql(expression, "expression")
    3804        return f"FOR {this} DO {expression_sql}"

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

    3806    def refresh_sql(self, expression: exp.Refresh) -> str:
    3807        this = self.sql(expression, "this")
    3808        table = "" if isinstance(expression.this, exp.Literal) else "TABLE "
    3809        return f"REFRESH {table}{this}"

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

    3811    def toarray_sql(self, expression: exp.ToArray) -> str:
    3812        arg = expression.this
    3813        if not arg.type:
    3814            from sqlglot.optimizer.annotate_types import annotate_types
    3815
    3816            arg = annotate_types(arg)
    3817
    3818        if arg.is_type(exp.DataType.Type.ARRAY):
    3819            return self.sql(arg)
    3820
    3821        cond_for_null = arg.is_(exp.null())
    3822        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

    3824    def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str:
    3825        this = expression.this
    3826        if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME):
    3827            return self.sql(this)
    3828
    3829        return self.sql(exp.cast(this, exp.DataType.Type.TIME))

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

    3831    def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str:
    3832        this = expression.this
    3833        if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP):
    3834            return self.sql(this)
    3835
    3836        return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP))

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

    3838    def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str:
    3839        this = expression.this
    3840        time_format = self.format_time(expression)
    3841
    3842        if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT):
    3843            return self.sql(
    3844                exp.cast(
    3845                    exp.StrToTime(this=this, format=expression.args["format"]),
    3846                    exp.DataType.Type.DATE,
    3847                )
    3848            )
    3849
    3850        if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE):
    3851            return self.sql(this)
    3852
    3853        return self.sql(exp.cast(this, exp.DataType.Type.DATE))

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

    3855    def unixdate_sql(self, expression: exp.UnixDate) -> str:
    3856        return self.sql(
    3857            exp.func(
    3858                "DATEDIFF",
    3859                expression.this,
    3860                exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE),
    3861                "day",
    3862            )
    3863        )

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

    3865    def lastday_sql(self, expression: exp.LastDay) -> str:
    3866        if self.LAST_DAY_SUPPORTS_DATE_PART:
    3867            return self.function_fallback_sql(expression)
    3868
    3869        unit = expression.text("unit")
    3870        if unit and unit != "MONTH":
    3871            self.unsupported("Date parts are not supported in LAST_DAY.")
    3872
    3873        return self.func("LAST_DAY", expression.this)

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

    3875    def dateadd_sql(self, expression: exp.DateAdd) -> str:
    3876        from sqlglot.dialects.dialect import unit_to_str
    3877
    3878        return self.func(
    3879            "DATE_ADD", expression.this, expression.expression, unit_to_str(expression)
    3880        )

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

    3882    def arrayany_sql(self, expression: exp.ArrayAny) -> str:
    3883        if self.CAN_IMPLEMENT_ARRAY_ANY:
    3884            filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression)
    3885            filtered_not_empty = exp.ArraySize(this=filtered).neq(0)
    3886            original_is_empty = exp.ArraySize(this=expression.this).eq(0)
    3887            return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty)))
    3888
    3889        from sqlglot.dialects import Dialect
    3890
    3891        # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect
    3892        if self.dialect.__class__ != Dialect:
    3893            self.unsupported("ARRAY_ANY is unsupported")
    3894
    3895        return self.function_fallback_sql(expression)

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

    3897    def struct_sql(self, expression: exp.Struct) -> str:
    3898        expression.set(
    3899            "expressions",
    3900            [
    3901                exp.alias_(e.expression, e.name if e.this.is_string else e.this)
    3902                if isinstance(e, exp.PropertyEQ)
    3903                else e
    3904                for e in expression.expressions
    3905            ],
    3906        )
    3907
    3908        return self.function_fallback_sql(expression)

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

    3910    def partitionrange_sql(self, expression: exp.PartitionRange) -> str:
    3911        low = self.sql(expression, "this")
    3912        high = self.sql(expression, "expression")
    3913
    3914        return f"{low} TO {high}"

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

    3916    def truncatetable_sql(self, expression: exp.TruncateTable) -> str:
    3917        target = "DATABASE" if expression.args.get("is_database") else "TABLE"
    3918        tables = f" {self.expressions(expression)}"
    3919
    3920        exists = " IF EXISTS" if expression.args.get("exists") else ""
    3921
    3922        on_cluster = self.sql(expression, "cluster")
    3923        on_cluster = f" {on_cluster}" if on_cluster else ""
    3924
    3925        identity = self.sql(expression, "identity")
    3926        identity = f" {identity} IDENTITY" if identity else ""
    3927
    3928        option = self.sql(expression, "option")
    3929        option = f" {option}" if option else ""
    3930
    3931        partition = self.sql(expression, "partition")
    3932        partition = f" {partition}" if partition else ""
    3933
    3934        return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"

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

    3938    def convert_sql(self, expression: exp.Convert) -> str:
    3939        to = expression.this
    3940        value = expression.expression
    3941        style = expression.args.get("style")
    3942        safe = expression.args.get("safe")
    3943        strict = expression.args.get("strict")
    3944
    3945        if not to or not value:
    3946            return ""
    3947
    3948        # Retrieve length of datatype and override to default if not specified
    3949        if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    3950            to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False)
    3951
    3952        transformed: t.Optional[exp.Expression] = None
    3953        cast = exp.Cast if strict else exp.TryCast
    3954
    3955        # Check whether a conversion with format (T-SQL calls this 'style') is applicable
    3956        if isinstance(style, exp.Literal) and style.is_int:
    3957            from sqlglot.dialects.tsql import TSQL
    3958
    3959            style_value = style.name
    3960            converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value)
    3961            if not converted_style:
    3962                self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}")
    3963
    3964            fmt = exp.Literal.string(converted_style)
    3965
    3966            if to.this == exp.DataType.Type.DATE:
    3967                transformed = exp.StrToDate(this=value, format=fmt)
    3968            elif to.this == exp.DataType.Type.DATETIME:
    3969                transformed = exp.StrToTime(this=value, format=fmt)
    3970            elif to.this in self.PARAMETERIZABLE_TEXT_TYPES:
    3971                transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe)
    3972            elif to.this == exp.DataType.Type.TEXT:
    3973                transformed = exp.TimeToStr(this=value, format=fmt)
    3974
    3975        if not transformed:
    3976            transformed = cast(this=value, to=to, safe=safe)
    3977
    3978        return self.sql(transformed)

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

    4034    def copyparameter_sql(self, expression: exp.CopyParameter) -> str:
    4035        option = self.sql(expression, "this")
    4036
    4037        if expression.expressions:
    4038            upper = option.upper()
    4039
    4040            # Snowflake FILE_FORMAT options are separated by whitespace
    4041            sep = " " if upper == "FILE_FORMAT" else ", "
    4042
    4043            # Databricks copy/format options do not set their list of values with EQ
    4044            op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = "
    4045            values = self.expressions(expression, flat=True, sep=sep)
    4046            return f"{option}{op}({values})"
    4047
    4048        value = self.sql(expression, "expression")
    4049
    4050        if not value:
    4051            return option
    4052
    4053        op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " "
    4054
    4055        return f"{option}{op}{value}"

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

    4057    def credentials_sql(self, expression: exp.Credentials) -> str:
    4058        cred_expr = expression.args.get("credentials")
    4059        if isinstance(cred_expr, exp.Literal):
    4060            # Redshift case: CREDENTIALS <string>
    4061            credentials = self.sql(expression, "credentials")
    4062            credentials = f"CREDENTIALS {credentials}" if credentials else ""
    4063        else:
    4064            # Snowflake case: CREDENTIALS = (...)
    4065            credentials = self.expressions(expression, key="credentials", flat=True, sep=" ")
    4066            credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else ""
    4067
    4068        storage = self.sql(expression, "storage")
    4069        storage = f"STORAGE_INTEGRATION = {storage}" if storage else ""
    4070
    4071        encryption = self.expressions(expression, key="encryption", flat=True, sep=" ")
    4072        encryption = f" ENCRYPTION = ({encryption})" if encryption else ""
    4073
    4074        iam_role = self.sql(expression, "iam_role")
    4075        iam_role = f"IAM_ROLE {iam_role}" if iam_role else ""
    4076
    4077        region = self.sql(expression, "region")
    4078        region = f" REGION {region}" if region else ""
    4079
    4080        return f"{credentials}{storage}{encryption}{iam_role}{region}"

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

    4082    def copy_sql(self, expression: exp.Copy) -> str:
    4083        this = self.sql(expression, "this")
    4084        this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}"
    4085
    4086        credentials = self.sql(expression, "credentials")
    4087        credentials = self.seg(credentials) if credentials else ""
    4088        kind = self.seg("FROM" if expression.args.get("kind") else "TO")
    4089        files = self.expressions(expression, key="files", flat=True)
    4090
    4091        sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " "
    4092        params = self.expressions(
    4093            expression,
    4094            key="params",
    4095            sep=sep,
    4096            new_line=True,
    4097            skip_last=True,
    4098            skip_first=True,
    4099            indent=self.COPY_PARAMS_ARE_WRAPPED,
    4100        )
    4101
    4102        if params:
    4103            if self.COPY_PARAMS_ARE_WRAPPED:
    4104                params = f" WITH ({params})"
    4105            elif not self.pretty:
    4106                params = f" {params}"
    4107
    4108        return f"COPY{this}{kind} {files}{credentials}{params}"

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

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

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

    4113    def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str:
    4114        on_sql = "ON" if expression.args.get("on") else "OFF"
    4115        filter_col: t.Optional[str] = self.sql(expression, "filter_column")
    4116        filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None
    4117        retention_period: t.Optional[str] = self.sql(expression, "retention_period")
    4118        retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None
    4119
    4120        if filter_col or retention_period:
    4121            on_sql = self.func("ON", filter_col, retention_period)
    4122
    4123        return f"DATA_DELETION={on_sql}"

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

    4125    def maskingpolicycolumnconstraint_sql(
    4126        self, expression: exp.MaskingPolicyColumnConstraint
    4127    ) -> str:
    4128        this = self.sql(expression, "this")
    4129        expressions = self.expressions(expression, flat=True)
    4130        expressions = f" USING ({expressions})" if expressions else ""
    4131        return f"MASKING POLICY {this}{expressions}"

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

    4133    def gapfill_sql(self, expression: exp.GapFill) -> str:
    4134        this = self.sql(expression, "this")
    4135        this = f"TABLE {this}"
    4136        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

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

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

    4141    def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str:
    4142        this = self.sql(expression, "this")
    4143        expr = expression.expression
    4144
    4145        if isinstance(expr, exp.Func):
    4146            # T-SQL's CLR functions are case sensitive
    4147            expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})"
    4148        else:
    4149            expr = self.sql(expression, "expression")
    4150
    4151        return self.scope_resolution(expr, this)

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

    4153    def parsejson_sql(self, expression: exp.ParseJSON) -> str:
    4154        if self.PARSE_JSON_NAME is None:
    4155            return self.sql(expression.this)
    4156
    4157        return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression)

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

    4159    def rand_sql(self, expression: exp.Rand) -> str:
    4160        lower = self.sql(expression, "lower")
    4161        upper = self.sql(expression, "upper")
    4162
    4163        if lower and upper:
    4164            return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}"
    4165        return self.func("RAND", expression.this)

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

    4167    def changes_sql(self, expression: exp.Changes) -> str:
    4168        information = self.sql(expression, "information")
    4169        information = f"INFORMATION => {information}"
    4170        at_before = self.sql(expression, "at_before")
    4171        at_before = f"{self.seg('')}{at_before}" if at_before else ""
    4172        end = self.sql(expression, "end")
    4173        end = f"{self.seg('')}{end}" if end else ""
    4174
    4175        return f"CHANGES ({information}){at_before}{end}"

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

    4177    def pad_sql(self, expression: exp.Pad) -> str:
    4178        prefix = "L" if expression.args.get("is_left") else "R"
    4179
    4180        fill_pattern = self.sql(expression, "fill_pattern") or None
    4181        if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED:
    4182            fill_pattern = "' '"
    4183
    4184        return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)

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

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

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

    4190    def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str:
    4191        generate_series = exp.GenerateSeries(**expression.args)
    4192
    4193        parent = expression.parent
    4194        if isinstance(parent, (exp.Alias, exp.TableAlias)):
    4195            parent = parent.parent
    4196
    4197        if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)):
    4198            return self.sql(exp.Unnest(expressions=[generate_series]))
    4199
    4200        if isinstance(parent, exp.Select):
    4201            self.unsupported("GenerateSeries projection unnesting is not supported.")
    4202
    4203        return self.sql(generate_series)

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

    4205    def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str:
    4206        exprs = expression.expressions
    4207        if not self.ARRAY_CONCAT_IS_VAR_LEN:
    4208            rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs)
    4209        else:
    4210            rhs = self.expressions(expression)
    4211
    4212        return self.func(name, expression.this, rhs)

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

    4214    def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str:
    4215        if self.SUPPORTS_CONVERT_TIMEZONE:
    4216            return self.function_fallback_sql(expression)
    4217
    4218        source_tz = expression.args.get("source_tz")
    4219        target_tz = expression.args.get("target_tz")
    4220        timestamp = expression.args.get("timestamp")
    4221
    4222        if source_tz and timestamp:
    4223            timestamp = exp.AtTimeZone(
    4224                this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz
    4225            )
    4226
    4227        expr = exp.AtTimeZone(this=timestamp, zone=target_tz)
    4228
    4229        return self.sql(expr)

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

    4231    def json_sql(self, expression: exp.JSON) -> str:
    4232        this = self.sql(expression, "this")
    4233        this = f" {this}" if this else ""
    4234
    4235        _with = expression.args.get("with")
    4236
    4237        if _with is None:
    4238            with_sql = ""
    4239        elif not _with:
    4240            with_sql = " WITHOUT"
    4241        else:
    4242            with_sql = " WITH"
    4243
    4244        unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else ""
    4245
    4246        return f"JSON{this}{with_sql}{unique_sql}"

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

    4248    def jsonvalue_sql(self, expression: exp.JSONValue) -> str:
    4249        def _generate_on_options(arg: t.Any) -> str:
    4250            return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}"
    4251
    4252        path = self.sql(expression, "path")
    4253        returning = self.sql(expression, "returning")
    4254        returning = f" RETURNING {returning}" if returning else ""
    4255
    4256        on_condition = self.sql(expression, "on_condition")
    4257        on_condition = f" {on_condition}" if on_condition else ""
    4258
    4259        return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}")

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

    4261    def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str:
    4262        else_ = "ELSE " if expression.args.get("else_") else ""
    4263        condition = self.sql(expression, "expression")
    4264        condition = f"WHEN {condition} THEN " if condition else else_
    4265        insert = self.sql(expression, "this")[len("INSERT") :].strip()
    4266        return f"{condition}{insert}"

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

    4268    def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str:
    4269        kind = self.sql(expression, "kind")
    4270        expressions = self.seg(self.expressions(expression, sep=" "))
    4271        res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}"
    4272        return res

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

    4274    def oncondition_sql(self, expression: exp.OnCondition) -> str:
    4275        # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR"
    4276        empty = expression.args.get("empty")
    4277        empty = (
    4278            f"DEFAULT {empty} ON EMPTY"
    4279            if isinstance(empty, exp.Expression)
    4280            else self.sql(expression, "empty")
    4281        )
    4282
    4283        error = expression.args.get("error")
    4284        error = (
    4285            f"DEFAULT {error} ON ERROR"
    4286            if isinstance(error, exp.Expression)
    4287            else self.sql(expression, "error")
    4288        )
    4289
    4290        if error and empty:
    4291            error = (
    4292                f"{empty} {error}"
    4293                if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR
    4294                else f"{error} {empty}"
    4295            )
    4296            empty = ""
    4297
    4298        null = self.sql(expression, "null")
    4299
    4300        return f"{empty}{error}{null}"

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

    4302    def jsonexists_sql(self, expression: exp.JSONExists) -> str:
    4303        this = self.sql(expression, "this")
    4304        path = self.sql(expression, "path")
    4305
    4306        passing = self.expressions(expression, "passing")
    4307        passing = f" PASSING {passing}" if passing else ""
    4308
    4309        on_condition = self.sql(expression, "on_condition")
    4310        on_condition = f" {on_condition}" if on_condition else ""
    4311
    4312        path = f"{path}{passing}{on_condition}"
    4313
    4314        return self.func("JSON_EXISTS", this, path)

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

    4316    def arrayagg_sql(self, expression: exp.ArrayAgg) -> str:
    4317        array_agg = self.function_fallback_sql(expression)
    4318
    4319        if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"):
    4320            parent = expression.parent
    4321            if isinstance(parent, exp.Filter):
    4322                parent_cond = parent.expression.this
    4323                parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_()))
    4324            else:
    4325                array_agg = f"{array_agg} FILTER(WHERE {self.sql(expression, 'this')} IS NOT NULL)"
    4326
    4327        return array_agg